@outsidedata/dolex 3.1.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * MCP Tool: refine_visualization_cli_only
3
+ *
4
+ * FOR CLAUDE CODE / CLI USE ONLY. DO NOT USE IN CLAUDE DESKTOP.
5
+ *
6
+ * Same as refine_visualization but:
7
+ * - NEVER returns HTML in response
8
+ * - Writes HTML directly to disk via writeTo parameter
9
+ * - Returns only specId and changes
10
+ */
11
+
12
+ import { z } from 'zod';
13
+ import { writeFileSync, mkdirSync } from 'fs';
14
+ import { dirname } from 'path';
15
+ import type { VisualizationSpec, CompoundVisualizationSpec } from '../../types.js';
16
+ import { isCompoundSpec } from '../../types.js';
17
+ import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
18
+ import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
19
+ import { specStore } from '../spec-store.js';
20
+ import { errorResponse } from './shared.js';
21
+ import { refineInputSchema, handleRefine } from './refine.js';
22
+
23
+ // Extend the refine schema with required writeTo
24
+ export const refineCliInputSchema = refineInputSchema.extend({
25
+ writeTo: z.string().describe('REQUIRED. File path to write the refined HTML chart to. The HTML is written to disk and NOT returned in the response.'),
26
+ });
27
+
28
+ function buildOutputHtml(spec: VisualizationSpec | CompoundVisualizationSpec): string | undefined {
29
+ if (isCompoundSpec(spec)) {
30
+ return buildCompoundHtml(spec);
31
+ }
32
+ if (isHtmlPatternSupported(spec.pattern)) {
33
+ return buildChartHtml(spec);
34
+ }
35
+ return undefined;
36
+ }
37
+
38
+ export function handleRefineCli() {
39
+ // Get the base refine handler to reuse its logic
40
+ const baseRefine = handleRefine();
41
+
42
+ return async (args: z.infer<typeof refineCliInputSchema>) => {
43
+ // Call the base refine to do all the spec manipulation
44
+ const stored = specStore.get(args.specId);
45
+ if (!stored) {
46
+ return errorResponse(`Spec "${args.specId}" not found. It may have expired. Re-run visualize to get a new specId.`);
47
+ }
48
+
49
+ // Run base refine (it will update the spec store)
50
+ const baseResult = await baseRefine(args);
51
+
52
+ // Extract the response body from base result
53
+ const textContent = baseResult.content.find((c: any) => c.type === 'text');
54
+ if (!textContent) {
55
+ return errorResponse('Unexpected error: no text content from refine');
56
+ }
57
+
58
+ const body = JSON.parse(textContent.text);
59
+ const newSpecId = body.specId;
60
+
61
+ // Get the updated spec and build HTML
62
+ const updatedStored = specStore.get(newSpecId);
63
+ if (!updatedStored) {
64
+ return errorResponse('Unexpected error: refined spec not found');
65
+ }
66
+
67
+ const outputHtml = buildOutputHtml(updatedStored.spec);
68
+
69
+ // Write HTML to disk
70
+ let writeResult: string;
71
+ if (outputHtml) {
72
+ try {
73
+ mkdirSync(dirname(args.writeTo), { recursive: true });
74
+ writeFileSync(args.writeTo, outputHtml, 'utf-8');
75
+ writeResult = `Wrote ${outputHtml.length} bytes to ${args.writeTo}`;
76
+ } catch (err) {
77
+ return errorResponse(`Failed to write to ${args.writeTo}: ${err instanceof Error ? err.message : String(err)}`);
78
+ }
79
+ } else {
80
+ const pattern = isCompoundSpec(updatedStored.spec)
81
+ ? (updatedStored.spec as any).views?.find((v: any) => v.type === 'chart')?.chart?.pattern
82
+ : (updatedStored.spec as VisualizationSpec).pattern;
83
+ writeResult = `No HTML builder for pattern "${pattern}"`;
84
+ }
85
+
86
+ // Add write info to response
87
+ body.writeTo = args.writeTo;
88
+ body.writeResult = writeResult;
89
+
90
+ // CLI tools NEVER return structuredContent - just text
91
+ return {
92
+ content: [{
93
+ type: 'text' as const,
94
+ text: JSON.stringify(body, null, 2),
95
+ }],
96
+ };
97
+ };
98
+ }
@@ -452,6 +452,7 @@ export function handleRefine() {
452
452
  },
453
453
  });
454
454
 
