diff --git a/.changeset/claude-charts-plugin.md b/.changeset/claude-charts-plugin.md new file mode 100644 index 0000000000..e0744e9e6a --- /dev/null +++ b/.changeset/claude-charts-plugin.md @@ -0,0 +1,8 @@ +--- +'@hyperdx/claude-plugin': minor +--- + +feat: add a Claude Code plugin that connects the ClickStack MCP server and draws +`clickstack_timeseries` and `clickstack_table` results as terminal charts, using +the CLI's renderers. Install with +`/plugin install hyperdx-charts --marketplace hyperdxio/hyperdx`. diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000000..d4ff9bd48f --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,11 @@ +{ + "name": "hyperdx", + "owner": { "name": "HyperDX" }, + "plugins": [ + { + "name": "hyperdx-charts", + "description": "Draws ClickStack MCP query results as terminal charts in Claude Code", + "source": { "source": "npm", "package": "@hyperdx/claude-plugin" } + } + ] +} diff --git a/AGENTS.md b/AGENTS.md index 9e5653ec04..fb3d5029b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ schema-agnostic design, and correlation across all telemetry types in one place. ## Architecture (WHAT) -This is a **monorepo** with six packages: +This is a **monorepo** with seven packages: - `packages/app` - Next.js frontend (TypeScript, Mantine UI, TanStack Query) - `packages/api` - Express backend (Node.js 22+, MongoDB for metadata, @@ -23,6 +23,9 @@ This is a **monorepo** with six packages: tailing, and inspecting logs and traces (Ink/React). Has its own [`AGENTS.md`](packages/cli/AGENTS.md) with detailed architecture and keybindings. +- `packages/claude-plugin` - Claude Code plugin that draws ClickStack MCP + query results as terminal charts, using the CLI's chart renderers. See its + [`README.md`](packages/claude-plugin/README.md). - `packages/otel-collector` - Custom-built OpenTelemetry Collector (Go, OCB). See its [`README.md`](packages/otel-collector/README.md) for architecture, included components, and upgrade procedures. diff --git a/MCP.md b/MCP.md index 132a7a9d79..2065874d08 100644 --- a/MCP.md +++ b/MCP.md @@ -45,6 +45,14 @@ claude mcp add --transport http clickstack /api/mcp \ --header "Authorization: Bearer " ``` +Or install the [charts plugin](packages/claude-plugin/README.md) instead: it +connects the same server (asking for your URL and key) and draws query results +as charts in the terminal instead of JSON: + +``` +/plugin install hyperdx-charts --marketplace hyperdxio/hyperdx +``` + ### Codex CLI The Codex CLI reads the bearer token from an environment variable rather than a diff --git a/knip.json b/knip.json index 7d88c3d288..9b9601221d 100644 --- a/knip.json +++ b/knip.json @@ -33,6 +33,10 @@ "ignoreDependencies": ["@stryker-mutator/core"], "ignoreBinaries": ["stryker"] }, + "packages/claude-plugin": { + "project": ["src/**/*.ts"], + "ignoreBinaries": ["claude"] + }, "packages/hdx-eval": { "project": ["src/**/*.ts"], "ignoreDependencies": ["tsx"], diff --git a/packages/claude-plugin/.claude-plugin/plugin.json b/packages/claude-plugin/.claude-plugin/plugin.json new file mode 100644 index 0000000000..da6b61f8b2 --- /dev/null +++ b/packages/claude-plugin/.claude-plugin/plugin.json @@ -0,0 +1,34 @@ +{ + "name": "hyperdx-charts", + "description": "Draws ClickStack MCP query results as terminal charts in Claude Code", + "author": { + "name": "HyperDX" + }, + "homepage": "https://github.com/hyperdxio/hyperdx/tree/main/packages/claude-plugin", + "license": "MIT", + "types": "./types/index.d.ts", + "userConfig": { + "hyperdx_url": { + "type": "string", + "title": "HyperDX URL", + "description": "Your HyperDX address, e.g. https://hyperdx.example.com (no trailing slash).", + "required": true + }, + "access_key": { + "type": "string", + "title": "Personal API access key", + "description": "From Team Settings > API keys in HyperDX. Kept in secure storage.", + "required": true, + "sensitive": true + } + }, + "mcpServers": { + "clickstack": { + "type": "http", + "url": "${user_config.hyperdx_url}/api/mcp", + "headers": { + "Authorization": "Bearer ${user_config.access_key}" + } + } + } +} diff --git a/packages/claude-plugin/.gitignore b/packages/claude-plugin/.gitignore new file mode 100644 index 0000000000..37914d9e6f --- /dev/null +++ b/packages/claude-plugin/.gitignore @@ -0,0 +1,2 @@ +hooks/chart.js +.claude-plugin/types/ diff --git a/packages/claude-plugin/README.md b/packages/claude-plugin/README.md new file mode 100644 index 0000000000..da84395e5c --- /dev/null +++ b/packages/claude-plugin/README.md @@ -0,0 +1,49 @@ +# @hyperdx/claude-plugin + +A Claude Code plugin that draws ClickStack MCP query results as charts in the +terminal. When Claude runs `clickstack_timeseries` or `clickstack_table`, the +tool row shows a line, stacked bar, bar, pie, number or table chart in place of +the raw JSON. Claude still reads the full result. + +Charts are drawn by the same renderers as the `hdx` CLI, so a query looks the +same in both. + +## Install + +At a Claude Code prompt: + +``` +/plugin install hyperdx-charts --marketplace hyperdxio/hyperdx +``` + +Answer `y` to add the marketplace and pick a scope. The plugin asks for your +HyperDX URL and your personal API access key (Team Settings > API keys), then +connects the ClickStack MCP server for you, so there is no separate +`claude mcp add` step. If you already added the server yourself, remove it with +`claude mcp remove clickstack` to avoid two copies of every tool. The bundled +server's tools are named `mcp__plugin_hyperdx-charts_clickstack__*`, so update +any permission rules that name `mcp__clickstack__*`. Charts stay off until both +values are set; `/plugin configure hyperdx-charts` sets them later. + +## Limits + +- Terminal only. Desktop and IDE surfaces keep the normal tool row. +- Results too large for Claude's context are replaced by a file pointer before + the plugin sees them, so they are not charted. Ask for a coarser + `granularity`. +- The Claude Code plugin API this uses is early access and may change between + releases. + +## Development + +```bash +yarn build # bundle src/ into hooks/chart.js +yarn ci:unit # jest, src/__tests__/*.spec.ts +claude plugin test . # engine tests, test/*.test.tsx +claude plugin validate . +claude --plugin-dir . # run Claude Code with the plugin loaded +``` + +`hooks/register.tsx` is compiled by Claude Code and must stay readable to +`claude plugin validate`, so only the renderer is bundled. The bundle must stay +under the 1 MiB hooks module limit; `tsup.config.ts` explains how. diff --git a/packages/claude-plugin/eslint.config.mjs b/packages/claude-plugin/eslint.config.mjs new file mode 100644 index 0000000000..ab4bc80838 --- /dev/null +++ b/packages/claude-plugin/eslint.config.mjs @@ -0,0 +1,47 @@ +import js from '@eslint/js'; +import tseslint from 'typescript-eslint'; +import prettierConfig from 'eslint-config-prettier'; +import prettierPlugin from 'eslint-plugin-prettier'; + +export default [ + js.configs.recommended, + ...tseslint.configs.recommended, + prettierConfig, + { + // hooks/register.tsx and test/ are typed against the API Claude Code writes + // at load time; `claude plugin validate` and `claude plugin test` check them. + ignores: [ + 'node_modules/**', + '.claude-plugin/**', + 'hooks/**', + 'test/**', + '**/*.config.cjs', + '**/*.config.mjs', + '**/*.config.ts', + ], + }, + { + files: ['src/**/*.ts', 'types/**/*.ts'], + plugins: { + '@typescript-eslint': tseslint.plugin, + prettier: prettierPlugin, + }, + rules: { + '@typescript-eslint/ban-ts-comment': 'error', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, + ], + 'prettier/prettier': 'error', + }, + languageOptions: { + parser: tseslint.parser, + parserOptions: { + ecmaVersion: 'latest', + sourceType: 'module', + project: './tsconfig.json', + tsconfigRootDir: import.meta.dirname, + }, + }, + }, +]; diff --git a/packages/claude-plugin/hooks/chart.d.ts b/packages/claude-plugin/hooks/chart.d.ts new file mode 100644 index 0000000000..94e6b16a98 --- /dev/null +++ b/packages/claude-plugin/hooks/chart.d.ts @@ -0,0 +1,17 @@ +// Types for the bundled hooks/chart.js. The published package ships without src/, +// so these are written out; src/__tests__/chartTypes.spec.ts keeps them in step. +import type { ChartCall } from '../types'; + +export type Segment = { + text: string; + color?: string; + dim?: boolean; + bold?: boolean; +}; + +export function chartedTool(toolName: string): string | undefined; +export function renderChart( + call: ChartCall, + columns: number, +): Segment[][] | undefined; +export function stripControlChars(text: string): string; diff --git a/packages/claude-plugin/hooks/hooks.json b/packages/claude-plugin/hooks/hooks.json new file mode 100644 index 0000000000..5a63f64959 --- /dev/null +++ b/packages/claude-plugin/hooks/hooks.json @@ -0,0 +1 @@ +{ "modules": ["./register.tsx"] } diff --git a/packages/claude-plugin/hooks/register.tsx b/packages/claude-plugin/hooks/register.tsx new file mode 100644 index 0000000000..40e0cb7d53 --- /dev/null +++ b/packages/claude-plugin/hooks/register.tsx @@ -0,0 +1,130 @@ +import { atom, read, update } from 'claude-code'; +import type { + EngineInterface, + Register, + RenderElement, + RenderInput, +} from 'claude-code'; + +import type { ChartCall } from '../types'; + +import { chartedTool, renderChart, stripControlChars } from './chart.js'; + +const KEEP = 20; +const MAX_COLUMNS = 140; +const calls = atom({ plugin: 'hyperdx-charts', key: 'calls' } as const, {}); + +type Row = { id: string; tool: string; input: unknown }; + +function chartTree( + $: EngineInterface, + e: RenderInput, + row: Row, + call: ChartCall, +): RenderElement | undefined { + const columns = Math.min( + MAX_COLUMNS, + Math.max(40, (e.viewport?.columns ?? 80) - 6), + ); + const lines = renderChart(call, columns); + if (!lines) return undefined; + const { Box, Text } = $.ui.resolve(e); + const reason = (row.input as { reason?: unknown } | undefined)?.reason; + return ( + + + {stripControlChars(row.tool.split('__').pop() ?? '')} + {typeof reason === 'string' && ( + {stripControlChars(reason)} + )} + + {lines.map((segments, i) => ( + + {segments.length === 0 + ? ' ' + : segments.map((s, j) => ( + + {s.text} + + ))} + + ))} + + ); +} + +// Charted rows replace the engine's row and its JSON; the model still reads the full result. +async function drawRows( + $: EngineInterface, + e: RenderInput, + next: () => Promise, + rows: Row[], + isEveryRowCharted: boolean, +) { + if (e.surface !== 'terminal' || rows.length === 0) return next(); + const stored = await read($, calls); + const drawn = rows.flatMap(row => { + const call = stored[row.id]; + return (call && chartTree($, e, row, call)) || []; + }); + if (drawn.length === 0) return next(); + const { Box } = $.ui.resolve(e); + return ( + + {!(isEveryRowCharted && drawn.length === rows.length) && (await next())} + {drawn} + + ); +} + +export const register: Register = on => { + on('tool.call', async ($, e, next) => { + // The server fixes its default window before the query runs. + const calledAt = Date.now(); + const ran = await next(e); + if (!chartedTool(e.tool) || ran.deny !== undefined || ran.isError) + return ran; + const call: ChartCall = { + tool: e.tool, + input: e, + output: ran.result, + calledAt, + }; + // Chart bookkeeping must never fail the call it watched. + try { + await update($, calls, all => + Object.fromEntries( + [...Object.entries(all), [e.tool_use_id, call]].slice(-KEEP), + ), + ); + } catch { + // The row keeps the engine's own rendering. + } + return ran; + }).catch(($, e, next) => next(e)); + + // MCP calls draw as a collapsed group line; an expanded group draws its rows, which chart themselves. + on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => { + const rows = e.props.isExpanded + ? [] + : e.props.calls.flatMap(c => + chartedTool(c.tool) && c.tool_use_id + ? [{ id: c.tool_use_id, tool: c.tool, input: c.input }] + : [], + ); + return drawRows( + $, + e, + () => next(e), + rows, + rows.length === e.props.calls.length, + ); + }); + + on('ui.render', { component: 'ToolUse' }, async ($, e, next) => { + const rows = chartedTool(e.props.tool) + ? [{ id: e.props.tool_use_id, tool: e.props.tool, input: e.props.input }] + : []; + return drawRows($, e, () => next(e), rows, true); + }); +}; diff --git a/packages/claude-plugin/jest.config.cjs b/packages/claude-plugin/jest.config.cjs new file mode 100644 index 0000000000..f40134ba72 --- /dev/null +++ b/packages/claude-plugin/jest.config.cjs @@ -0,0 +1,17 @@ +/** @type {import("jest").Config} **/ +module.exports = { + preset: 'ts-jest/presets/default-esm', + testEnvironment: 'node', + extensionsToTreatAsEsm: ['.ts'], + rootDir: './src', + // *.test.ts(x) belong to `claude plugin test`, which runs every such file in the folder. + testMatch: ['**/__tests__/*.spec.ts'], + moduleNameMapper: { + // The CLI source this package renders with resolves its own `@/` alias. + '^@/(.*)$': '/../../cli/src/$1', + '^(\\.{1,2}/.*)\\.js$': '$1', + }, + transform: { + '^.+\\.tsx?$': ['ts-jest', { useESM: true }], + }, +}; diff --git a/packages/claude-plugin/package.json b/packages/claude-plugin/package.json new file mode 100644 index 0000000000..541850191e --- /dev/null +++ b/packages/claude-plugin/package.json @@ -0,0 +1,44 @@ +{ + "name": "@hyperdx/claude-plugin", + "version": "0.0.0", + "description": "Claude Code plugin that draws ClickStack MCP query results as terminal charts", + "license": "MIT", + "type": "module", + "repository": { + "type": "git", + "url": "git+https://github.com/hyperdxio/hyperdx.git", + "directory": "packages/claude-plugin" + }, + "homepage": "https://github.com/hyperdxio/hyperdx/tree/main/packages/claude-plugin#readme", + "publishConfig": { + "access": "public" + }, + "files": [ + ".claude-plugin/plugin.json", + "hooks/*", + "types/*", + "README.md" + ], + "scripts": { + "build": "tsup", + "prepublishOnly": "yarn build", + "validate": "claude plugin validate .", + "lint": "npx eslint . --max-warnings 0", + "lint:fix": "npx eslint . --fix", + "ci:build": "tsup", + "ci:lint": "yarn lint && yarn tsc --noEmit", + "ci:unit": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand --ci", + "dev:unit": "NODE_OPTIONS=--experimental-vm-modules jest --watchAll --runInBand" + }, + "devDependencies": { + "@hyperdx/cli": "workspace:*", + "@hyperdx/common-utils": "^0.31.0", + "@jest/globals": "^30.2.0", + "@types/jest": "^29.5.14", + "chalk": "^5.3.0", + "jest": "^30.2.0", + "ts-jest": "^29.4.11", + "tsup": "^8.4.0", + "typescript": "^6.0.3" + } +} diff --git a/packages/claude-plugin/src/__tests__/ansiLines.spec.ts b/packages/claude-plugin/src/__tests__/ansiLines.spec.ts new file mode 100644 index 0000000000..94eb8fade2 --- /dev/null +++ b/packages/claude-plugin/src/__tests__/ansiLines.spec.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from '@jest/globals'; + +import { ansiLines, stripControlChars } from '../ansiLines'; + +describe('ansiLines', () => { + it('splits lines and carries basic SGR styles across segments', () => { + expect( + ansiLines( + '\x1b[34m╭─\x1b[39m plain\n\x1b[2m11:00\x1b[22m \x1b[91m●\x1b[0m api', + ), + ).toEqual([ + [{ text: '╭─', color: 'blue' }, { text: ' plain' }], + [ + { text: '11:00', dim: true }, + { text: ' ' }, + { text: '●', color: 'redBright' }, + { text: ' api' }, + ], + ]); + }); + + it('keeps empty lines so the chart keeps its height', () => { + expect(ansiLines('a\n\nb')).toEqual([[{ text: 'a' }], [], [{ text: 'b' }]]); + }); + + it('drops escape sequences that are not colour codes', () => { + const osc = `\x1b]0;pwned\x07`; + expect(ansiLines(`\x1b[34mapi${osc}\x1b[39m \x1b[2Jdone`)).toEqual([ + [{ text: 'api]0;pwned', color: 'blue' }, { text: ' [2Jdone' }], + ]); + }); + + it('drops C1 controls, DEL and bidi overrides but keeps printable Unicode', () => { + expect(stripControlChars('a\u009b2Jb\u007fc\u202eé ● 😀')).toBe( + 'a2Jbcé ● 😀', + ); + }); +}); diff --git a/packages/claude-plugin/src/__tests__/chartTypes.spec.ts b/packages/claude-plugin/src/__tests__/chartTypes.spec.ts new file mode 100644 index 0000000000..bd507294d4 --- /dev/null +++ b/packages/claude-plugin/src/__tests__/chartTypes.spec.ts @@ -0,0 +1,11 @@ +import { expect, it } from '@jest/globals'; + +import type * as Published from '../../hooks/chart'; +import * as Source from '../index'; + +// Fails to compile when hooks/chart.d.ts drifts from what src/index.ts exports. +const published: typeof Published = Source; + +it('keeps the published chart types in step with the source', () => { + expect(published).toBe(Source); +}); diff --git a/packages/claude-plugin/src/__tests__/renderChart.spec.ts b/packages/claude-plugin/src/__tests__/renderChart.spec.ts new file mode 100644 index 0000000000..5cfc860b97 --- /dev/null +++ b/packages/claude-plugin/src/__tests__/renderChart.spec.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from '@jest/globals'; + +import { renderChart } from '../renderChart'; + +const result = { + meta: [ + { name: 'Spans', type: 'UInt64' }, + { name: '__hdx_time_bucket', type: 'DateTime' }, + ], + data: [ + { Spans: '1', __hdx_time_bucket: '2026-10-13T00:00:00Z' }, + { Spans: '4', __hdx_time_bucket: '2026-10-13T00:05:00Z' }, + ], +}; +const call = (body: object) => ({ + tool: 'mcp__clickstack__clickstack_timeseries', + input: { granularity: '5 minute' }, + output: [{ type: 'text', text: JSON.stringify(body) }], + calledAt: Date.parse('2026-10-13T00:10:00Z'), +}); + +describe('renderChart', () => { + it('ends a trimmed result with a dim note, and only a trimmed one', () => { + const trimmed = renderChart( + call({ result, note: 'Result was trimmed' }), + 80, + ); + expect(trimmed?.at(-1)).toEqual([ + { text: expect.stringContaining('trimmed'), dim: true }, + ]); + const whole = renderChart(call({ result }), 80); + expect(whole?.at(-1)?.[0]?.text ?? '').not.toContain('trimmed'); + }); +}); diff --git a/packages/claude-plugin/src/__tests__/toTileResult.spec.ts b/packages/claude-plugin/src/__tests__/toTileResult.spec.ts new file mode 100644 index 0000000000..e3cd5665de --- /dev/null +++ b/packages/claude-plugin/src/__tests__/toTileResult.spec.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from '@jest/globals'; +import { DisplayType } from '@hyperdx/common-utils/dist/types'; + +import { + chartedTool, + isTrimmed, + parseResponse, + toTileResult, +} from '../toTileResult'; + +const response = { + meta: [ + { name: 'Spans', type: 'UInt64' }, + { name: '__hdx_time_bucket', type: 'DateTime' }, + ], + data: [ + { Spans: '1', __hdx_time_bucket: '2026-10-13T00:00:00Z' }, + { Spans: '4', __hdx_time_bucket: '2026-10-13T00:05:00Z' }, + ], +}; +const output = [ + { + type: 'text', + text: JSON.stringify({ result: response, notebookUrl: 'x' }), + }, +]; +const calledAt = Date.parse('2026-10-13T01:00:00Z'); + +describe('chartedTool', () => { + it('matches the builder tools whatever the MCP server is named', () => { + expect(chartedTool('mcp__clickstack__clickstack_timeseries')).toBe( + 'clickstack_timeseries', + ); + expect(chartedTool('mcp__my-hdx__clickstack_table')).toBe( + 'clickstack_table', + ); + expect(chartedTool('mcp__clickstack__clickstack_search')).toBeUndefined(); + }); +}); + +describe('parseResponse', () => { + it('reads the result from MCP text blocks', () => { + expect(parseResponse(output)).toEqual(response); + expect(parseResponse({ content: output })).toEqual(response); + }); + + it('ignores errors and non-JSON output', () => { + expect( + parseResponse([{ type: 'text', text: 'Error: bad query' }]), + ).toBeUndefined(); + expect(parseResponse('not blocks')).toBeUndefined(); + }); +}); + +describe('toTileResult', () => { + it('maps the tool shape to a display type and keeps the requested window', () => { + const result = toTileResult( + 'mcp__clickstack__clickstack_timeseries', + { + shape: 'stacked_bar', + granularity: '5 minute', + startTime: '2026-10-13T00:00:00Z', + endTime: '2026-10-13T00:10:00Z', + }, + output, + calledAt, + ); + expect(result?.queriedConfig).toMatchObject({ + displayType: DisplayType.StackedBar, + granularity: '5 minute', + dateRange: [ + new Date('2026-10-13T00:00:00Z'), + new Date('2026-10-13T00:10:00Z'), + ], + }); + }); + + it('defaults to the server defaults: line and the last 15 minutes', () => { + const result = toTileResult( + 'mcp__clickstack__clickstack_timeseries', + {}, + output, + calledAt, + ); + expect(result?.queriedConfig).toMatchObject({ + displayType: DisplayType.Line, + dateRange: [new Date('2026-10-13T00:45:00Z'), new Date(calledAt)], + }); + }); + + it('fills empty buckets only for an explicit granularity on a whole result', () => { + const run = (input: object, out: unknown) => + toTileResult( + 'mcp__clickstack__clickstack_timeseries', + input, + out, + calledAt, + )?.queriedConfig; + const trimmed = [ + { + type: 'text', + text: JSON.stringify({ result: response, note: 'Result was trimmed' }), + }, + ]; + expect(run({}, output)).toMatchObject({ fillNulls: false }); + expect(run({ granularity: '5 minute' }, trimmed)).toMatchObject({ + fillNulls: false, + }); + expect(run({ granularity: '5 minute' }, output)?.fillNulls).toBeUndefined(); + }); + + it('follows the server turning multi-select number, pie and bar into a table', () => { + for (const shape of ['number', 'pie', 'bar']) { + const result = toTileResult( + 'mcp__clickstack__clickstack_table', + { shape, select: [{ aggFn: 'count' }, { aggFn: 'max' }] }, + output, + calledAt, + ); + expect(result?.queriedConfig.displayType).toBe(DisplayType.Table); + } + }); + + it('keeps a single-select number chart and a multi-select table as asked', () => { + const shapeOf = (input: object) => + toTileResult('mcp__clickstack__clickstack_table', input, output, calledAt) + ?.queriedConfig.displayType; + expect(shapeOf({ shape: 'number', select: [{ aggFn: 'count' }] })).toBe( + DisplayType.Number, + ); + expect( + shapeOf({ + shape: 'table', + select: [{ aggFn: 'count' }, { aggFn: 'max' }], + }), + ).toBe(DisplayType.Table); + }); + + it('notices a trimmed result', () => { + expect(isTrimmed(output)).toBe(false); + expect( + isTrimmed([ + { type: 'text', text: JSON.stringify({ result: response, note: 'x' }) }, + ]), + ).toBe(true); + }); + + it('skips empty results and shapes it does not know', () => { + const empty = [ + { + type: 'text', + text: JSON.stringify({ result: { ...response, data: [] } }), + }, + ]; + expect( + toTileResult( + 'mcp__clickstack__clickstack_timeseries', + {}, + empty, + calledAt, + ), + ).toBeUndefined(); + expect( + toTileResult( + 'mcp__clickstack__clickstack_table', + { shape: 'heatmap' }, + output, + calledAt, + ), + ).toBeUndefined(); + }); +}); diff --git a/packages/claude-plugin/src/ansiLines.ts b/packages/claude-plugin/src/ansiLines.ts new file mode 100644 index 0000000000..f3f0d80bcb --- /dev/null +++ b/packages/claude-plugin/src/ansiLines.ts @@ -0,0 +1,72 @@ +export type Segment = { + text: string; + color?: string; + dim?: boolean; + bold?: boolean; +}; + +const BASE = [ + 'black', + 'red', + 'green', + 'yellow', + 'blue', + 'magenta', + 'cyan', + 'white', +]; +// Built from a string so the ESC character isn't a literal control char in a regex. +const SGR = new RegExp(`${String.fromCharCode(27)}\\[([0-9;]*)m`, 'g'); + +function colorFor(code: number): string | undefined { + if (code >= 30 && code <= 37) return BASE[code - 30]; + if (code >= 90 && code <= 97) + return code === 90 ? 'gray' : `${BASE[code - 90]}Bright`; + return undefined; +} + +// Chart text carries user data (service names, log fields). Keep it from controlling +// the terminal (C0/C1 controls) or reordering what is shown (bidi overrides). +export function stripControlChars(text: string): string { + return [...text] + .filter(c => { + const code = c.codePointAt(0)!; + const isControl = code < 0x20 || (code >= 0x7f && code < 0xa0); + const isBidi = + (code >= 0x202a && code <= 0x202e) || + (code >= 0x2066 && code <= 0x2069); + return !isControl && !isBidi; + }) + .join(''); +} + +/** + * Splits termchart's output into styled segments per line. termchart runs at + * chalk level 1 here, so only basic SGR codes need handling. + */ +export function ansiLines(ansi: string): Segment[][] { + let style: Omit = {}; + return ansi.split('\n').map(line => { + const segments: Segment[] = []; + let last = 0; + const push = (raw: string) => { + const text = stripControlChars(raw); + if (text) segments.push({ text, ...style }); + }; + for (const match of line.matchAll(SGR)) { + push(line.slice(last, match.index)); + last = match.index + match[0].length; + for (const code of (match[1] || '0').split(';').map(Number)) { + if (code === 0) style = {}; + else if (code === 1) style = { ...style, bold: true }; + else if (code === 2) style = { ...style, dim: true }; + else if (code === 22) + style = { ...style, bold: undefined, dim: undefined }; + else if (code === 39) style = { ...style, color: undefined }; + else if (colorFor(code)) style = { ...style, color: colorFor(code) }; + } + } + push(line.slice(last)); + return segments; + }); +} diff --git a/packages/claude-plugin/src/chalk.ts b/packages/claude-plugin/src/chalk.ts new file mode 100644 index 0000000000..96be59d121 --- /dev/null +++ b/packages/claude-plugin/src/chalk.ts @@ -0,0 +1,5 @@ +import { Chalk } from 'chalk'; + +// The hooks environment has no TTY for chalk to detect; level 1 keeps termchart's +// colors to the basic SGR codes ansiLines reads. +export default new Chalk({ level: 1 }); diff --git a/packages/claude-plugin/src/index.ts b/packages/claude-plugin/src/index.ts new file mode 100644 index 0000000000..d627d028bb --- /dev/null +++ b/packages/claude-plugin/src/index.ts @@ -0,0 +1,3 @@ +export { stripControlChars } from './ansiLines'; +export { renderChart } from './renderChart'; +export { chartedTool } from './toTileResult'; diff --git a/packages/claude-plugin/src/renderChart.ts b/packages/claude-plugin/src/renderChart.ts new file mode 100644 index 0000000000..c1f991f268 --- /dev/null +++ b/packages/claude-plugin/src/renderChart.ts @@ -0,0 +1,47 @@ +import { renderTileContent } from '@hyperdx/cli/src/shared/tileRender'; +import { isTimeSeriesDisplayType } from '@hyperdx/common-utils/dist/core/utils'; +import { DisplayType } from '@hyperdx/common-utils/dist/types'; + +import type { ChartCall } from '../types'; + +import { ansiLines, type Segment } from './ansiLines'; +import { isTrimmed, toTileResult } from './toTileResult'; + +const TIME_CHART_ROWS = 14; +const MAX_TABLE_ROWS = 20; +const TRIMMED_NOTE = + 'The server trimmed this result to fit its size limit; the chart shows only the rows it returned.'; + +/** Draws a clickstack tool result with the same renderer as `hdx`, or undefined when it can't be charted. */ +export function renderChart( + call: ChartCall, + columns: number, +): Segment[][] | undefined { + const result = toTileResult( + call.tool, + call.input, + call.output, + call.calledAt, + ); + if (!result) return undefined; + + const { displayType } = result.queriedConfig; + const height = + displayType === DisplayType.Number + ? 3 + : isTimeSeriesDisplayType(displayType) + ? TIME_CHART_ROWS + : Math.min(result.data.data.length + 2, MAX_TABLE_ROWS); + + try { + const lines = ansiLines( + renderTileContent({ result, source: undefined, width: columns, height }), + ); + return isTrimmed(call.output) + ? [...lines, [{ text: TRIMMED_NOTE, dim: true }]] + : lines; + } catch { + // A result the shaping can't read (no timestamp or value column) keeps the engine's own row. + return undefined; + } +} diff --git a/packages/claude-plugin/src/toTileResult.ts b/packages/claude-plugin/src/toTileResult.ts new file mode 100644 index 0000000000..b68a77fbb4 --- /dev/null +++ b/packages/claude-plugin/src/toTileResult.ts @@ -0,0 +1,112 @@ +import type { ResponseJSON } from '@hyperdx/common-utils/dist/clickhouse'; +import type { ChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types'; +import { TIME_SERIES_DISPLAY_TYPE_BY_NAME } from '@hyperdx/common-utils/dist/core/utils'; +import { DisplayType } from '@hyperdx/common-utils/dist/types'; +import type { TileQueryResult } from '@hyperdx/cli/src/shared/tileQuery'; + +const DEFAULT_WINDOW_MS = 15 * 60 * 1000; +// clickstack_table turns these into a table when given more than one select item. +const SINGLE_SERIES_SHAPES = ['number', 'pie', 'bar']; + +// Builder tools whose shape input picks the chart. +const DISPLAY_TYPES: Record> = { + clickstack_timeseries: TIME_SERIES_DISPLAY_TYPE_BY_NAME, + clickstack_table: { + table: DisplayType.Table, + number: DisplayType.Number, + pie: DisplayType.Pie, + bar: DisplayType.Bar, + }, +}; + +type ToolInput = { + shape?: string; + select?: unknown[]; + groupBy?: string; + granularity?: string; + startTime?: string; + endTime?: string; +}; + +type ChartResult = Extract; + +/** Matches by MCP tool name suffix, so it works whatever the user named the server. */ +export function chartedTool(toolName: string): string | undefined { + const suffix = toolName.split('__').pop() ?? ''; + return suffix in DISPLAY_TYPES ? suffix : undefined; +} + +/** MCP output arrives as text blocks holding one JSON document. */ +function parseBody(output: unknown): Record | undefined { + const blocks = Array.isArray(output) + ? output + : (output as { content?: unknown })?.content; + if (!Array.isArray(blocks)) return undefined; + const text = blocks.map(b => (b as { text?: unknown })?.text ?? '').join(''); + try { + const body = JSON.parse(text); + return body && typeof body === 'object' ? body : undefined; + } catch { + return undefined; + } +} + +/** The server trims results over its size limit and says so in `note`. */ +export function isTrimmed(output: unknown): boolean { + return typeof parseBody(output)?.note === 'string'; +} + +/** The builder tools answer `{ result: ResponseJSON, ... }`. */ +export function parseResponse( + output: unknown, +): ResponseJSON> | undefined { + const result = parseBody(output)?.result as ResponseJSON | undefined; + return Array.isArray(result?.meta) && Array.isArray(result?.data) + ? (result as ResponseJSON>) + : undefined; +} + +/** + * Rebuilds what the server queried from the tool call, so the CLI's tile + * renderer can draw the result exactly as `hdx` would. + */ +export function toTileResult( + toolName: string, + input: unknown, + output: unknown, + calledAt: number, +): ChartResult | undefined { + const tool = chartedTool(toolName); + if (!tool) return undefined; + const args = (input ?? {}) as ToolInput; + const end = args.endTime ? new Date(args.endTime) : new Date(calledAt); + const start = args.startTime + ? new Date(args.startTime) + : new Date(end.getTime() - DEFAULT_WINDOW_MS); + + const data = parseResponse(output); + if (!data || data.data.length === 0) return undefined; + const shapes = DISPLAY_TYPES[tool]!; + const select = args.select ?? []; + const shape = + tool === 'clickstack_table' && + select.length > 1 && + SINGLE_SERIES_SHAPES.includes(args.shape ?? '') + ? 'table' + : (args.shape ?? Object.keys(shapes)[0]!); + const displayType = shapes[shape]; + if (!displayType) return undefined; + + const queriedConfig = { + displayType, + dateRange: [start, end], + granularity: args.granularity, + // Empty buckets are filled only when their alignment is known: an explicit + // granularity and every row present. Otherwise filling would invent zeros. + fillNulls: args.granularity && !isTrimmed(output) ? undefined : false, + select, + groupBy: args.groupBy, + } as unknown as ChartConfigWithDateRange; + + return { status: 'ok', queriedConfig, data }; +} diff --git a/packages/claude-plugin/test/render.test.tsx b/packages/claude-plugin/test/render.test.tsx new file mode 100644 index 0000000000..3d4fe99779 --- /dev/null +++ b/packages/claude-plugin/test/render.test.tsx @@ -0,0 +1,181 @@ +import { expect, test, type TestBody } from 'claude-code/testing'; + +// The bundled MCP server's settings must be set for the hooks module to load. +const options = { hyperdx_url: 'https://hyperdx.test', access_key: 'test-key' }; + +type Engine = Parameters[0]; +type On = Parameters[1]; + +const TIMESERIES = 'mcp__clickstack__clickstack_timeseries'; +const TABLE = 'mcp__clickstack__clickstack_table'; + +const timeseries = { + meta: [ + { name: 'Error %', type: 'Float64' }, + { name: 'ServiceName', type: 'LowCardinality(String)' }, + { name: '__hdx_time_bucket', type: 'DateTime' }, + ], + data: ['api', 'worker'].flatMap((service, s) => + [0, 5, 10, 15].map(m => ({ + 'Error %': (s + 1) * (m + 1), + ServiceName: service, + __hdx_time_bucket: `2026-10-13T00:${String(m).padStart(2, '0')}:00Z`, + })), + ), +}; + +const table = { + meta: [ + { name: 'Errors', type: 'UInt64' }, + { name: 'ServiceName', type: 'LowCardinality(String)' }, + ], + data: [ + { Errors: '42', ServiceName: 'api' }, + { Errors: '7', ServiceName: 'worker' }, + ], +}; + +async function drawCall( + $: Engine, + on: On, + tool: `mcp__${string}__${string}`, + input: Record, + result: unknown, +) { + let id = ''; + on('tool.call', (_, e) => { + id = e.tool_use_id; + return { result: [{ type: 'text', text: JSON.stringify({ result }) }] }; + }); + on('ui.render', ($, e) => { + const { Text } = $.ui.resolve(e); + return engine row; + }); + await $.tool.call({ + tool, + sourceId: 's', + select: [{ aggFn: 'count' }], + ...input, + }); + return $.ui.mount({ + plugin: 'hyperdx-charts', + surface: 'terminal', + component: 'ToolGroup', + props: { + calls: [ + { + tool_use_id: id, + tool, + input: { reason: 'Checking errors', ...input }, + isRunning: false, + isErrored: false, + isInterrupted: false, + }, + ], + isActive: false, + isExpanded: false, + }, + viewport: { columns: 100, rows: 40 }, + }); +} + +test( + 'draws a timeseries call as a line chart in place of its row', + { options }, + async ($, on) => { + const ui = await drawCall( + $, + on, + TIMESERIES, + { + startTime: '2026-10-13T00:00:00Z', + endTime: '2026-10-13T00:20:00Z', + granularity: '5 minute', + }, + timeseries, + ); + expect( + await ui.find({ type: 'Text', text: /^engine row$/ }), + ).toBeUndefined(); + expect( + await ui.find({ type: 'Text', text: /Checking errors/ }), + ).toBeDefined(); + expect(await ui.find({ type: 'Text', text: /worker/ })).toBeDefined(); + expect(await ui.find({ type: 'Text', text: /[┤┼╭╮╰╯─]/ })).toBeDefined(); + }, +); + +test( + 'draws a table call with bar shape as categorical bars', + { options }, + async ($, on) => { + const ui = await drawCall($, on, TABLE, { shape: 'bar' }, table); + expect(await ui.find({ type: 'Text', text: /api/ })).toBeDefined(); + expect(await ui.find({ type: 'Text', text: /█/ })).toBeDefined(); + }, +); + +test( + 'keeps the engine row for a result it cannot chart', + { options }, + async ($, on) => { + const ui = await drawCall( + $, + on, + TIMESERIES, + {}, + { meta: [{ name: 'x', type: 'String' }], data: [{ x: 'a' }] }, + ); + expect(await ui.find({ type: 'Text', text: /^engine row$/ })).toBeDefined(); + }, +); + +test( + 'draws a timeseries call drawn as its own tool row', + { options }, + async ($, on) => { + let id = ''; + on('tool.call', (_, e) => { + id = e.tool_use_id; + return { + result: [ + { type: 'text', text: JSON.stringify({ result: timeseries }) }, + ], + }; + }); + on('ui.render', ($, e) => { + const { Text } = $.ui.resolve(e); + return engine row; + }); + const input = { + startTime: '2026-10-13T00:00:00Z', + endTime: '2026-10-13T00:20:00Z', + granularity: '5 minute', + }; + await $.tool.call({ + tool: TIMESERIES, + sourceId: 's', + select: [{ aggFn: 'count' }], + ...input, + }); + const ui = await $.ui.mount({ + plugin: 'hyperdx-charts', + surface: 'terminal', + component: 'ToolUse', + requestId: id, + props: { + tool_use_id: id, + tool: TIMESERIES, + input, + isRunning: false, + isErrored: false, + isInterrupted: false, + }, + viewport: { columns: 100, rows: 40 }, + }); + expect( + await ui.find({ type: 'Text', text: /^engine row$/ }), + ).toBeUndefined(); + expect(await ui.find({ type: 'Text', text: /[┤┼╭╮╰╯─]/ })).toBeDefined(); + }, +); diff --git a/packages/claude-plugin/tsconfig.json b/packages/claude-plugin/tsconfig.json new file mode 100644 index 0000000000..fef8926239 --- /dev/null +++ b/packages/claude-plugin/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "types": ["jest", "node"], + "paths": { + "@/*": ["../cli/src/*"] + } + }, + "include": ["src", "types"] +} diff --git a/packages/claude-plugin/tsup.config.ts b/packages/claude-plugin/tsup.config.ts new file mode 100644 index 0000000000..3d0047e17e --- /dev/null +++ b/packages/claude-plugin/tsup.config.ts @@ -0,0 +1,70 @@ +import { fileURLToPath } from 'node:url'; +import { defineConfig, type Options } from 'tsup'; + +type Plugin = NonNullable[number]; + +const chalkShim = fileURLToPath(new URL('./src/chalk.ts', import.meta.url)); +const commonUtilsSrc = fileURLToPath( + new URL('../common-utils/src/', import.meta.url), +); + +// Claude Code refuses a hooks module over 1 MiB. common-utils' CommonJS dist +// can't be tree-shaken (node-sql-parser alone is 2.4 MB), so bundle its ESM +// source and treat dependencies as side-effect free to drop what the chart +// path never calls. +const shrink: Plugin = { + name: 'shrink', + setup(build) { + build.onResolve({ filter: /^chalk$/ }, args => + args.importer === chalkShim || args.pluginData + ? undefined + : { path: chalkShim }, + ); + build.onResolve( + { filter: /^@hyperdx\/common-utils\/dist\// }, + async args => { + const src = args.path.replace( + /^@hyperdx\/common-utils\/dist\//, + commonUtilsSrc, + ); + const resolved = await build.resolve(src, { + kind: args.kind, + resolveDir: args.resolveDir, + }); + return { path: resolved.path, sideEffects: false }; + }, + ); + build.onResolve({ filter: /^[^./]/ }, async args => { + if (args.pluginData) return undefined; + const resolved = await build.resolve(args.path, { + kind: args.kind, + resolveDir: args.resolveDir, + pluginData: true, + }); + return resolved.errors.length + ? undefined + : { ...resolved, sideEffects: false }; + }); + }, +}; + +// hooks/register.tsx is compiled by Claude Code itself and must stay readable to +// `claude plugin validate`; the renderer it imports is bundled here for an +// environment with no Node and no DOM. +export default defineConfig({ + entry: { chart: 'src/index.ts' }, + outDir: 'hooks', + format: ['esm'], + platform: 'browser', + bundle: true, + splitting: false, + clean: false, + noExternal: [/.*/], + define: { 'process.env.NODE_ENV': '"production"' }, + // Each package's source resolves its own `@/` alias, so esbuild must use the + // nearest tsconfig per file rather than this package's. + esbuildOptions(options) { + delete options.tsconfig; + }, + esbuildPlugins: [shrink], +}); diff --git a/packages/claude-plugin/types/index.d.ts b/packages/claude-plugin/types/index.d.ts new file mode 100644 index 0000000000..3aeb839616 --- /dev/null +++ b/packages/claude-plugin/types/index.d.ts @@ -0,0 +1,13 @@ +export type ChartCall = { + tool: string; + input: unknown; + output: unknown; + calledAt: number; +}; + +declare module 'claude-code' { + interface PluginState { + // Charted calls by tool_use_id: MCP rows don't carry their output to ui.render. + 'hyperdx-charts': { calls: Record }; + } +} diff --git a/yarn.lock b/yarn.lock index dd87de2efb..ce4abf00ac 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4937,7 +4937,23 @@ __metadata: languageName: node linkType: hard -"@hyperdx/cli@workspace:packages/cli": +"@hyperdx/claude-plugin@workspace:packages/claude-plugin": + version: 0.0.0-use.local + resolution: "@hyperdx/claude-plugin@workspace:packages/claude-plugin" + dependencies: + "@hyperdx/cli": "workspace:*" + "@hyperdx/common-utils": "npm:^0.31.0" + "@jest/globals": "npm:^30.2.0" + "@types/jest": "npm:^29.5.14" + chalk: "npm:^5.3.0" + jest: "npm:^30.2.0" + ts-jest: "npm:^29.4.11" + tsup: "npm:^8.4.0" + typescript: "npm:^6.0.3" + languageName: unknown + linkType: soft + +"@hyperdx/cli@workspace:*, @hyperdx/cli@workspace:packages/cli": version: 0.0.0-use.local resolution: "@hyperdx/cli@workspace:packages/cli" dependencies: