Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(mcp-host): draw each dashboard chart on its own, in the page's theme

marcoteb828538f38c84
diff --git a/mcp-host/src/workflow/dashboardCharts.ts b/mcp-host/src/workflow/dashboardCharts.ts
new file mode 100644
index 000000000..b58c3bae1
--- /dev/null
+++ b/mcp-host/src/workflow/dashboardCharts.ts
@@ -0,0 +1,519 @@
+/**
+ * Chart preparation for `clerum__generate_dashboard`: each chart is validated
+ * and translated to a configuration Chart.js registers before the page is
+ * written, so an unusable chart becomes a note in its own card and a warning
+ * for the agent instead of an error that stops the page script.
+ */
+import { ChartDataError, coerceNumber, normalizeChartData } from './chartData'
+import type { NormalizedDataset, NormalizedPoint } from './chartData'
+import { escapeHtml } from './dashboardHtml'
+
+/** Every chart type the dashboard draws, the same set clerum__generate_chart accepts. */
+export const DASHBOARD_CHART_TYPES = [
+ 'line',
+ 'bar',
+ 'horizontalBar',
+ 'pie',
+ 'doughnut',
+ 'area',
+ 'radar',
+ 'polarArea',
+ 'scatter',
+ 'bubble',
+ 'stackedBar',
+ 'stackedArea',
+ 'mixedBarLine',
+ 'gauge',
+ 'waterfall',
+ 'funnel',
+] as const
+
+const KNOWN_TYPES = new Set<string>(DASHBOARD_CHART_TYPES)
+const SLICE_TYPES = new Set(['pie', 'doughnut', 'polarArea'])
+const XY_TYPES = new Set(['scatter', 'bubble'])
+const TRANSLUCENT_TYPES = new Set(['line', 'area', 'stackedArea', 'radar', 'scatter', 'bubble'])
+
+/**
+ * What the page script needs to draw one chart. Colors are left as tokens
+ * ("$chart-0", "[email protected]", "$success") that the script resolves against
+ * the page's CSS variables, so the series follow light, dark and print modes.
+ */
+export interface ClientChart {
+ id: string
+ type: string
+ labels: string[]
+ datasets: Array<Record<string, unknown>>
+ axes: 'cartesian' | 'radial' | 'none'
+ indexAxis: 'x' | 'y'
+ stacked: boolean
+ legend: boolean
+ xAxisLabel?: string
+ yAxisLabel?: string
+ gauge?: { value: string; max: string }
+}
+
+/** The number of series colors each theme defines (DashboardThemeColors.chart). */
+const PALETTE_SIZE = 7
+
+/**
+ * The palette token for series or slice `i`. Past the palette the colors
+ * repeat fainter each round, with `dash` for lines, so no two series look alike.
+ */
+function paletteColor(i: number, alpha = 1): { color: string; dash?: number[] } {
+ const round = Math.floor(i / PALETTE_SIZE)
+ const shade = alpha * Math.max(0.35, 1 - 0.3 * round)
+ const base = `$chart-${i % PALETTE_SIZE}`
+ return {
+ color: shade === 1 ? base : `${base}@${Number(shade.toFixed(2))}`,
+ dash:
+ round === 0
+ ? undefined
+ : [
+ [6, 3],
+ [2, 3],
+ [8, 3, 2, 3],
+ ][(round - 1) % 3],
+ }
+}
+
+/** The values of a chart as a table, shown when Chart.js is not inlined. */
+interface ValueTable {
+ labels: string[]
+ series: Array<{ label: string; values: string[] }>
+}
+
+interface Translated {
+ chart: Omit<ClientChart, 'id'>
+ warnings: string[]
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value === 'string') return value.trim() ? value : undefined
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value)
+ return undefined
+}
+
+function seriesColors(ds: NormalizedDataset, index: number, type: string): Record<string, unknown> {
+ if (SLICE_TYPES.has(type)) {
+ return {
+ backgroundColor: ds.backgroundColor ?? ds.data.map((_, j) => paletteColor(j).color),
+ borderColor: ds.borderColor ?? '$surface',
+ }
+ }
+ const { color, dash } = paletteColor(index)
+ const border = ds.borderColor ?? color
+ const dashed = dash && ds.borderColor === undefined ? { borderDash: dash } : {}
+ if (!TRANSLUCENT_TYPES.has(type)) {
+ return { borderColor: border, backgroundColor: ds.backgroundColor ?? color, ...dashed }
+ }
+ // Points take the fill color by default, which here is the faint area tint.
+ return {
+ borderColor: border,
+ backgroundColor: ds.backgroundColor ?? paletteColor(index, 0.2).color,
+ pointBackgroundColor: border,
+ ...dashed,
+ }
+}
+
+/** CSS color keywords, which canvas and Chart.js both read. */
+const NAMED_COLORS = new Set(
+ (
+ 'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue ' +
+ 'blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk ' +
+ 'crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki ' +
+ 'darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen ' +
+ 'darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue ' +
+ 'dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite ' +
+ 'gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki ' +
+ 'lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan ' +
+ 'lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen ' +
+ 'lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen ' +
+ 'magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen ' +
+ 'mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream ' +
+ 'mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid ' +
+ 'palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum ' +
+ 'powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown ' +
+ 'seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen ' +
+ 'steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow ' +
+ 'yellowgreen transparent'
+ ).split(' ')
+)
+
+/** Longer than any CSS color a chart needs, e.g. "hsl(210deg 50% 40% / 0.8)". */
+const MAX_COLOR_LENGTH = 64
+
+function isCssColor(value: unknown): boolean {
+ if (typeof value !== 'string' || value.length > MAX_COLOR_LENGTH) return false
+ const v = value.trim().toLowerCase()
+ return (
+ /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(v) ||
+ /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\((?:[\d\s.,%/+-]|deg|g?rad|turn|none)*\)$/.test(v) ||
+ NAMED_COLORS.has(v)
+ )
+}
+
+/** Color warnings written out per chart; the rest are counted in one line. */
+const COLOR_WARNINGS_SHOWN = 3
+
+/**
+ * `ds` without the colors that are not CSS colors, which canvas would paint
+ * black: a single color is dropped for the palette's, a per-point one gets the
+ * palette color of its point (slices) or of its series. Each rejected value's
+ * path and text go to `bad`.
+ */
+function checkColors(
+ ds: NormalizedDataset,
+ index: number,
+ type: string,
+ where: string,
+ bad: Array<{ at: string; value: unknown }>
+): NormalizedDataset {
+ const out = { ...ds }
+ for (const key of ['backgroundColor', 'borderColor'] as const) {
+ const value = ds[key]
+ if (value === undefined) continue
+ const at = `${where}.datasets[${index}].${key}`
+ if (!Array.isArray(value)) {
+ if (!isCssColor(value)) {
+ bad.push({ at, value })
+ delete out[key]
+ }
+ continue
+ }
+ out[key] = value.map((v, j) => {
+ if (isCssColor(v)) return v
+ bad.push({ at: `${at}[${j}]`, value: v })
+ return paletteColor(SLICE_TYPES.has(type) ? j : index).color
+ })
+ }
+ return out
+}
+
+function colorWarnings(bad: Array<{ at: string; value: unknown }>, where: string): string[] {
+ const shown = bad.slice(0, COLOR_WARNINGS_SHOWN).map(({ at, value }) => {
+ const text = JSON.stringify(
+ typeof value === 'string' && value.length > 40 ? `${value.slice(0, 40)}…` : value
+ )
+ return (
+ `${at} ${text} is not a CSS color, so the palette color was used. ` +
+ 'Pass hex such as "#2563eb", rgb(), hsl() or a color name.'
+ )
+ })
+ const more = bad.length - shown.length
+ if (more > 0) {
+ shown.push(`${where}: ${more} more colors are not CSS colors and were replaced the same way.`)
+ }
+ return shown
+}
+
+function readout(n: number): string {
+ return Number.isInteger(n) ? String(n) : String(Number(n.toFixed(2)))
+}
+
+function firstSeriesValues(ds: NormalizedDataset | undefined): number[] {
+ return ((ds?.data ?? []) as Array<number | null>).map(v => (typeof v === 'number' ? v : 0))
+}
+
+/** Map a validated user-facing chart onto the Chart.js configuration that draws it. */
+function translate(
+ type: string,
+ spec: Record<string, unknown>,
+ labels: string[],
+ datasets: NormalizedDataset[]
+): Translated {
+ const warnings: string[] = []
+ const chart: Omit<ClientChart, 'id'> = {
+ type,
+ labels,
+ datasets: [],
+ axes: SLICE_TYPES.has(type) ? 'none' : type === 'radar' ? 'radial' : 'cartesian',
+ indexAxis: 'x',
+ stacked: false,
+ legend: SLICE_TYPES.has(type) || datasets.some(ds => Boolean(ds.label)),
+ xAxisLabel: optionalText(spec.xAxisLabel),
+ yAxisLabel: optionalText(spec.yAxisLabel),
+ }
+ if (type === 'polarArea') chart.axes = 'radial'
+
+ const styled = (ds: NormalizedDataset, i: number, as = type): Record<string, unknown> => ({
+ ...ds,
+ label: ds.label ?? '',
+ ...seriesColors(ds, i, as),
+ })
+
+ switch (type) {
+ case 'horizontalBar':
+ chart.type = 'bar'
+ chart.indexAxis = 'y'
+ chart.datasets = datasets.map((ds, i) => styled(ds, i))
+ return { chart, warnings }
+ case 'area':
+ chart.type = 'line'
+ chart.datasets = datasets.map((ds, i) => ({ ...styled(ds, i), fill: ds.fill ?? true }))
+ return { chart, warnings }
+ case 'stackedBar':
+ chart.type = 'bar'
+ chart.stacked = true
+ chart.datasets = datasets.map((ds, i) => styled(ds, i))
+ return { chart, warnings }
+ case 'stackedArea':
+ chart.type = 'line'
+ chart.stacked = true
+ chart.datasets = datasets.map((ds, i) => ({
+ ...styled(ds, i),
+ fill: ds.fill ?? (i === 0 ? 'origin' : '-1'),
+ }))
+ return { chart, warnings }
+ case 'mixedBarLine':
+ chart.type = 'bar'
+ // A lower order draws later, which keeps the lines above the bars.
+ chart.datasets = datasets.map((ds, i) =>
+ i === 0
+ ? { ...styled(ds, i, 'bar'), order: 1 }
+ : { ...styled(ds, i, 'line'), type: 'line', fill: false, order: 0 }
+ )
+ return { chart, warnings }
+ case 'funnel': {
+ chart.type = 'bar'
+ chart.indexAxis = 'y'
+ chart.legend = false
+ const pairs = firstSeriesValues(datasets[0]).map((v, i) => ({ v, l: labels[i] ?? '' }))
+ pairs.sort((a, b) => b.v - a.v)
+ chart.labels = pairs.map(p => p.l)
+ chart.datasets = [
+ { ...styled({ ...datasets[0], data: pairs.map(p => p.v) }, 0, 'bar'), label: '' },
+ ]
+ return { chart, warnings }
+ }
+ case 'waterfall': {
+ chart.type = 'bar'
+ chart.legend = false
+ const deltas = firstSeriesValues(datasets[0])
+ const floats: number[][] = []
+ const colors: string[] = []
+ let total = 0
+ for (const delta of deltas) {
+ floats.push([total, total + delta])
+ colors.push(delta >= 0 ? '$success' : '$danger')
+ total += delta
+ }
+ floats.push([0, total])
+ colors.push('$chart-0')
+ chart.labels = [...labels, 'Total']
+ chart.datasets = [
+ {
+ label: datasets[0]?.label ?? '',
+ data: floats,
+ backgroundColor: colors,
+ borderColor: colors,
+ },
+ ]
+ return { chart, warnings }
+ }
+ case 'gauge': {
+ chart.type = 'doughnut'
+ chart.axes = 'none'
+ chart.legend = false
+ const requestedMax = coerceNumber(spec.gaugeMax)
+ const max = requestedMax !== undefined && requestedMax > 0 ? requestedMax : 100
+ const values = firstSeriesValues(datasets[0])
+ const raw = values[0] ?? 0
+ if (values.length > 1) {
+ warnings.push(
+ `the gauge shows one value, so ${values.length - 1} more in datasets[0].data ` +
+ `${values.length > 2 ? 'were' : 'was'} left out. ` +
+ 'Send one value, or use a bar chart to compare several.'
+ )
+ }
+ const value = Math.min(Math.max(raw, 0), max)
+ if (value !== raw) {
+ warnings.push(
+ `the gauge value ${raw} is outside 0..${max}, so the dial is drawn ` +
+ `${value === 0 ? 'empty' : 'full'} and the readout shows ${readout(raw)}.`
+ )
+ }
+ chart.labels = labels.length > 0 ? [labels[0], ''] : ['', '']
+ chart.datasets = [
+ {
+ label: datasets[0]?.label ?? '',
+ data: [value, max - value],
+ backgroundColor: ['$chart-0', '$border'],
+ borderColor: ['$chart-0', '$border'],
+ },
+ ]
+ chart.gauge = { value: readout(raw), max: readout(max) }
+ return { chart, warnings }
+ }
+ default:
+ // A point or bubble at the end of an axis is drawn whole, past the plot edge.
+ chart.datasets = datasets.map((ds, i) =>
+ XY_TYPES.has(type) ? { ...styled(ds, i), clip: false } : styled(ds, i)
+ )
+ return { chart, warnings }
+ }
+}
+
+function valueTable(type: string, labels: string[], datasets: NormalizedDataset[]): ValueTable {
+ if (XY_TYPES.has(type)) {
+ const points = Math.max(...datasets.map(ds => ds.data.length))
+ return {
+ labels: Array.from({ length: points }, (_, i) => String(i + 1)),
+ series: datasets.map(ds => ({
+ label: ds.label ?? '',
+ values: (ds.data as NormalizedPoint[]).map(p =>
+ p.r === undefined ? `(${p.x}, ${p.y})` : `(${p.x}, ${p.y}, ${p.r})`
+ ),
+ })),
+ }
+ }
+ return {
+ labels,
+ series: datasets.map(ds => ({
+ label: ds.label ?? '',
+ values: (ds.data as Array<number | null>).map(v => (v === null ? '' : String(v))),
+ })),
+ }
+}
+
+export interface PreparedChart {
+ title?: string
+ /** Text under the chart: a gauge's label. */
+ caption?: string
+ chart?: Omit<ClientChart, 'id'>
+ table?: ValueTable
+ error?: string
+ warnings: string[]
+}
+
+/** Validate one chart spec found at `where` in the arguments. */
+export function prepareDashboardChart(raw: unknown, where: string): PreparedChart {
+ if (!isRecord(raw)) {
+ return {
+ warnings: [],
+ error: `${where} must be a chart object {type, labels, datasets}; received ${
+ raw === undefined
+ ? 'nothing'
+ : raw === null
+ ? 'null'
+ : Array.isArray(raw)
+ ? 'an array'
+ : `a ${typeof raw}`
+ }.`,
+ }
+ }
+ const title = optionalText(raw.title)
+ const type = typeof raw.type === 'string' ? raw.type : undefined
+ if (!type || !KNOWN_TYPES.has(type)) {
+ const got = type ? `"${type}" is not a chart type` : 'is missing'
+ return {
+ title,
+ warnings: [],
+ error: `${where}.type ${got}; use one of: ${DASHBOARD_CHART_TYPES.join(', ')}.`,
+ }
+ }
+ try {
+ const clean = normalizeChartData(
+ { labels: raw.labels, datasets: raw.datasets },
+ { chartType: type, path: where }
+ )
+ const labels = clean.labels ?? []
+ // A gauge draws one value, so it has no categories to label.
+ const unlabeledGauge = type === 'gauge' && raw.labels === undefined
+ const warnings = clean.warnings
+ .filter(w => !(unlabeledGauge && w.includes(`\`${where}.labels\``)))
+ .map(w => (w.includes(where) ? w : `${where}: ${w}`))
+ const badColors: Array<{ at: string; value: unknown }> = []
+ const datasets = clean.datasets.map((ds, i) => checkColors(ds, i, type, where, badColors))
+ warnings.push(...colorWarnings(badColors, where))
+ const slices = SLICE_TYPES.has(type)
+ const colored = slices
+ ? datasets.reduce((n, ds) => (ds.backgroundColor ? n : Math.max(n, ds.data.length)), 0)
+ : datasets.length
+ const paletted = slices || datasets.slice(PALETTE_SIZE).some(ds => !ds.borderColor)
+ if (colored > PALETTE_SIZE && paletted && !['gauge', 'waterfall', 'funnel'].includes(type)) {
+ const what = slices ? 'slices' : 'series'
+ const past =
+ colored === PALETTE_SIZE + 1
+ ? `${what} ${colored} repeats one in a fainter shade`
+ : `${what} ${PALETTE_SIZE + 1}-${colored} repeat them in fainter shades`
+ warnings.push(
+ `${where} has ${colored} ${what} and the palette ${PALETTE_SIZE} colors, so ${past}. ` +
+ `Fewer ${what} read better.`
+ )
+ }
+ const translated = translate(type, raw, labels, datasets)
+ warnings.push(...translated.warnings.map(w => `${where}: ${w}`))
+ return {
+ title,
+ caption:
+ type === 'gauge' && Array.isArray(raw.labels) ? optionalText(raw.labels[0]) : undefined,
+ chart: translated.chart,
+ table: valueTable(type, labels, datasets),
+ warnings,
+ }
+ } catch (err) {
+ if (!(err instanceof ChartDataError)) throw err
+ return { title, warnings: [], error: err.message }
+ }
+}
+
+function valueTableHtml(table: ValueTable): string {
+ const head = `<tr><th></th>${table.series.map(s => `<th>${escapeHtml(s.label)}</th>`).join('')}</tr>`
+ const rows = table.labels
+ .map(
+ (label, i) =>
+ `<tr><td>${escapeHtml(label)}</td>${table.series
+ .map(s => `<td>${escapeHtml(s.values[i] ?? '')}</td>`)
+ .join('')}</tr>`
+ )
+ .join('')
+ return `<div class="chart-card__table"><table class="data-table"><thead>${head}</thead><tbody>${rows}</tbody></table></div>`
+}
+
+/**
+ * The charts of one dashboard. Each `card` call validates a spec and returns
+ * its card; the specs Chart.js has to draw accumulate in `specs`.
+ */
+export class DashboardCharts {
+ readonly specs: ClientChart[] = []
+ drawn = 0
+
+ /**
+ * @param drawInBrowser false when Chart.js is not inlined: cards then carry a table of their values.
+ * @param notes where repairs (`warnings`) and charts that could not be drawn (`failures`) are reported.
+ */
+ constructor(
+ private readonly drawInBrowser: boolean,
+ private readonly notes: { warnings: string[]; failures: string[] }
+ ) {}
+
+ card(raw: unknown, where: string, opts: { title?: string; tall?: boolean } = {}): string {
+ const prepared = prepareDashboardChart(raw, where)
+ this.notes.warnings.push(...prepared.warnings)
+ const title = opts.title ?? prepared.title
+ const heading = title ? `<h3 class="chart-card__title">${escapeHtml(title)}</h3>` : ''
+ const wide = opts.tall ? ' chart-card--wide' : ''
+ let body: string
+ if (!prepared.chart) {
+ this.notes.failures.push(prepared.error!)
+ body = `<p class="chart-card__note">${escapeHtml(`This chart could not be drawn: ${prepared.error}`)}</p>`
+ } else if (!this.drawInBrowser) {
+ this.drawn++
+ body = valueTableHtml(prepared.table!)
+ } else {
+ this.drawn++
+ const id = `chart-${this.specs.length}`
+ this.specs.push({ id, ...prepared.chart })
+ const tall = opts.tall ? ' chart-card__container--tall' : ''
+ const caption = prepared.caption
+ ? `<p class="chart-card__caption">${escapeHtml(prepared.caption)}</p>`
+ : ''
+ body = `<div class="chart-card__container${tall}"><canvas id="${id}" role="img" aria-label="${escapeHtml(title ?? prepared.caption ?? '')}"></canvas></div>${caption}`
+ }
+ return `<div class="chart-card${wide}">${heading}${body}</div>`
+ }
+}
diff --git a/mcp-host/src/workflow/dashboardHtml.ts b/mcp-host/src/workflow/dashboardHtml.ts
new file mode 100644
index 000000000..eb93f4ad5
--- /dev/null
+++ b/mcp-host/src/workflow/dashboardHtml.ts
@@ -0,0 +1,23 @@
+/**
+ * HTML escaping for the dashboard. Every value that reaches the page from the
+ * arguments goes through here or through a whitelist, because the file is
+ * opened straight from disk in the user's browser.
+ */
+
+/** Escape text for an element body or a quoted attribute. */
+export function escapeHtml(s: unknown): string {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;')
+ .replace(/\//g, '&#x2F;')
+}
+
+/** `value` when it is one of `allowed`, otherwise `fallback`. */
+export function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
+ return typeof value === 'string' && (allowed as readonly string[]).includes(value)
+ ? (value as T)
+ : fallback
+}
diff --git a/mcp-host/src/workflow/dashboardScript.ts b/mcp-host/src/workflow/dashboardScript.ts
new file mode 100644
index 000000000..cb6897369
--- /dev/null
+++ b/mcp-host/src/workflow/dashboardScript.ts
@@ -0,0 +1,223 @@
+/**
+ * The script that draws a dashboard's charts in the browser.
+ *
+ * Each chart and each sparkline is drawn on its own, so one that Chart.js
+ * refuses shows why in its card and never blanks the others. Colors are read
+ * from the page's CSS variables and read again when the color scheme or the
+ * print media changes, so the series stay legible in light, dark and print.
+ * Animation is off: headless HTML-to-PDF converters print a chart the moment it
+ * is created, which with animation on is at a fraction of its height.
+ */
+
+const PAGE_SCRIPT = String.raw`
+(function () {
+ 'use strict';
+ var charts = __CHARTS__;
+ var root = document.documentElement;
+ var instances = [];
+ var COLOR_KEYS = ['backgroundColor', 'borderColor', 'pointBackgroundColor'];
+
+ function cssVar(name) {
+ return getComputedStyle(root).getPropertyValue(name).trim();
+ }
+
+ function withAlpha(color, alpha) {
+ var m = /^#([0-9a-f]{6})$/i.exec(color);
+ if (!m) return color;
+ var n = parseInt(m[1], 16);
+ return 'rgba(' + (n >> 16) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + alpha + ')';
+ }
+
+ function paint(value) {
+ if (Array.isArray(value)) return value.map(paint);
+ if (typeof value !== 'string' || value.charAt(0) !== '$') return value;
+ var parts = value.slice(1).split('@');
+ var series = /^chart-(\d+)$/.exec(parts[0]);
+ var color = cssVar(series ? '--chart-' + ((Number(series[1]) % 7) + 1) : '--' + parts[0]);
+ return parts.length > 1 ? withAlpha(color, Number(parts[1])) : color;
+ }
+
+ function paintDatasets(spec) {
+ return spec.datasets.map(function (ds) {
+ var out = Object.assign({}, ds);
+ COLOR_KEYS.forEach(function (key) {
+ if (ds[key] !== undefined) out[key] = paint(ds[key]);
+ });
+ return out;
+ });
+ }
+
+ function options(spec) {
+ var text = cssVar('--text-muted');
+ var grid = cssVar('--border');
+ function axis(title) {
+ var out = {
+ stacked: spec.stacked,
+ ticks: { color: text },
+ grid: { color: grid },
+ title: title ? { display: true, text: title, color: text } : { display: false },
+ };
+ // Set only where needed: an explicit false would override the bar charts' own zero baseline.
+ if (spec.stacked) out.beginAtZero = true;
+ return out;
+ }
+ var scales;
+ if (spec.axes === 'cartesian') {
+ scales = { x: axis(spec.xAxisLabel), y: axis(spec.yAxisLabel) };
+ } else if (spec.axes === 'radial') {
+ scales = {
+ r: {
+ ticks: { color: text, backdropColor: cssVar('--surface') },
+ grid: { color: grid },
+ angleLines: { color: grid },
+ pointLabels: { color: text },
+ },
+ };
+ }
+ var labels = { color: text };
+ // Chart.js sorts the legend by dataset "order", which mixed charts set to draw lines on top.
+ if (spec.datasets.some(function (ds) { return ds.order !== undefined; })) {
+ labels.sort = function (a, b) { return a.datasetIndex - b.datasetIndex; };
+ }
+ var result = {
+ responsive: true,
+ maintainAspectRatio: false,
+ animation: false,
+ indexAxis: spec.indexAxis,
+ plugins: { legend: { display: spec.legend, labels: labels } },
+ scales: scales,
+ };
+ if (spec.gauge) {
+ result.rotation = -90;
+ result.circumference = 180;
+ result.cutout = '70%';
+ result.plugins.tooltip = { enabled: false };
+ }
+ return result;
+ }
+
+ function gaugeReadout(spec) {
+ return {
+ id: 'gaugeReadout',
+ afterDatasetsDraw: function (chart) {
+ var arc = chart.getDatasetMeta(0).data[0];
+ if (!arc) return;
+ var ctx = chart.ctx;
+ var size = Math.max(16, Math.min(40, arc.innerRadius * 0.45));
+ ctx.save();
+ ctx.textAlign = 'center';
+ ctx.fillStyle = cssVar('--text');
+ ctx.font = '700 ' + size + 'px ' + cssVar('--font');
+ ctx.fillText(spec.gauge.value, arc.x, arc.y - size * 0.7);
+ ctx.fillStyle = cssVar('--text-muted');
+ ctx.font = '500 ' + Math.round(size * 0.45) + 'px ' + cssVar('--font');
+ ctx.fillText('/ ' + spec.gauge.max, arc.x, arc.y - size * 0.05);
+ ctx.restore();
+ },
+ };
+ }
+
+ function message(err) {
+ return err && err.message ? err.message : String(err);
+ }
+
+ function discard(canvas) {
+ var drawn = typeof Chart !== 'undefined' && Chart.getChart(canvas);
+ if (drawn) drawn.destroy();
+ }
+
+ function draw(spec) {
+ var canvas = document.getElementById(spec.id);
+ if (!canvas) return;
+ try {
+ if (typeof Chart === 'undefined') throw new Error('the chart library did not load');
+ var chart = new Chart(canvas, {
+ type: spec.type,
+ data: { labels: spec.labels, datasets: paintDatasets(spec) },
+ options: options(spec),
+ plugins: spec.gauge ? [gaugeReadout(spec)] : [],
+ });
+ instances.push({ chart: chart, spec: spec });
+ } catch (err) {
+ discard(canvas);
+ var note = document.createElement('p');
+ note.className = 'chart-card__note';
+ note.textContent = 'This chart could not be drawn: ' + message(err);
+ (canvas.parentNode || canvas).replaceWith(note);
+ }
+ }
+
+ function sparkline(canvas) {
+ try {
+ var data = JSON.parse(canvas.getAttribute('data-spark') || '[]');
+ var chart = new Chart(canvas, {
+ type: 'line',
+ data: {
+ labels: data.map(function (_, i) { return i; }),
+ datasets: [{
+ data: data,
+ borderColor: paint('$accent'),
+ backgroundColor: 'transparent',
+ borderWidth: 2,
+ tension: 0.3,
+ pointRadius: 0,
+ }],
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ animation: false,
+ plugins: { legend: { display: false }, tooltip: { enabled: false } },
+ scales: { x: { display: false }, y: { display: false } },
+ },
+ });
+ instances.push({ chart: chart });
+ } catch (err) {
+ discard(canvas);
+ if (canvas.parentNode) canvas.parentNode.remove();
+ }
+ }
+
+ function retheme() {
+ instances.forEach(function (it) {
+ try {
+ if (it.spec) {
+ var painted = paintDatasets(it.spec);
+ it.chart.data.datasets.forEach(function (ds, i) {
+ COLOR_KEYS.forEach(function (key) {
+ if (painted[i][key] !== undefined) ds[key] = painted[i][key];
+ });
+ });
+ it.chart.options = options(it.spec);
+ } else {
+ it.chart.data.datasets[0].borderColor = paint('$accent');
+ }
+ // Not update('none'): that mode keeps the shared element options, so
+ // bars and points would stay in the previous scheme's colors.
+ it.chart.update();
+ } catch (err) {
+ // Keep the chart as it was drawn.
+ }
+ });
+ }
+
+ charts.forEach(draw);
+ document.querySelectorAll('canvas.kpi-card__sparkline[data-spark]').forEach(sparkline);
+
+ ['(prefers-color-scheme: dark)', 'print'].forEach(function (query) {
+ var media = window.matchMedia && window.matchMedia(query);
+ if (media && media.addEventListener) media.addEventListener('change', retheme);
+ });
+ window.addEventListener('beforeprint', function () {
+ instances.forEach(function (it) { it.chart.resize(); });
+ });
+})();
+`.trim()
+
+/**
+ * The page script for a dashboard. `chartsJson` is the list of ClientChart
+ * specs, already serialized so it cannot close the script element.
+ */
+export function dashboardScript(chartsJson: string): string {
+ return PAGE_SCRIPT.replace('__CHARTS__', () => chartsJson)
+}
diff --git a/mcp-host/src/workflow/dashboardThemes.ts b/mcp-host/src/workflow/dashboardThemes.ts
new file mode 100644
index 000000000..94b96c08f
--- /dev/null
+++ b/mcp-host/src/workflow/dashboardThemes.ts
@@ -0,0 +1,219 @@
+/**
+ * Color themes for `clerum__generate_dashboard`. Each theme has a light and a
+ * dark set; the page switches between them with the color scheme and prints in
+ * the light one.
+ */
+
+export type ThemeName = 'default' | 'corporate' | 'warm' | 'alert'
+
+export interface DashboardThemeColors {
+ bg: string
+ surface: string
+ surfaceMuted: string
+ text: string
+ textMuted: string
+ textSoft: string
+ border: string
+ primary: string
+ primaryHover: string
+ accent: string
+ success: string
+ warning: string
+ danger: string
+ successBg: string
+ warningBg: string
+ dangerBg: string
+ neutralBg: string
+ /** Series colors, each at least 3:1 against `surface` (WCAG 1.4.11). */
+ chart: string[]
+}
+
+export interface DashboardTheme {
+ name: ThemeName
+ light: DashboardThemeColors
+ dark: DashboardThemeColors
+ fontFamily: string
+}
+
+export const DASHBOARD_THEMES: Record<ThemeName, DashboardTheme> = {
+ default: {
+ name: 'default',
+ fontFamily:
+ "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
+ light: {
+ bg: '#f8fafc',
+ surface: '#ffffff',
+ surfaceMuted: '#f1f5f9',
+ text: '#0f172a',
+ textMuted: '#475569',
+ textSoft: '#94a3b8',
+ border: '#e2e8f0',
+ primary: '#0f172a',
+ primaryHover: '#1e293b',
+ accent: '#3b82f6',
+ success: '#16a34a',
+ warning: '#ca8a04',
+ danger: '#dc2626',
+ successBg: '#dcfce7',
+ warningBg: '#fef9c3',
+ dangerBg: '#fee2e2',
+ neutralBg: '#f1f5f9',
+ chart: ['#0f172a', '#16a34a', '#d97706', '#dc2626', '#2563eb', '#9333ea', '#0891b2'],
+ },
+ dark: {
+ bg: '#0f172a',
+ surface: '#1e293b',
+ surfaceMuted: '#334155',
+ text: '#f1f5f9',
+ textMuted: '#cbd5e1',
+ textSoft: '#94a3b8',
+ border: '#334155',
+ primary: '#3b82f6',
+ primaryHover: '#60a5fa',
+ accent: '#3b82f6',
+ success: '#22c55e',
+ warning: '#facc15',
+ danger: '#f87171',
+ successBg: '#14532d',
+ warningBg: '#713f12',
+ dangerBg: '#7f1d1d',
+ neutralBg: '#334155',
+ chart: ['#e2e8f0', '#4ade80', '#fbbf24', '#f87171', '#60a5fa', '#c084fc', '#22d3ee'],
+ },
+ },
+ corporate: {
+ name: 'corporate',
+ fontFamily:
+ "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
+ light: {
+ bg: '#f1f5f9',
+ surface: '#ffffff',
+ surfaceMuted: '#e0f2fe',
+ text: '#1e293b',
+ textMuted: '#475569',
+ textSoft: '#94a3b8',
+ border: '#cbd5e1',
+ primary: '#1e3a8a',
+ primaryHover: '#1e40af',
+ accent: '#0891b2',
+ success: '#059669',
+ warning: '#ca8a04',
+ danger: '#b91c1c',
+ successBg: '#dcfce7',
+ warningBg: '#fef9c3',
+ dangerBg: '#fee2e2',
+ neutralBg: '#e0f2fe',
+ chart: ['#1e40af', '#0e7490', '#0f766e', '#047857', '#4d7c0f', '#a16207', '#dc2626'],
+ },
+ dark: {
+ bg: '#0f172a',
+ surface: '#1e293b',
+ surfaceMuted: '#1e3a5f',
+ text: '#e0f2fe',
+ textMuted: '#bae6fd',
+ textSoft: '#7dd3fc',
+ border: '#1e3a5f',
+ primary: '#3b82f6',
+ primaryHover: '#60a5fa',
+ accent: '#0ea5e9',
+ success: '#34d399',
+ warning: '#facc15',
+ danger: '#f87171',
+ successBg: '#14532d',
+ warningBg: '#713f12',
+ dangerBg: '#7f1d1d',
+ neutralBg: '#1e3a5f',
+ chart: ['#60a5fa', '#22d3ee', '#2dd4bf', '#34d399', '#a3e635', '#facc15', '#f87171'],
+ },
+ },
+ warm: {
+ name: 'warm',
+ fontFamily:
+ "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
+ light: {
+ bg: '#f7f7f5',
+ surface: '#fffdfa',
+ surfaceMuted: '#f1ede6',
+ text: '#2f2823',
+ textMuted: '#66584c',
+ textSoft: '#857568',
+ border: '#d6d2cc',
+ primary: '#b45309',
+ primaryHover: '#ca6e1e',
+ accent: '#b45309',
+ success: '#15803d',
+ warning: '#b45309',
+ danger: '#9f1239',
+ successBg: '#dcfce7',
+ warningBg: '#fef3c7',
+ dangerBg: '#fee2e2',
+ neutralBg: '#f1ede6',
+ chart: ['#b45309', '#2f2823', '#0f766e', '#1e40af', '#9f1239', '#4d7c0f', '#7c3aed'],
+ },
+ dark: {
+ bg: '#0e0f10',
+ surface: '#141517',
+ surfaceMuted: '#1f2123',
+ text: '#f2f2ef',
+ textMuted: '#c6c8cc',
+ textSoft: '#92969e',
+ border: '#2a2c2f',
+ primary: '#ca6e1e',
+ primaryHover: '#e0833a',
+ accent: '#ca6e1e',
+ success: '#34d399',
+ warning: '#fbbf24',
+ danger: '#fb7185',
+ successBg: '#14532d',
+ warningBg: '#78350f',
+ dangerBg: '#7f1d1d',
+ neutralBg: '#1f2123',
+ chart: ['#f59e0b', '#e7e5e4', '#2dd4bf', '#60a5fa', '#fb7185', '#a3e635', '#a78bfa'],
+ },
+ },
+ alert: {
+ name: 'alert',
+ fontFamily:
+ "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
+ light: {
+ bg: '#fef2f2',
+ surface: '#ffffff',
+ surfaceMuted: '#fee2e2',
+ text: '#1f2937',
+ textMuted: '#4b5563',
+ textSoft: '#9ca3af',
+ border: '#fecaca',
+ primary: '#9f1239',
+ primaryHover: '#be123c',
+ accent: '#dc2626',
+ success: '#15803d',
+ warning: '#ca8a04',
+ danger: '#9f1239',
+ successBg: '#dcfce7',
+ warningBg: '#fef9c3',
+ dangerBg: '#fecaca',
+ neutralBg: '#fee2e2',
+ chart: ['#9f1239', '#dc2626', '#c2410c', '#a16207', '#4d7c0f', '#0e7490', '#1e40af'],
+ },
+ dark: {
+ bg: '#1f0a0a',
+ surface: '#2c0f0f',
+ surfaceMuted: '#3d1414',
+ text: '#fee2e2',
+ textMuted: '#fca5a5',
+ textSoft: '#f87171',
+ border: '#3d1414',
+ primary: '#fb7185',
+ primaryHover: '#fda4af',
+ accent: '#f87171',
+ success: '#34d399',
+ warning: '#facc15',
+ danger: '#fb7185',
+ successBg: '#14532d',
+ warningBg: '#713f12',
+ dangerBg: '#7f1d1d',
+ neutralBg: '#3d1414',
+ chart: ['#fb7185', '#fca5a5', '#fb923c', '#facc15', '#a3e635', '#22d3ee', '#93c5fd'],
+ },
+ },
+}