455
+ // Always include HTML — Desktop requires it for inline chart rendering
455
456
  if (outputHtml) {
456
457
  return htmlResponse(body, outputHtml);
457
458
  }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * MCP Tool: visualize_cli_only
3
+ *
4
+ * FOR CLAUDE CODE / CLI USE ONLY. DO NOT USE IN CLAUDE DESKTOP.
5
+ *
6
+ * Same as visualize but:
7
+ * - NEVER returns HTML in response
8
+ * - Writes HTML directly to disk via writeTo parameter
9
+ * - Returns only specId and metadata
10
+ */
11
+
12
+ import { z } from 'zod';
13
+ import { writeFileSync, mkdirSync } from 'fs';
14
+ import { dirname } from 'path';
15
+ import type { VisualizeInput, VisualizeOutput, DataColumn, VisualizationSpec } from '../../types.js';
16
+ import { isCompoundSpec } from '../../types.js';
17
+ import { ALL_PALETTE_NAMES } from './sql-schemas.js';
18
+ import { buildChartHtml, isHtmlPatternSupported } from '../../renderers/html/index.js';
19
+ import { shouldCompound, buildCompoundSpec } from '../../renderers/html/compound.js';
20
+ import { buildCompoundHtml } from '../../renderers/html/builders/compound.js';
21
+ import { specStore } from '../spec-store.js';
22
+ import { getResult } from './result-cache.js';
23
+ import { errorResponse, inferColumns, applyColorPreferences } from './shared.js';
24
+ import { columnsSchema, dataShapeHintsSchema } from './visualize.js';
25
+
26
+ export const visualizeCliInputSchema = z.object({
27
+ data: z.array(z.record(z.any())).optional().describe('Array of data rows to visualize. Optional if resultId or sourceId+sql is provided.'),
28
+ resultId: z.string().optional().describe('Result ID from a previous query_data call'),
29
+ sourceId: z.string().optional().describe('Dataset ID returned by load_csv'),
30
+ sql: z.string().optional().describe('SQL SELECT query to slice/aggregate the data before visualizing.'),
31
+ intent: z.string().describe('What the user wants to see'),
32
+ columns: columnsSchema,
33
+ dataShapeHints: dataShapeHintsSchema,
34
+ pattern: z.string().optional().describe('Force a specific chart pattern by ID'),
35
+ title: z.string().optional().describe('Chart title'),
36
+ subtitle: z.string().optional().describe('Chart subtitle'),
37
+ includeDataTable: z.boolean().optional().describe('Whether to add a companion data table. Default: true'),
38
+ palette: z.enum(ALL_PALETTE_NAMES).optional().describe('Named palette'),
39
+ highlight: z.object({
40
+ values: z.array(z.union([z.string(), z.number()])).describe('Values to emphasize'),
41
+ color: z.union([z.string(), z.array(z.string())]).optional(),
42
+ mutedColor: z.string().optional(),
43
+ mutedOpacity: z.number().optional(),
44
+ }).optional(),
45
+ colorField: z.string().optional().describe('Which data field to base colors on'),
46
+ maxAlternativeChartTypes: z.number().optional().describe('Max alternative chart type recommendations to return (default: 2)'),
47
+ geoLevel: z.enum(['country', 'subdivision']).optional().describe('Geographic level'),
48
+ geoRegion: z.string().optional().describe('Geographic region code'),
49
+ writeTo: z.string().describe('REQUIRED. File path to write the HTML chart to. The HTML is written to disk and NOT returned in the response.'),
50
+ });
51
+
52
+ export function handleVisualizeCli(
53
+ selectPatterns: (input: VisualizeInput) => VisualizeOutput,
54
+ deps?: { sourceManager?: any },
55
+ ) {
56
+ return async (args: z.infer<typeof visualizeCliInputSchema>) => {
57
+ let data = args.data;
58
+ let queryMeta: { truncated?: boolean; totalSourceRows?: number } | undefined;
59
+
60
+ // Path 1: sourceId + sql → server-side query
61
+ if (args.sourceId && args.sql) {
62
+ if (!deps?.sourceManager) {
63
+ return errorResponse('Source manager not available.');
64
+ }
65
+ const result = await deps.sourceManager.querySql(args.sourceId, args.sql);
66
+ if (!result.ok) {
67
+ return errorResponse(result.error);
68
+ }
69
+ data = result.rows;
70
+ queryMeta = { truncated: result.truncated, totalSourceRows: result.totalRows };
71
+ }
72
+
73
+ // Path 2: resultId → cached query result
74
+ if (!data && args.resultId) {
75
+ const cached = getResult(args.resultId);
76
+ if (!cached) {
77
+ return errorResponse(`Result "${args.resultId}" not found or expired. Re-run query_data to get a new resultId.`);
78
+ }
79
+ data = cached.rows;
80
+ }
81
+
82
+ if (!data || data.length === 0) {
83
+ return errorResponse('No data provided. Pass data array, resultId from query_data, or sourceId + sql.');
84
+ }
85
+
86
+ const notes: string[] = [];
87
+ const columns = (args.columns as DataColumn[]) || inferColumns(data);
88
+ const maxAlternativeChartTypes = args.maxAlternativeChartTypes ?? 2;
89
+
90
+ const input: VisualizeInput = {
91
+ data,
92
+ intent: args.intent,
93
+ columns,
94
+ dataShapeHints: args.dataShapeHints,
95
+ forcePattern: args.pattern,
96
+ geoLevel: args.geoLevel,
97
+ geoRegion: args.geoRegion,
98
+ };
99
+
100
+ const result = selectPatterns(input);
101
+ const alternatives = result.alternatives.slice(0, maxAlternativeChartTypes);
102
+
103
+ const colorPrefs = (args.palette || args.highlight || args.colorField)
104
+ ? { palette: args.palette, highlight: args.highlight, colorField: args.colorField }
105
+ : undefined;
106
+ if (colorPrefs) {
107
+ const colorResult = applyColorPreferences(result.recommended.spec, colorPrefs, data);
108
+ notes.push(...colorResult.notes);
109
+ }
110
+
111
+ const spec = result.recommended.spec;
112
+ if (args.title) spec.title = args.title;
113
+ if (args.subtitle) spec.config = { ...spec.config, subtitle: args.subtitle };
114
+ const hasHtmlBuilder = spec && isHtmlPatternSupported(spec.pattern);
115
+
116
+ let outputHtml: string | undefined;
117
+ let finalSpec: VisualizationSpec | import('../../types.js').CompoundVisualizationSpec = spec;
118
+ if (hasHtmlBuilder && shouldCompound(spec, { compound: args.includeDataTable })) {
119
+ const compoundSpec = buildCompoundSpec(spec, columns);
120
+ outputHtml = buildCompoundHtml(compoundSpec);
121
+ finalSpec = compoundSpec;
122
+ } else if (hasHtmlBuilder) {
123
+ outputHtml = buildChartHtml(spec);
124
+ }
125
+
126
+ const alternativesMap = new Map<string, VisualizationSpec>();
127
+ for (const alt of alternatives) {
128
+ alternativesMap.set(alt.pattern, alt.spec);
129
+ }
130
+ const specId = specStore.save(finalSpec, columns, alternativesMap, data);
131
+
132
+ // Write HTML to disk
133
+ let writeResult: string;
134
+ if (outputHtml) {
135
+ try {
136
+ mkdirSync(dirname(args.writeTo), { recursive: true });
137
+ writeFileSync(args.writeTo, outputHtml, 'utf-8');
138
+ writeResult = `Wrote ${outputHtml.length} bytes to ${args.writeTo}`;
139
+ } catch (err) {
140
+ return errorResponse(`Failed to write to ${args.writeTo}: ${err instanceof Error ? err.message : String(err)}`);
141
+ }
142
+ } else {
143
+ writeResult = `No HTML builder for pattern "${spec.pattern}"`;
144
+ }
145
+
146
+ const compactResponse: Record<string, any> = {
147
+ specId,
148
+ writeTo: args.writeTo,
149
+ writeResult,
150
+ ...(notes.length > 0 ? { notes } : {}),
151
+ recommended: {
152
+ pattern: result.recommended.pattern,
153
+ title: spec.title,
154
+ reasoning: result.recommended.reasoning,
155
+ },
156
+ alternatives: alternatives.map(a => ({
157
+ pattern: a.pattern,
158
+ reasoning: a.reasoning,
159
+ })),
160
+ dataShape: {
161
+ rowCount: data.length,
162
+ columnCount: columns.length,
163
+ ...(queryMeta?.truncated ? { truncated: true, totalSourceRows: queryMeta.totalSourceRows } : {}),
164
+ },
165
+ };
166
+
167
+ if (isCompoundSpec(finalSpec)) {
168
+ compactResponse.compound = true;
169
+ }
170
+
171
+ // CLI tools NEVER return structuredContent - just text
172
+ return {
173
+ content: [{
174
+ type: 'text' as const,
175
+ text: JSON.stringify(compactResponse, null, 2),
176
+ }],
177
+ };
178
+ };
179
+ }
@@ -67,8 +67,6 @@ export const visualizeInputSchema = z.object({
67
67
  .describe('Geographic level: "country" (each row = a nation) or "subdivision" (each row = a state/province). Auto-detected if omitted.'),
68
68
  geoRegion: z.string().optional()
69
69
  .describe('Geographic region code: "world", ISO country code (US, CN, AU, etc.), or continent (EU, AF, AS, SA, NA, OC). Auto-detected if omitted.'),
70
- returnHtml: z.boolean().optional()
71
- .describe('Whether to return pre-rendered HTML in the response. Default: true. Set to false to save tokens — use screenshot(specId) to render later.'),
72
70
  });
