@outsidedata/dolex 4.0.0 → 6.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
+ }
@@ -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,
@@ -1,35 +0,0 @@
1
- import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import { z } from 'zod';
3
-
4
- export function registerPrompts(server: McpServer) {
5
- server.registerPrompt(
6
- 'explore-data',
7
- {
8
- title: 'Explore a Dataset',
9
- description: 'Drop a data file and get automatic analysis — like having a data analyst at your desk',
10
- argsSchema: {
11
- path: z.string().describe('Path to a CSV file or directory of CSV files'),
12
- },
13
- },
14
- async ({ path }) => ({
15
- messages: [{
16
- role: 'user' as const,
17
- content: {
18
- type: 'text' as const,
19
- text: [
20
- `I want to explore a dataset. The file path is: ${path}`,
21
- '',
22
- 'Please:',
23
- '1. Load it using load_csv',
24
- '2. Call analyze_data to get an automatic analysis plan',
25
- '3. For each step in the plan, call visualize with sourceId, sql, and intent using one of the suggested patterns',
26
- '4. After each chart, write a 2-3 sentence finding explaining what the data reveals — be specific about numbers, trends, and outliers',
27
- '5. End with a "Key Takeaways" summary',
28
- '',
29
- 'Use the full Dolex pattern library — the analysis plan suggests patterns like violin plots, sparkline grids, treemaps, and beeswarms. Use them instead of defaulting to bar charts.',
30
- ].join('\n'),
31
- },
32
- }],
33
- }),
34
- );
35
- }