@schemacast/mcp 0.0.0-stage → 0.5.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,7 @@
1
+ /**
2
+ * The report logic lives in `@schemacast/core` so the playground shows exactly what an MCP agent
3
+ * receives; this module keeps the MCP package's historical import path.
4
+ */
5
+ export { createVisualizeReport, getConfidenceBand, resolveFieldUnit, REPORTED_VIEW_LIMIT, SCORE_MEANING_NOTE, PLAUSIBLE_BAND_MIN_SCORE, DETECTED_BAND_MIN_SCORE, } from '@schemacast/core';
6
+ export type { ConfidenceBand, IntentReport, ReportedView, VisualizeReport, VisualizeReportOptions, } from '@schemacast/core';
7
+ //# sourceMappingURL=visualize-report.d.ts.map
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The report logic lives in `@schemacast/core` so the playground shows exactly what an MCP agent
3
+ * receives; this module keeps the MCP package's historical import path.
4
+ */
5
+ export { createVisualizeReport, getConfidenceBand, resolveFieldUnit, REPORTED_VIEW_LIMIT, SCORE_MEANING_NOTE, PLAUSIBLE_BAND_MIN_SCORE, DETECTED_BAND_MIN_SCORE, } from '@schemacast/core';
6
+ //# sourceMappingURL=visualize-report.js.map
@@ -0,0 +1,22 @@
1
+ import { type VisualSpec } from '@schemacast/core';
2
+ import { type VisualizeReport } from './visualize-report.js';
3
+ /**
4
+ * Describes the selected view, ranked alternates with confidence bands, fields used and ignored,
5
+ * and assumptions, as the text half of a `visualize_json` result.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const summary = createVisualizeJsonSummary(data, spec, 'compare revenue');
10
+ * ```
11
+ */
12
+ export declare function createVisualizeJsonSummary(input: unknown, spec: VisualSpec, intent?: string): string;
13
+ /**
14
+ * Formats an existing report as the human-readable summary text.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const text = formatVisualizeSummary(spec, createVisualizeReport(data, spec));
19
+ * ```
20
+ */
21
+ export declare function formatVisualizeSummary(spec: VisualSpec, report: VisualizeReport): string;
22
+ //# sourceMappingURL=visualize-summary.d.ts.map
@@ -0,0 +1,125 @@
1
+ import { findSecondaryAxisSeries, measureSeriesMagnitude, UNIT_INTERVAL_MAX, } from '@schemacast/core';
2
+ import { createVisualizeReport, resolveFieldUnit, } from './visualize-report.js';
3
+ /**
4
+ * Describes the selected view, ranked alternates with confidence bands, fields used and ignored,
5
+ * and assumptions, as the text half of a `visualize_json` result.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const summary = createVisualizeJsonSummary(data, spec, 'compare revenue');
10
+ * ```
11
+ */
12
+ export function createVisualizeJsonSummary(input, spec, intent) {
13
+ return formatVisualizeSummary(spec, createVisualizeReport(input, spec, { intent }));
14
+ }
15
+ /**
16
+ * Formats an existing report as the human-readable summary text.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const text = formatVisualizeSummary(spec, createVisualizeReport(data, spec));
21
+ * ```
22
+ */
23
+ export function formatVisualizeSummary(spec, report) {
24
+ const primary = report.views[0];
25
+ const intentStatus = report.intent === undefined
26
+ ? ''
27
+ : `, ${report.intent.applied ? 'intent applied' : 'intent not applied'}; base ${report.intent.baseScore.toFixed(2)}`;
28
+ const lines = [
29
+ `Primary view: ${spec.primaryView.archetype} (score ${spec.primaryView.score.toFixed(2)}${intentStatus}; ${primary?.band ?? 'default'}).${describeBindings(spec)}`,
30
+ 'Top views:',
31
+ ...report.views.map((view, index) => `${index + 1}. ${view.archetype} ${view.score.toFixed(2)} [${view.band}]: ${view.reason}`),
32
+ ...(report.rejectedViews.length === 0
33
+ ? []
34
+ : [
35
+ 'Rejected views:',
36
+ ...report.rejectedViews.map((view) => `- ${view.archetype}: ${view.reason}`),
37
+ ]),
38
+ `Fields used: ${formatFieldsUsed(report)}. Fields ignored: ${formatFieldsIgnored(report)}.`,
39
+ ];
40
+ if (report.assumptions.length > 0) {
41
+ lines.push('Assumptions:', ...report.assumptions.map((assumption) => `- ${assumption}`));
42
+ }
43
+ lines.push(report.scoreNote);
44
+ return lines.join('\n');
45
+ }
46
+ function formatFieldsIgnored(report) {
47
+ if (report.fieldsIgnored.length === 0) {
48
+ return 'none';
49
+ }
50
+ return report.fieldsIgnored
51
+ .map((key) => {
52
+ const reason = report.ignoredReasons[key];
53
+ return reason === undefined ? key : `${key} (${reason})`;
54
+ })
55
+ .join(', ');
56
+ }
57
+ function formatFieldsUsed(report) {
58
+ const roles = Object.entries(report.fieldsUsed).map(([role, keys]) => `${role}: ${keys.join(', ')}`);
59
+ return roles.length === 0 ? 'none' : roles.join('; ');
60
+ }
61
+ function describeBindings(spec) {
62
+ const { x, y = [] } = spec.primaryView.bindings;
63
+ if (x === undefined && y.length === 0) {
64
+ return '';
65
+ }
66
+ if (spec.primaryView.archetype === 'kpi-grid') {
67
+ return ` Metrics shown: ${y.map((key) => describeSeries(spec, key)).join(', ')}.`;
68
+ }
69
+ const secondarySeries = findSecondaryAxisKeys(spec, y);
70
+ const bindingParts = [];
71
+ if (x !== undefined) {
72
+ bindingParts.push(`x: ${x}`);
73
+ }
74
+ if (secondarySeries.size === 0) {
75
+ if (y.length > 0) {
76
+ bindingParts.push(`y: ${y.map((key) => describeSeries(spec, key)).join(', ')}`);
77
+ }
78
+ }
79
+ else {
80
+ const leftKeys = y.filter((key) => !secondarySeries.has(key));
81
+ const rightKeys = y.filter((key) => secondarySeries.has(key));
82
+ bindingParts.push(`left: ${leftKeys.map((key) => describeSeries(spec, key)).join(', ')}`, `right${describeRightRange(spec, rightKeys)}: ${rightKeys.map((key) => describeSeries(spec, key)).join(', ')}`);
83
+ }
84
+ return ` Axes/series: ${bindingParts.join('; ')}.`;
85
+ }
86
+ /** ` (0–1)` when every series on the right axis stays between 0 and 1, so the axis range is known. */
87
+ function describeRightRange(spec, rightKeys) {
88
+ const rows = getPlottedRows(spec);
89
+ const isUnitInterval = rightKeys.every((key) => {
90
+ const field = findField(spec.fields, key);
91
+ return measureSeriesMagnitude(rows, key, field?.semanticType) <= UNIT_INTERVAL_MAX;
92
+ });
93
+ return isUnitInterval ? ' (0–1)' : '';
94
+ }
95
+ function getPlottedRows(spec) {
96
+ return spec.primaryView.archetype === 'bar-chart'
97
+ ? (spec.primaryView.data ?? spec.data)
98
+ : spec.data;
99
+ }
100
+ function describeSeries(spec, key) {
101
+ const unit = resolveFieldUnit(spec, key);
102
+ return unit === undefined ? key : `${key} (${unit})`;
103
+ }
104
+ function findSecondaryAxisKeys(spec, yKeys) {
105
+ const firstKey = yKeys[0];
106
+ if (firstKey === undefined || yKeys.length < 2) {
107
+ return new Set();
108
+ }
109
+ const firstUnit = fieldUnitKey(spec, firstKey);
110
+ const differentUnits = yKeys.some((key) => fieldUnitKey(spec, key) !== firstUnit);
111
+ if (differentUnits) {
112
+ return new Set(yKeys.filter((key) => fieldUnitKey(spec, key) !== firstUnit));
113
+ }
114
+ const rows = getPlottedRows(spec);
115
+ const magnitudes = yKeys.map((key) => measureSeriesMagnitude(rows, key, findField(spec.fields, key)?.semanticType));
116
+ const rightIndexes = findSecondaryAxisSeries(magnitudes, spec.primaryView.archetype === 'line-chart');
117
+ return new Set(yKeys.filter((_, index) => rightIndexes.includes(index)));
118
+ }
119
+ function findField(fields, key) {
120
+ return fields.find((field) => field.key === key);
121
+ }
122
+ function fieldUnitKey(spec, key) {
123
+ return `${findField(spec.fields, key)?.semanticType ?? 'unknown'}:${resolveFieldUnit(spec, key) ?? 'unitless'}`;
124
+ }
125
+ //# sourceMappingURL=visualize-summary.js.map
@@ -0,0 +1,80 @@
1
+ import type { AnySchema, ZodRawShapeCompat } from '@modelcontextprotocol/sdk/server/zod-compat.js';
2
+ import type { McpServer, RegisteredTool, ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
4
+ type ToolHandler = (...parameters: never[]) => CallToolResult | Promise<CallToolResult>;
5
+ /**
6
+ * Metadata to copy into an MCP tool config when registering a wrapped handler.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * server.registerTool('existing_tool', { _meta: wrappedHandler._meta }, wrappedHandler);
11
+ * ```
12
+ */
13
+ export interface AutoVisualToolMetadata extends Record<string, unknown> {
14
+ readonly ui: {
15
+ readonly resourceUri: string;
16
+ };
17
+ }
18
+ /**
19
+ * A wrapped MCP handler with the resource metadata needed by its tool registration.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * const wrappedHandler = withAutoVisual(existingHandler);
24
+ * server.registerTool('existing_tool', { _meta: wrappedHandler._meta }, wrappedHandler);
25
+ * ```
26
+ */
27
+ export type AutoVisualToolHandler<Handler extends ToolHandler> = ((...parameters: Parameters<Handler>) => Promise<CallToolResult>) & {
28
+ readonly _meta: AutoVisualToolMetadata;
29
+ };
30
+ /**
31
+ * Optional view-selection settings for {@link withAutoVisual}.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const options: WithAutoVisualOptions = {
36
+ * intent: 'show regional revenue',
37
+ * select: (result) => result.structuredContent?.report,
38
+ * };
39
+ * ```
40
+ */
41
+ export interface WithAutoVisualOptions {
42
+ /** Optional intent forwarded to `cast()`. */
43
+ intent?: string;
44
+ /** Selects the portion of the original result that should be visualized. */
45
+ select?: (result: CallToolResult) => unknown;
46
+ }
47
+ /**
48
+ * Adds a VisualSpec sidecar to an existing MCP tool handler without changing its content or
49
+ * structured data. The returned function carries `_meta.ui.resourceUri` for tool registration.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const wrapped = withAutoVisual(existingHandler, {
54
+ * select: (result) => result.structuredContent?.report,
55
+ * });
56
+ * server.registerTool('existing_tool', { _meta: wrapped._meta }, wrapped);
57
+ * ```
58
+ */
59
+ export declare function withAutoVisual<Args extends undefined | ZodRawShapeCompat | AnySchema>(handler: ToolCallback<Args>, options?: WithAutoVisualOptions): ToolCallback<Args> & {
60
+ readonly _meta: AutoVisualToolMetadata;
61
+ };
62
+ export declare function withAutoVisual<Handler extends ToolHandler>(handler: Handler, options?: WithAutoVisualOptions): AutoVisualToolHandler<Handler>;
63
+ /**
64
+ * Registers an existing MCP handler with the shared VisualSpec UI resource.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * registerAutoVisualTool(server, 'existing_tool', config, existingHandler);
69
+ * ```
70
+ */
71
+ export declare function registerAutoVisualTool<InputArgs extends undefined | ZodRawShapeCompat | AnySchema = undefined, OutputArgs extends ZodRawShapeCompat | AnySchema = AnySchema>(server: McpServer, name: string, config: {
72
+ title?: string;
73
+ description?: string;
74
+ inputSchema?: InputArgs;
75
+ outputSchema?: OutputArgs;
76
+ annotations?: ToolAnnotations;
77
+ _meta?: Record<string, unknown>;
78
+ }, handler: ToolCallback<InputArgs>): RegisteredTool;
79
+ export {};
80
+ //# sourceMappingURL=with-auto-visual.d.ts.map
@@ -0,0 +1,106 @@
1
+ import { cast } from '@schemacast/core';
2
+ import { AUTO_VISUAL_RESULT_META_KEY } from './auto-visual-meta.js';
3
+ import { UI_RESOURCE_URI } from './ui-resource.js';
4
+ export function withAutoVisual(handler, options = {}) {
5
+ const wrappedHandler = async (...parameters) => {
6
+ const result = await handler(...parameters);
7
+ const data = options.select === undefined ? selectResultData(result) : options.select(result);
8
+ if (!isUsableJsonValue(data)) {
9
+ return result;
10
+ }
11
+ const spec = cast(data, options.intent === undefined ? undefined : { intent: options.intent });
12
+ return {
13
+ ...result,
14
+ _meta: {
15
+ ...result._meta,
16
+ [AUTO_VISUAL_RESULT_META_KEY]: spec,
17
+ },
18
+ };
19
+ };
20
+ return Object.assign(wrappedHandler, {
21
+ _meta: {
22
+ ui: {
23
+ resourceUri: UI_RESOURCE_URI,
24
+ },
25
+ },
26
+ });
27
+ }
28
+ /**
29
+ * Registers an existing MCP handler with the shared VisualSpec UI resource.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * registerAutoVisualTool(server, 'existing_tool', config, existingHandler);
34
+ * ```
35
+ */
36
+ export function registerAutoVisualTool(server, name, config, handler) {
37
+ const wrappedHandler = withAutoVisual(handler);
38
+ const existingUi = config._meta?.ui;
39
+ const uiMetadata = isPlainRecord(existingUi) ? existingUi : {};
40
+ const appConfig = {
41
+ ...config,
42
+ _meta: {
43
+ ...config._meta,
44
+ ui: {
45
+ ...uiMetadata,
46
+ ...wrappedHandler._meta.ui,
47
+ },
48
+ },
49
+ };
50
+ return server.registerTool(name, appConfig, wrappedHandler);
51
+ }
52
+ function selectResultData(result) {
53
+ if (isUsableJsonValue(result.structuredContent)) {
54
+ return result.structuredContent;
55
+ }
56
+ for (const item of result.content) {
57
+ if (item.type !== 'text' || item.text.trim().length === 0) {
58
+ continue;
59
+ }
60
+ try {
61
+ const parsed = JSON.parse(item.text);
62
+ if (isUsableJsonValue(parsed)) {
63
+ return parsed;
64
+ }
65
+ }
66
+ catch {
67
+ continue;
68
+ }
69
+ }
70
+ return undefined;
71
+ }
72
+ function isUsableJsonValue(value) {
73
+ if (value === undefined ||
74
+ value === null ||
75
+ (typeof value === 'string' && value.trim().length === 0) ||
76
+ (Array.isArray(value) && value.length === 0) ||
77
+ (isPlainRecord(value) && Object.keys(value).length === 0)) {
78
+ return false;
79
+ }
80
+ return isJsonValue(value, new Set());
81
+ }
82
+ function isJsonValue(value, ancestors) {
83
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') {
84
+ return true;
85
+ }
86
+ if (typeof value === 'number') {
87
+ return Number.isFinite(value);
88
+ }
89
+ if (typeof value !== 'object' || ancestors.has(value)) {
90
+ return false;
91
+ }
92
+ ancestors.add(value);
93
+ const valid = Array.isArray(value)
94
+ ? value.every((item) => isJsonValue(item, ancestors))
95
+ : isPlainRecord(value) && Object.values(value).every((item) => isJsonValue(item, ancestors));
96
+ ancestors.delete(value);
97
+ return valid;
98
+ }
99
+ function isPlainRecord(value) {
100
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
101
+ return false;
102
+ }
103
+ const prototype = Object.getPrototypeOf(value);
104
+ return prototype === Object.prototype || prototype === null;
105
+ }
106
+ //# sourceMappingURL=with-auto-visual.js.map
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@schemacast/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.5.0",
4
+ "description": "MCP server and UI resource for rendering schemacast VisualSpecs.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "keywords": [
11
+ "schemacast",
12
+ "mcp",
13
+ "model-context-protocol",
14
+ "visualization",
15
+ "json"
16
+ ],
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "bin": {
20
+ "schemacast-mcp": "./dist/main.js"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "!dist/**/*.map"
31
+ ],
32
+ "dependencies": {
33
+ "@modelcontextprotocol/ext-apps": "1.7.5",
34
+ "@modelcontextprotocol/sdk": "1.32.2",
35
+ "@schemacast/core": "0.5.0",
36
+ "zod": "4.2.0"
37
+ },
38
+ "devDependencies": {
39
+ "@schemacast/react": "0.5.0",
40
+ "@types/node": "^22.0.0",
41
+ "@types/react": "^19.0.0",
42
+ "@types/react-dom": "^19.0.0",
43
+ "esbuild": "^0.25.0",
44
+ "react": "^19.0.0",
45
+ "react-dom": "^19.0.0",
46
+ "typescript": "^5.7.0"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "scripts": {
52
+ "typecheck": "tsc --noEmit",
53
+ "build": "pnpm --filter @schemacast/react build && tsc && node --experimental-strip-types scripts/build-ui.ts",
54
+ "start": "node dist/main.js"
55
+ }
6
56
  }