73
71
 
74
72
  /**
@@ -93,7 +91,6 @@ export function handleVisualizeCore(
93
91
  maxAlternativeChartTypes?: number;
94
92
  geoLevel?: 'country' | 'subdivision';
95
93
  geoRegion?: string;
96
- returnHtml?: boolean;
97
94
  }, queryMeta?: { truncated?: boolean; totalSourceRows?: number }, extraMeta?: Partial<OperationMeta>) => {
98
95
  const start = Date.now();
99
96
  const notes: string[] = [];
@@ -193,13 +190,13 @@ export function handleVisualizeCore(
193
190
  },
194
191
  });
195
192
 
196
- const shouldReturnHtml = args.returnHtml !== false;
193
+ // Always include HTML — Desktop requires it for inline chart rendering
197
194
  return {
198
195
  content: [{
199
196
  type: 'text' as const,
200
197
  text: JSON.stringify(compactResponse, null, 2),
201
198
  }],
202
- ...(outputHtml && shouldReturnHtml ? {
199
+ ...(outputHtml ? {
203
200
  structuredContent: {
204
201
  specId,
205
202
  html: outputHtml,
@@ -1,180 +0,0 @@
1
- /**
2
- * MCP Tool: report_bug
3
- * Generates a sanitized bug report for GitHub issues.
4
- * No data values, connection strings, or file paths leave the machine.
5
- * Field names anonymized by default (opt-in to include real names).
6
- */
7
-
8
- import { z } from 'zod';
9
- import { createRequire } from 'node:module';
10
- import { platform, version as nodeVersion } from 'node:process';
11
- import { specStore } from '../spec-store.js';
12
- import { resultCacheStats } from './result-cache.js';
13
- import { operationLog } from './operation-log.js';
14
- import type { OperationEntry } from './operation-log.js';
15
- import { formatUptime } from './shared.js';
16
- import type { SourceManager } from '../../connectors/manager.js';
17
-
18
- const require = createRequire(import.meta.url);
19
- let dolexVersion: string;
20
- try {
21
- dolexVersion = require('../../../../package.json').version;
22
- } catch {
23
- dolexVersion = require('../../../package.json').version;
24
- }
25
-
26
- export const bugReportInputSchema = z.object({
27
- description: z.string().describe('What went wrong — describe the issue'),
28
- specId: z.string().optional().describe('Spec ID from a recent visualize/refine call to include context'),
29
- includeFieldNames: z.boolean().optional().describe('Include real field names in the report (default: false — fields anonymized as col_0, col_1)'),
30
- });
31
-
32
- export function anonymizeColumns(
33
- columns: { name: string; type: string }[],
34
- include: boolean,
35
- ): { name: string; type: string }[] {
36
- return columns.map((c, i) => ({
37
- name: include ? c.name : `col_${i}`,
38
- type: c.type,
39
- }));
40
- }
41
-
42
- export function sanitizeSpecConfig(config: Record<string, unknown>): Record<string, string> {
43
- const safe: Record<string, string> = {};
44
- for (const [key, val] of Object.entries(config)) {
45
- if (key.startsWith('_')) continue;
46
- if (typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') {
47
- safe[key] = String(val);
48
- } else if (val == null) {
49
- safe[key] = 'null';
50
- } else {
51
- safe[key] = typeof val;
52
- }
53
- }
54
- return safe;
55
- }
56
-
57
- export function sanitizeError(error: string): string {
58
- return error
59
- .replace(/\/[\w/.~-]+/g, '<path>')
60
- .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/gi, '<email>');
61
- }
62
-
63
- function formatDuration(ms: number): string {
64
- if (ms < 1000) return `${ms}ms`;
65
- return `${(ms / 1000).toFixed(1)}s`;
66
- }
67
-
68
- function buildOperationsTable(entries: OperationEntry[]): string {
69
- if (entries.length === 0) return '_No recent operations._';
70
-
71
- const rows = entries.map(e => {
72
- const status = e.success ? 'ok' : 'error';
73
- const pattern = e.meta.pattern || '-';
74
- const shape = e.meta.dataShape
75
- ? `${e.meta.dataShape.rowCount}r x ${e.meta.dataShape.columnCount}c`
76
- : '-';
77
- return `| ${e.toolName} | ${status} | ${formatDuration(e.durationMs)} | ${pattern} | ${shape} |`;
78
- });
79
-
80
- return [
81
- '| Tool | Status | Duration | Pattern | Shape |',
82
- '|------|--------|----------|---------|-------|',
83
- ...rows,
84
- ].join('\n');
85
- }
86
-
87
- interface ReportDeps {
88
- sourceManager: SourceManager;
89
- serverStartTime: number;
90
- }
91
-
92
- export function handleReportBug(deps: ReportDeps) {
93
- return async (args: z.infer<typeof bugReportInputSchema>) => {
94
- const includeFieldNames = args.includeFieldNames ?? false;
95
- const sections: string[] = [];
96
-
97
- sections.push(`## Description\n\n${args.description}`);
98
-
99
- sections.push([
100
- '## Environment',
101
- '',
102
- `- **Dolex**: ${dolexVersion}`,
103
- `- **Node.js**: ${nodeVersion}`,
104
- `- **Platform**: ${platform}`,
105
- ].join('\n'));
106
-
107
- if (args.specId) {
108
- const stored = specStore.get(args.specId);
109
- if (stored) {
110
- const spec = stored.spec as any;
111
- const columns = anonymizeColumns(
112
- stored.columns.map(c => ({ name: c.name, type: c.type })),
113
- includeFieldNames,
114
- );
115
- const contextLines = [
116
- '## Visualization Context',
117
- '',
118
- `- **Pattern**: ${spec.pattern}`,
119
- `- **Data shape**: ${spec.data?.length ?? '?'} rows x ${columns.length} columns`,
120
- `- **Columns**: ${columns.map(c => `${c.name} (${c.type})`).join(', ')}`,
121
- ];
122
-
123
- if (spec.encoding) {
124
- const fieldNameMap = new Map<string, string>();
125
- if (!includeFieldNames) {
126
- stored.columns.forEach((c, i) => fieldNameMap.set(c.name, `col_${i}`));
127
- }
128
- const encodingFields: string[] = [];
129
- for (const [channel, enc] of Object.entries(spec.encoding)) {
130
- const field = (enc as any)?.field;
131
- if (field) {
132
- const displayName = fieldNameMap.get(field) ?? field;
133
- encodingFields.push(`${channel}=${displayName}`);
134
- }
135
- }
136
- if (encodingFields.length > 0) {
137
- contextLines.push(`- **Encoding**: ${encodingFields.join(', ')}`);
138
- }
139
- }
140
-
141
- if (spec.config) {
142
- const safeConfig = sanitizeSpecConfig(spec.config);
143
- const configStr = Object.entries(safeConfig)
144
- .map(([k, v]) => `${k}=${v}`)
145
- .join(', ');
146
- if (configStr) {
147
- contextLines.push(`- **Config**: ${configStr}`);
148
- }
149
- }
150
-
151
- sections.push(contextLines.join('\n'));
152
- }
153
- }
154
-
155
- const ops = operationLog.getAll();
156
- sections.push(`## Recent Operations\n\n${buildOperationsTable(ops)}`);
157
-
158
- const specStats = specStore.stats();
159
- const resultStats = resultCacheStats();
160
- const datasets = deps.sourceManager.list();
161
-
162
- sections.push([
163
- '## Server State',
164
- '',
165
- `- **Uptime**: ${formatUptime(Date.now() - deps.serverStartTime)}`,
166
- `- **Cached specs**: ${specStats.entries}`,
167
- `- **Cached results**: ${resultStats.entries}`,
168
- `- **Datasets**: ${datasets.length}`,
169
- ].join('\n'));
170
-
171
- const report = sections.join('\n\n');
172
-
173
- return {
174
- content: [{
175
- type: 'text' as const,
176
- text: report,
177
- }],
178
- };
179
- };
180
- }