@outsidedata/dolex 4.0.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.
@@ -81,9 +81,6 @@ export const refineInputSchema = z.object({
81
81
  removeTable: z.boolean().optional().describe('Remove the data table from a compound chart'),
82
82
  layout: z.enum(['rows', 'columns']).optional().describe('Compound layout'),
83
83
  hideColumns: z.array(z.string()).optional().describe('Hide columns from the data table'),
84
-
85
- returnHtml: z.boolean().optional()
86
- .describe('Whether to return pre-rendered HTML in the response. Default: true. Set to false to save tokens.'),
87
84
  });
88
85
 
89
86
  type RefineArgs = z.infer<typeof refineInputSchema>;
@@ -455,8 +452,8 @@ export function handleRefine() {
455
452
  },
456
453
  });
457
454
 
458
- const shouldReturnHtml = args.returnHtml !== false;
459
- if (outputHtml && shouldReturnHtml) {
455
+ // Always include HTML — Desktop requires it for inline chart rendering
456
+ if (outputHtml) {
460
457
  return htmlResponse(body, outputHtml);
461
458
  }
462
459
  return { content: [{ type: 'text' as const, text: JSON.stringify(body, null, 2) }] };
@@ -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,