@malloydata/malloyyo 0.2.46 → 0.2.48

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.
Files changed (2) hide show
  1. package/dist/index.js +214 -72
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { Command } from "commander";
5
- import { resolve as resolve3 } from "node:path";
5
+ import { resolve as resolve4 } from "node:path";
6
6
 
7
7
  // src/config.ts
8
8
  import { readFileSync, existsSync } from "node:fs";
@@ -202,6 +202,7 @@ var contentFiles = {
202
202
  "dashboards/authoring.md": '---\ndescription: How to author a dashboard \u2014 a self-contained file in the dashboards/ directory that defines its own query; the entry point for dashboard how-to\n---\n\n# Authoring dashboards\n\nA dashboard is a **self-contained `.malloy` file in the `dashboards/`\ndirectory**. The file IS the dashboard: it imports the model parts it needs,\ndefines its query (with the filtering it applies), and tags it. No manifest, and\nfor the basic case no JavaScript. Preview with `malloyyo dashboard dev`; check\nwith `malloyyo lint`. Requires `@malloydata/malloy` 0.0.423+.\n\nRelated: `yo_help dashboards/givens-and-controls` (filter controls),\n`dashboards/grid-layout` (columns/colspan/break), `dashboards/charts` (the\n`# bar_chart`/`# line_chart` tags and their channel rules),\n`dashboards/custom-components` (a flat `<name>.jsx`), `dashboards/vega-charts`\n(`<VegaChart>`).\n\n> **Need a chart the `# bar_chart`/`# line_chart`/`# shape_map` tags can\'t do?**\n> Use the `<VegaChart>` COMPONENT (a Vega-Lite spec over query rows) \u2014 NOT a `#`\n> tag; there is no `# vega_lite`. See `yo_help dashboards/vega-charts`.\n\n## The layout\n\n```\nmodel/\n ecommerce.malloy # sources, reusable views/measures, # drill tags\n givens.malloy # given: declarations (the filter controls)\n index.malloy # imports/exports sources \u2014 the MCP/data surface ONLY\n dashboards/\n overview.malloy # one dashboard; the FILENAME is its name/slug\n overview.jsx # optional custom component for overview\n```\n\n**The filename is the dashboard\'s name** \u2014 its URL slug, its `# drill` target,\nand the basename of its optional component. Discovery globs\n`dashboards/*.malloy` and compiles EACH as its own entry \u2014 so dashboards are NOT\ndeclared in, or exported through, `index.malloy` (`index.malloy` is just the\n`query`/`describe_source` data surface).\n\n## Preferred: put the query IN the dashboard file\n\nDefine the query right in `dashboards/<name>.malloy` and tag it `# artifact`, so\nthe given mapping (the `where: \u2026 ~ $GIVEN`) is visible next to the dashboard:\n\n```malloy\n// dashboards/overview.malloy\n##! experimental.givens\nimport "../ecommerce.malloy" // BARE import: source + givens in scope\n\n#" Business health at a glance \u2014 sales, margin, orders.\n# artifact { title="Business Overview" } dashboard {columns=6}\nquery: overview is order_items -> {\n where: // the given mapping, HERE\n inventory_items.product_brand ~ $BRAND, // multi-filter where: is\n inventory_items.product_category ~ $CATEGORY, // COMMA separated\n created_at ~ $PERIOD\n # colspan=2\n aggregate: total_sales, total_gross_margin, order_count\n # colspan=3\n nest:\n # line_chart\n sales_trend is by_month\n top_brands\n # shape_map\n sales_by_state\n}\n```\n\nThat\'s a complete dashboard: the runtime auto-renders a title (the tag\'s\n`title`, else the `#"` doc), a control for every given the query references, and\nthe result panel. `# artifact` DECLARES the dashboard; `# dashboard {columns=6}`\nis the renderer tag that draws it as KPI tiles + a card grid \u2014 partners, on the\nsame line. Grid rules: `yo_help dashboards/grid-layout`.\n\n**You know you\'re doing it right when the `where: foo ~ $FOO` is in the DASHBOARD\nfile, not the model.** Keep the model\'s sources/views reusable and given-free;\neach dashboard decides its own filtering.\n\n**The bare import is required for controls.** A control renders only when the\ngiven\'s DECLARATION is in the dashboard file\'s scope \u2014 a bare\n`import "../ecommerce.malloy"` (or `import "../givens.malloy"`) brings them all;\nthe runtime shows a control for exactly the givens the query references. A\nselective `import { order_items } from \u2026` brings the filter but NOT the control.\n\nKeep the FILENAME as the name \u2014 don\'t set `name=`, so the URL, the\n`# drill { to=\u2026 }`, and the component basename all agree (one source of truth).\n\n## Other forms\n\n- **A view of a source you extend in the file** \u2014 tag the dashboard `view:` with\n `# artifact` (runs as `<source> -> <view>`). Good when the dashboard needs\n helper views defined alongside it.\n- **Compose existing views**: a model-level `## artifact { tiles=["a -> b", "c -> d"]\n dashboard_columns=6 }` (`##`, ONE line) names several views. Each tile runs as\n its own query (in parallel), and the results are combined into ONE\n `# dashboard` that Malloy\'s dashboard renderer lays out \u2014 so it looks exactly\n like the equivalent single-query dashboard: `dashboard_columns=N` sets the grid\n and `# colspan=N` / `# break` on the tile VIEWS place them. A tile that returns\n a SINGLE ROW with no group-by (an aggregate view) is merged in as top-level KPI\n tiles rather than a card (its `# colspan` is spread across those KPIs). The\n dashboard paints once the tiles are ready, with a single early paint if one tile\n straggles so a slow tile can\'t hold up the rest. Use for multi-tile /\n cross-source; prefer the inline query whenever a dashboard has its own filtering.\n- A `dashboards/*.malloy` with NO `# artifact`/`## artifact` is a shared INCLUDE\n (skipped by discovery) \u2014 put helper sources/views there for several dashboards\n to import.\n\n## Givens (filter controls)\n\nDeclare givens as `filter<T>` in the MODEL (`givens.malloy` or the source file) \u2014\nthey\'re shared and used by the MCP surface too; each dashboard APPLIES them in\nits `where:`. Full control reference: `yo_help dashboards/givens-and-controls`.\nPer-dashboard starting values go in the tag:\n\n```malloy\n# artifact { title="Ford recalls" givens { MANUFACTURER=f\'Ford Motor Company\' } }\n```\n\n## Drill from a dimension\n\n`# drill` on a source `dimension:` (in the model) makes its cells clickable \u2014\nopening another dashboard (seeding the value) or filtering in place:\n\n```malloy\ndimension:\n # drill { to=[category_explorer, self] }\n category is inventory_items.product_category\n```\n\n`to` is a list; each is a **dashboard slug** (a `dashboards/<slug>.malloy`\nfilename) \u2192 opens it, seeding the value into the given named like the dimension\nUPPER-cased (`category` \u2192 `CATEGORY`), or **`self`** \u2192 filter the current\ndashboard in place. Add `given=` when the target given differs. `lint` VERIFIES\nevery `to=` slug resolves to a real dashboard file (a typo/renamed dashboard\nfails loudly, not at click time).\n\n> **malloy#2979 (fixed in 0.0.423):** a `# drill` on a bare `group_by: name` was\n> dropped when nested through `+ {\u2026}`. Put it on the source `dimension:`, or use\n> `group_by: name is concat(name,\'\')`.\n\n## Custom component (optional)\n\nFor bespoke layout/charts, add a flat sibling `dashboards/<name>.jsx` (or\n`.tsx`). Only React + `@malloyyo/dashboard` importable (sandboxed). A bare\n`<Panel/>` renders the whole dashboard; a `<Panel query="\u2026"/>` /\n`<VegaChart query="\u2026"/>` runs a query DEFINED in this dashboard file (by name) or\na `source -> view`. `lint` checks each `query="\u2026"` still resolves. See `yo_help\ndashboards/custom-components`.\n\n## Rules\n- Each dashboard is one `dashboards/<name>.malloy`; the filename is the slug.\n Prefer the inline `query: \u2026 # artifact` form \u2014 the `where: ~ $GIVEN` lives in\n the dashboard file.\n- Bare-import the model (and/or `givens.malloy`) so the controls render.\n- Givens are `filter<T>` declared in the model; options come from `# suggest {\u2026}`;\n interactivity = setting given values, not rewriting query text.\n- `index.malloy` is the data surface, NOT where dashboards live.\n- If a query/given you need is missing, add it (check with `describe_source`).\n\n## Preview & validate\n`malloyyo dashboard dev` \u2192 open the URL; `.malloy`/`.jsx` edits hot-reload.\n`malloyyo lint` checks each dashboard file on its own: it compiles as its entry;\neach tile/query and `# suggest` compiles; `dashboard_columns` is a positive int;\nthe component compiles and its `query="\u2026"` resolve; no duplicate names, no\norphaned component; every `# drill { to=\u2026 }` resolves. Tight loop: the local\n`malloyyo mcp --develop` server hot-reloads edits \u2014 `query(execute:false)` to\ncompile-check, `execute:true` to run. Don\'t validate against a hosted/claude.ai\nconnector \u2014 it serves the PUBLISHED model (stale until `malloyyo publish`).\n',
203
203
  "dashboards/charts.md": "# Charts (`# bar_chart`, `# line_chart`, \u2026)\n\nThe renderer's built-in chart tags cover most dashboard tiles. Tag a nested view\nand it draws:\n\n```malloy\nnest:\n # bar_chart\n sales_by_brand\n # line_chart\n sales_by_month\n```\n\nRelated: `yo_help dashboards/grid-layout` (where tiles sit),\n`dashboards/vega-charts` (`<VegaChart>`, for shapes these tags can't express),\n`dashboards/authoring` (the dashboard file itself).\n\n## Channels: name them, don't leave them to be guessed\n\nA chart has three channels \u2014 **x** (the category axis), **y** (the value), and\n**series** (the colour split). Set them on the tag:\n\n```malloy\n# bar_chart { x=weekday y=drunk }\n# bar_chart { x=nickname y=flight_count series=destination }\n# line_chart { x=sale_date y=['sales', 'cost'] }\n```\n\nLeft unset, the renderer infers them: x prefers a time dimension and otherwise\ntakes the first dimension, y takes the first aggregate, and **series takes any\ndimension left over**. That last rule is the one that surprises people \u2014 see\nbelow. Naming `x` and `y` explicitly costs one line and removes the guesswork.\n\nOther properties: `.stack`, `.size` (`spark`/`xs`/`sm`/`md`/`lg`/`xl`/`2xl`, or\n`size.width` / `size.height`), `.x.limit`, `.series.limit`, and `.independent`\non any channel for nested charts.\n\n## THE RULE: charts count DIMENSIONS, not columns\n\nA chart can carry **one x dimension and one series dimension**. The renderer\ncounts the *dimensions* in the result (`group_by` fields \u2014 not aggregates) and:\n\n- **two dimensions, only `x` named** \u2192 the spare one is promoted to a colour\n series, whether or not you wanted a legend\n- **three or more dimensions, none tagged `series`** \u2192 it refuses:\n *\"Too many dimensions. A bar chart can have at most 2 dimensions: 1 for the x\n axis, and 1 for the series. To use 3+ dimensions, explicitly tag multiple\n fields as series.\"*\n\nThat last sentence is the escape hatch: 3+ dimensions is legal if you say which\nones are the series. What is NOT legal is leaving it to be inferred. If you\ngenuinely want a third dimension in the picture, name it; if you don't, the\nproblem is that a field you didn't think of as a dimension is one.\n\nAggregates are exempt. A result can carry as many measures as you like \u2014 only\nthe ones named in `y` (or the first, if `y` is unset) get plotted, and the rest\nare ignored rather than turned into channels.\n\n**`# hidden` does not exempt a dimension from this count.** It hides a field in\ntables, `big_value` comparisons and `# link` targets; it has no effect on chart\nchannel assignment. A `# hidden` group_by is still a dimension and will still\nbecome a series.\n\n## Sorting a named axis (the common case this rule makes hard)\n\nYou want an axis labelled `Sunday \u2026 Saturday`, or `Jan \u2026 Dec`, in *that* order \u2014\nnot alphabetical. The label has to be a string, but the sort key is a number, and\nthe naive fixes both fail:\n\n```malloy\n// WRONG \u2014 two dimensions: weekday_num becomes a colour series.\ngroup_by:\n # hidden\n weekday_num is day_of_week(exit_date)\n weekday is pick 'Sunday' when day_of_week(exit_date) = 1 \u2026\n```\n\n```malloy\n// ALSO WRONG \u2014 a `select:` stage is a projection, so it has no measures:\n// every column becomes a dimension and a 3-column result is rejected.\n} -> {\n select: weekday is pick 'Sunday' when weekday_num = 1 \u2026 , drunk, avg_price\n}\n```\n\n**Make the sort key a MEASURE.** Measures aren't dimensions, so a sort key\nexpressed as one can never be promoted to a channel:\n\n```malloy\n# bar_chart { x=weekday y=drunk }\nview: by_weekday is {\n group_by: weekday is\n pick 'Sunday' when day_of_week(exit_date) = 1\n pick 'Monday' when day_of_week(exit_date) = 2\n \u2026\n else 'Saturday'\n aggregate:\n drunk\n weekday_sort is min(day_of_week(exit_date)) // orders rows; never a channel\n order_by: weekday_sort asc\n}\n```\n\nOne dimension reaches the chart, the rows arrive in the order you asked for, and\na bar chart preserves query row order for a categorical axis. The same shape\nworks for months (`min(month(date))`), fiscal periods, size buckets, and any\nother \"display a name, sort by a number\" axis.\n\n> `min()` because a sort key needs *some* aggregate function and every row in the\n> group shares the value; `max()` is equally fine.\n\n## Deciding which tile is a chart at all\n\n- **Ranked categories** (top brands, regions by volume) \u2014 `# bar_chart`, ordered\n by the measure. Query order is the bar order.\n- **A value over time** \u2014 `# line_chart` with the time dimension as `x`.\n- **A wide detail table** \u2014 no chart tag. Charting eight columns is worse than\n showing them; give the tile `# colspan=6` instead and label the columns.\n- **Flat data** \u2014 if every bar is within a few percent of the others, the chart\n is saying \"no pattern here\" at the cost of a card. Consider whether the tile\n earns its place.\n\n## Trends by period: drop the incomplete one\n\nA by-year or by-month trend whose final period is partial draws a cliff that\nreads as collapse. Filter to complete periods, using a cutoff that comes from\nthe DATA (e.g. a snapshot/max-date column carried on a joined dimension), not\nfrom the result set \u2014 deriving it from the visible rows will wrongly declare a\nperiod partial as soon as a filter narrows the data.\n\n## Validate\n\n`malloyyo lint` compiles each dashboard and its tiles, but it does not render\nthem \u2014 a chart that compiles can still throw \"Too many dimensions\" in the\nbrowser. See it with `malloyyo dashboard dev`, which runs the queries\nserver-side and renders the real result.\n",
204
204
  "dashboards/custom-components.md": '---\ndescription: Custom dashboard UI \u2014 a flat dashboards/<name>.jsx|tsx sibling composing @malloyyo/dashboard widgets/hooks/helpers with your own React\n---\n\n# Custom dashboard components (`dashboards/<name>.jsx`)\n\nThe default UI (auto-rendered controls + panel) covers most dashboards. When it\nisn\'t enough, add ONE file \u2014 a **flat sibling** `dashboards/<name>.jsx` (or\n`.tsx`) next to the dashboard\'s `dashboards/<name>.malloy` (same basename) \u2014 that\ncomposes the runtime\'s widgets/hooks with your own React. You own layout, copy,\nand theming; the `.malloy` file still owns every query and filter. See also\n`yo_help dashboards/authoring` and `dashboards/vega-charts`.\n\n```tsx\nimport React from "react";\nimport { Controls, Given, Search, Select, TimeRange, Panel, filters, useGiven } from "@malloyyo/dashboard";\n\nexport default function Dashboard({ dashboard, givens }) {\n return (\n <div style={{ maxWidth: 860, margin: "0 auto", padding: 24 }}>\n <h1>{dashboard.title}</h1>\n <Controls>\n <Given name="STATE" /> {/* picks the control from the declaration */}\n <Search given="NAME" /> {/* committing input + typeahead + validation */}\n <TimeRange given="PERIOD" presets={[\n { value: "", text: "All time" },\n { value: filters.lastN(1, "day"), text: "Last day" },\n { value: filters.lastN(1, "week"), text: "Last week" },\n { value: filters.lastN(1, "month"), text: "Last month" },\n ]} /> {/* "Custom range\u2026" is always appended */}\n <Select given="MIN_SAMPLE"\n options={[10, 200, 1000].map(n => ({ value: filters.greaterThan(n), text: `> ${n}` }))} />\n </Controls>\n <Panel givens={givens} /> {/* the dashboard itself (its tiles/query) */}\n <Panel query="baby_names -> births_by_decade" givens={givens} /> {/* a specific query */}\n </div>\n );\n}\n```\n\nFrom `@malloyyo/dashboard` (also handed to the component as props):\n- **Widgets** (headless-ish; restyle via className/style or the `--dash-*` CSS\n vars \u2014 see Theming below): `<Controls/>` (all givens, or compose children;\n grows Apply/Reset under `autorun=false`), `<Given name/>`,\n `<Select given [options]/>`, `<Search given/>` (committing input + typeahead +\n inline \u2715 clear), `<MultiSelect given [options]/>` (chip multi-select for a\n `filter<string>` \u2014 commits an exact-match list via `filters.oneOf`),\n `<Range given [min max]/>`, `<TimeRange given [presets]/>` (temporal presets +\n custom range), `<Checkbox given/>` (bound to a boolean given),\n `<VegaChart spec query|malloy|data givens/>` (a Vega-Lite chart over query\n rows \u2014 see `yo_help dashboards/vega-charts`)\n- **Hooks**: `useGiven(name)` \u2192 {value, set, spec};\n `useOptions(name, typed?)` \u2192 {options, loading} (typeahead);\n `useQuery({query|malloy, givens})` \u2192 {rows, loading, error} \u2014 plain rows\n for your own visuals;\n `useUrlState(key, initial)` \u2192 [value, setValue] \u2014 shareable view-state (below)\n- **Helpers**: `filters.oneOf/contains/between/atLeast/\u2026` build\n filter-expression strings with correct escaping; temporal:\n `filters.lastN(7, "day")` \u2192 `\'7 days\'`, `filters.dateRange("2026-01-01",\n "2026-07-01")`, `filters.afterDate/beforeDate`; read back with\n `filters.values/numberRange/threshold/inLast/temporalRange`;\n `filters.isValid(type, src)` checks typed input.\n Never hand-concatenate a filter string.\n **Escaping rule for custom controls:** a filter given\'s value is an\n EXPRESSION, so committing a raw column value is wrong the moment it contains\n a comma/percent/dash (\'Tesla, Inc.\' parses as two alternatives and matches\n nothing). Commit `filters.oneOf(value)` (exact) or\n `filters.contains(term)` (substring), and unwrap for display with\n `filters.values(src)`. The stock `<Select/>` does this automatically;\n `<Search/>` deliberately commits raw text (its input IS a filter\n expression).\n- `<Panel/>` runs against the DASHBOARD\'s own file: a bare `<Panel/>` renders\n the whole dashboard (its tiles); `<Panel query="\u2026"/>` runs a query defined in\n the dashboard file (by name) or a `source -> view`; `<Panel malloy="\u2026"/>` and\n `runData(text, givens)` run arbitrary Malloy as a RESTRICTED query (no import /\n given: / connection.* / raw SQL / ##! flags \u2014 the model\'s governed surface\n only). `lint` checks each hard-coded `query="\u2026"` still resolves.\n\n## Shareable view-state: `useUrlState`\n\n`useState` is invisible to the page that owns the URL, so a component built on\nit has an address bar that never changes \u2014 the result can\'t be shared or\nbookmarked. **`useUrlState(key, initial)` is a `useState` twin whose value lives\nin the URL**, under a `~key` param:\n\n```jsx\nimport { useUrlState } from "@malloyyo/dashboard";\n\nconst [rack, setRack] = useUrlState("rack", ""); // string\nconst [reuse, setReuse] = useUrlState("reuse", false); // boolean\nconst [board, setBoard] = useUrlState("board", "........"); // string\nconst [topN, setTopN] = useUrlState("n", 20); // number\n```\n\n- Same shape as `useState`: `[value, setValue]`, and `setValue` takes a value\n **or** an updater fn (`setBoard(b => \u2026)`).\n- The value comes from the URL on load, else `initial`. Every change is written\n back (debounced, `replaceState` \u2014 no history spam), so the address bar is\n always a shareable link.\n- Typed by `initial`: string / number / boolean / any JSON-serializable value.\n Strings stay readable in the URL (`~rack=retinas`); objects and arrays are\n JSON. A value equal to `initial` is dropped from the URL, so defaults never\n clutter it, and a malformed value falls back to `initial` instead of throwing.\n- Works identically in `malloyyo dashboard dev`, on a bundled static site, and\n on a hosted instance \u2014 including inside the sandboxed iframe, which cannot\n reach the top-level URL on its own. That\'s why this is a hook and not\n something a component can do with `history.replaceState`.\n\n**Use it for view-state, not query parameters.** A `given:` is the governed,\nfilter-typed query contract: it\'s declared in the model, drives the default\ncontrols, and is visible over MCP \u2014 bind those with `useGiven` and they already\nround-trip through the URL as `$NAME`. `useUrlState` is for everything else a\ncustom component needs to make shareable: a letter rack whose real query inputs\n(allowed letters, min/max length) are computed from it in JS, a board layout, a\nmode toggle. The two namespaces (`$NAME` vs `~key`) never collide.\n\n## Theming\n\nEvery widget is styled by the runtime\'s **default Malloyyo theme** (system\nfont, neutral grays, blue accent, auto light/dark following the viewer\'s OS) \u2014\na bare component looks styled with zero effort, so DON\'T hand-hardcode\n`fontFamily`/colors. The theme is CSS custom properties; override any subset by\nsetting them on a wrapper element (more specific than the runtime\'s `:root`):\n\n```tsx\n<div style={{ "--dash-accent": "#e11d48", "--dash-controls-bg": "#faf5ff" }}>\n <Controls /> \u2026\n</div>\n```\n\nVars: `--dash-font`, `--dash-bg`, `--dash-fg`, `--dash-muted`, `--dash-border`,\n`--dash-accent`, `--dash-accent-fg`, `--dash-control-bg`, `--dash-controls-bg`,\n`--dash-chip-bg`, `--dash-chip-fg`, `--dash-panel-bg`, `--dash-radius`,\n`--dash-danger`. `DefaultDashboard` also takes a `theme={{ accent, controlsBg }}`\nprop (camelCase keys \u2192 `--dash-*`). The results `<Panel>` keeps a light surface\nin both light/dark (the Malloy renderer has no dark theme) \u2014 override\n`--dash-panel-bg` if your renderer output is dark-safe.\n\n**Use `--dash-*` and nothing else.** A custom component renders in its own\n**iframe**, so CSS variables defined by the surrounding page \u2014 including the\nbundled site\'s `--line` / `--card` / `--muted` \u2014 are NOT in scope inside it. A\ncomponent styled against those still renders, but every rule referencing them\nresolves to nothing: borders, dividers and panel backgrounds vanish silently\nwhile text and layout survive, so the page looks *almost* right and the cause\nisn\'t obvious. If you\'re porting CSS that has to work both inside the frame and\non a bundled page, resolve each colour once through the chain and use the alias:\n\n```css\n.my-card {\n --edge: var(--dash-border, var(--line, #e4e6eb));\n --surface: var(--dash-panel-bg, var(--card, #fff));\n border: 1px solid var(--edge);\n background: var(--surface);\n}\n```\n\nThis is a class of bug `lint` cannot see and a screenshot can \u2014 look at custom\ncomponents in `malloyyo dashboard dev` before shipping them.\n\nFor charts beyond the Malloy renderer\'s `#` tags, use `<VegaChart>` \u2014\n`yo_help dashboards/vega-charts`.\n',
205
+ "dashboards/drafts.md": "---\ndescription: Writing a draft dashboard from a chat client \u2014 one component file, queries inline, saved with save_draft_dashboard; and how one is promoted into the model repo\n---\n\n# Draft dashboards (`save_draft_dashboard`)\n\nA draft is a dashboard stored on this instance rather than in the model repo.\nIt gets a URL, renders like any other dashboard, and can be re-saved as often\nas you like. Read this before writing one.\n\n## The shape\n\nONE React component, default-exported, whose queries are Malloy written inline:\n\n```tsx\nimport { useQuery } from \"@malloyyo/dashboard\";\n\nexport default function Dashboard() {\n const top = useQuery({\n malloy: `run: flights -> { group_by: carrier; aggregate: flight_count; limit: 10 }`,\n });\n const rows = top.rows ?? [];\n return (\n <div style={{ padding: 24 }}>\n <h1 style={{ fontSize: 22, fontWeight: 600 }}>Top carriers</h1>\n {top.loading ? <p>Loading\u2026</p> : <ol>{rows.map((r) => (\n <li key={String(r.carrier)}>{String(r.carrier)}: {Number(r.flight_count).toLocaleString()}</li>\n ))}</ol>}\n </div>\n );\n}\n```\n\nSave it with `save_draft_dashboard({ dataset, name, title, source })`. The\nresult carries a `url` to open and a `dashboard` name that `show_dashboard`\nrenders. Pass the returned `slug` back on the next save to update the same\ndraft instead of making another.\n\n## The queries\n\nInline Malloy runs against what the model PUBLISHES \u2014 the same rules as the\n`query` tool. You may define your own sources, measures and joins derived from\nthe model's sources. You may not `import`, open a connection, write raw SQL, or\ndeclare `given:`. Check a query with `query(execute:false)` before you put it\nin a component; the save also compiles every literal query it finds and reports\nwhat failed.\n\nWrite the whole query as one template literal. A query built by string\nconcatenation can't be checked at save time and only fails when a reader opens\nthe dashboard.\n\n## What you can import\n\nOnly these resolve:\n\n| Import | What you get |\n|---|---|\n| `react` | React itself, hooks included |\n| `@malloyyo/dashboard` | `useQuery`, `useGiven`, `useOptions`, `useUrlState`, `runData`, `filters`, `VegaChart`, `Field`, and the controls: `Controls`, `Given`, `Select`, `Search`, `MultiSelect`, `Range`, `Checkbox`, `TimeRange` |\n\nNothing else \u2014 no chart library, no icon set, no CSS framework, no `fetch`.\nUse inline `style` objects, plain HTML, and `VegaChart` (see\n`yo_help dashboards/vega-charts`) for charts.\n\n`useQuery` returns `{ rows, result, loading, error }`. `rows` is an array of\nplain objects. Numbers can arrive as BigInt or decimal objects, so wrap them\nwith `Number()` before `.toLocaleString()` or arithmetic, and format dates in\nMalloy rather than in JavaScript.\n\n## Presentation\n\n- One clear page title, then the content. No wrapper card around everything.\n- Put a few headline numbers in a row, value large (~40px) with a small label\n beneath; don't stack them vertically.\n- Give each query-backed section its own loading and error state, so a slow one\n doesn't blank the page.\n- Prefer a table under ~8 categories, where exact values and ranking matter;\n use a chart when shape or trend is the point.\n- Keep charts responsive in width and roughly 200\u2013280px tall.\n- Say what the data shows. Don't call a change strong, concerning or surprising.\n\n## When to add a `.malloy` file instead\n\nPass `malloy` as well when the dashboard needs:\n\n- **filters/controls** \u2014 declare givens in the model and the controls render\n themselves (`yo_help dashboards/givens-and-controls`);\n- **named queries** shared across several tiles, or a composite grid\n (`yo_help dashboards/authoring`);\n- **no code at all** \u2014 a tagged Malloy query renders through Malloy's own\n renderer, which is often the better dashboard.\n\nThat file is `dashboards/<name>.malloy`: it imports `\"../index.malloy\"` and\ntags a query `# artifact`.\n\n## Promotion\n\nA draft lives on the instance; the model repo is where dashboards belong. To\nmove one in, from a checkout of the repo:\n\n```bash\nmalloyyo draft list # find the slug\nmalloyyo draft promote <slug> # writes dashboards/<name>.malloy + component\n```\n\nPromotion writes the files and records what the draft became; it never deletes\nthe draft, whose URL people may already hold. A draft whose queries are inline\nneeds them LIFTED into its `.malloy` as named queries \u2014 the component then uses\n`useQuery({ query: \"<name>\" })` \u2014 because a repo dashboard's queries live in\nthe model, not the component. The written `.malloy` carries them as comments to\nwork from. Then `malloyyo lint`, and the usual PR.\n\n## Iterating\n\n1. `list_sources`, then `describe_source` for the source you'll query.\n2. Validate each query with `query(execute:false)`.\n3. Save the draft; fix anything the report names.\n4. Show the user the URL (or `show_dashboard`), and ask what to change.\n5. Re-save with the same `slug`.\n",
205
206
  "dashboards/givens-and-controls.md": "---\ndescription: Dashboard filter controls \u2014 declare filter<T> givens with # label / suggest / control tags; faceted (related) suggestions\n---\n\n# Dashboard givens & controls\n\nA dashboard's filters are `filter<T>` **givens** declared in the model; the\n`#` tags on each declaration drive its control. This is part of authoring a\ndashboard \u2014 see also `yo_help dashboards/authoring`.\n\n**Declare the filters as `filter<T>` givens** \u2014 never raw strings/numbers.\nA `filter<string>` value accepts one value ('NY'), alternatives ('NY, CA'),\nwildcards ('Ann%'), negation ('-NY'); a `filter<number>` accepts ranges\n('[1910 to 1930]') and comparisons ('> 200'); a `filter<timestamp>` /\n`filter<date>` accepts relative windows ('7 days' = the last 7 days, 'today',\n'last month') and literal ranges ('2026-01-01 to 2026-07-01' \u2014 NO `@` in\nfilter literals). Apply with `~`; `f''` = empty = no filter (the natural\n\"All\"/\"all time\" \u2014 just `col ~ $X`, no `$X = '' or \u2026` dance):\n\n```malloy\n##! experimental { givens }\ngiven:\n # label=\"State\" control=select suggest { source=baby_names dimension=state }\n STATE :: filter<string> is f'NY'\n # label=\"Brand\" suggest { query=brand_suggest dimension=product_brand }\n BRAND :: filter<string> is f''\n # label=\"Names\" control=multiselect suggest { query=name_suggest dimension=name }\n NAMES :: filter<string> is f''\n # label=\"Years\" range_min=1910 range_max=2025\n YEAR_RANGE :: filter<number> is f'[1910 to 1930]'\n # label=\"Time period\"\n PERIOD :: filter<timestamp> is f''\n # label=\"Include rare names\"\n INCLUDE_RARE :: boolean is false\n```\n\nTags on the declaration drive the control (tag syntax is `key=\"value\"` \u2014\nequals, not colon):\n- `label` \u2014 control caption (defaults to the given's name)\n- `suggest { \u2026 }` \u2014 where the control's options come from. NO Malloy code in\n strings \u2014 just names:\n - `suggest { query=brand_suggest dimension=product_brand }` \u2014 the FIRST\n COLUMN of a named query (declare the query in the model \u2014 governed and\n reviewable). PREFER THIS FORM. The query must be in scope where the dashboard\n runs (bring it in with the dashboard file's bare `import`).\n - `suggest { source=baby_names dimension=state }` \u2014 the DISTINCT VALUES of\n a dimension on a source (the source must be in the dashboard's scope)\n A `dimension` (in either form) is what enables SERVER-SIDE TYPEAHEAD: the\n runtime refines the base query with what the user has typed\n (`\u2026 + { where: lower(field) ~ f'll%'; limit: 50 }`, case-insensitive,\n escaped). Without a dimension the fetched list is filtered client-side.\n Runs as a restricted query; lint checks the declaration compiles.\n\n **RELATED (faceted) filters** \u2014 query-form only: a suggest query may\n reference the OTHER givens, and the runtime runs it with the dashboard's\n current values (the suggested given itself is excluded, so the list never\n collapses to the current pick). Brand suggestions narrow when Category is\n set:\n\n ```malloy\n query: brand_suggest is inventory_items -> product_brand + {\n where:\n product_category ~ $CATEGORY, // NOT product_brand ~ $BRAND\n product_department ~ $DEPARTMENT\n limit: 500\n }\n ```\n\n Declare one `*_suggest` per filter, each referencing the others; `f''`\n defaults mean unset filters don't constrain. `source=` suggests can't do\n this (no place for a `where:`) \u2014 another reason to prefer `query=`.\n- `control=select` \u2014 a fixed dropdown instead of a typeahead search box\n- `control=multiselect` \u2014 a tokenized multi-select for a `filter<string>`:\n each pick is a removable chip, the committed value is an exact-match list\n (`Emma, Olivia, Sophia`). Ideal for \"pick several\" filters (names, brands).\n Suggestions come from the given's `suggest {\u2026}` (server-side typeahead when\n it names a dimension). Empty (start from `f''`) = no filter (all).\n- `range_min` / `range_max` \u2014 bounds; makes a filter<number> given a\n dual-thumb range slider\n- anything else passes through in `spec.tags` for custom components\n\nControl picked from the declaration automatically: numeric range tags \u2192\ndual-thumb slider; `filter<timestamp|timestamptz|date>` \u2192 the TimeRange\nwidget (relative presets: Today / Last 7 days / Last 30 days / \u2026 plus a\n\"Custom range\u2026\" from/to date picker); `control=multiselect` \u2192 chip\nmulti-select; suggest + control=select \u2192 dropdown; boolean \u2192 checkbox;\nanything else \u2192 committing search box with typeahead (an inline \u2715 clears it;\na \"Press \u21B5 to apply\" hint shows while the typed draft differs from what's\nrunning \u2014 free text can't safely re-run per keystroke).\nThe suggest-driven options are DATA VALUES only \u2014 options that aren't column\nvalues (custom time presets, threshold buckets) need a custom component\n(`yo_help dashboards/custom-components`) with explicit `{value, text}` options\nwhere value is a filter expression built with `filters.*`.\n\n## When the query re-runs: live (default) vs. Apply\n\nBy default a dashboard is **live** \u2014 every control change re-runs the query\nimmediately (the committing search box is the exception: free text commits on\nEnter/blur, since a half-typed filter is invalid). To batch changes behind an\n**Apply** button instead, set `autorun=false` on the `# artifact` tag:\n\n```malloy\n# artifact { name=\"births-by-name\" title=\"Births by name\" autorun=false }\n```\n\n`autorun=false` makes `<Controls>` grow an Apply/Reset pair \u2014 controls edit a\ndraft and nothing re-runs until Apply. Reach for it when the query is expensive\nor several filters are usually changed together; leave it off (live) otherwise.\n",
206
207
  "dashboards/grid-layout.md": "---\ndescription: Dashboard grid layout \u2014 # dashboard {columns=N} with # colspan and # break to place KPI tiles and charts\n---\n\n# Dashboard grid layout (`# dashboard {columns=N}`)\n\nBy default a `# dashboard` result flows its KPI tiles and cards and wraps.\nAdd `{columns=N}` to place them on a fixed **N-column grid** instead \u2014 use\n`columns=6`, which divides evenly into 2- and 3-wide cards.\n\n**Key mechanic:** a tag placed ABOVE `aggregate:` or `nest:` applies to EVERY\nitem declared in that block. So you set card widths once per block, not per\nfield.\n\n```malloy\n# artifact { title=\"Customer Insights\" } dashboard {columns=6}\nview: customer_insights is {\n where: created_at ~ $PERIOD\n # colspan=2\n aggregate: total_sales, user_count, order_count, average_order_value\n # colspan=3\n nest:\n # break\n # bar_chart\n users_by_spend_tier\n sales_by_traffic_source\n # shape_map\n sales_by_state\n # colspan=6\n recent_orders // wide detail table \u2192 full width\n}\n```\n\n## The conventions\n\n- **`# colspan=2` above `aggregate:`** \u2014 each KPI / measure tile spans 2 of 6\n columns \u2192 3 tiles per row.\n- **`# colspan=3` above `nest:`** \u2014 each graph or small table spans 3 \u2192 2 per\n row. Per-item render tags (`# line_chart`, `# bar_chart`, `# shape_map`) still\n go on the individual nested items.\n- **`# colspan=6`** \u2014 a single wide / many-column table gets its own full-width\n line. Tag that one item; a per-item `# colspan` overrides the block default.\n- **`# break` on the FIRST nest item** \u2014 starts the graphs on a fresh row, so\n KPI tiles and charts never share one. The renderer splits fields into a new\n grid at each `# break`. Just always add it: it's a no-op when the tiles\n already fill complete rows, and the fix when they don't (e.g. 4 measures\n leave a lone tile a colspan-3 chart would otherwise pack in beside).\n\n`# colspan` only does anything in columns mode \u2014 without `{columns=N}` the\nlayout is free-flow wrap and colspan is ignored. Clamp colspans to `1..N`.\n\nSee also `yo_help dashboards/vega-charts` for custom charts, and the fuller\nauthoring guide surfaced by the local `malloyyo mcp` server.\n",
207
208
  "dashboards/vega-charts.md": '---\ndescription: Custom dashboard charts with Vega-Lite \u2014 the <VegaChart> component, for charts the # renderer tags can\'t do\n---\n\n# Custom charts with Vega-Lite (`<VegaChart>`)\n\nWhen Malloy\'s renderer tags (`# bar_chart`, `# line_chart`, `# shape_map`, \u2026)\ndon\'t cover the chart you want, a dashboard can draw a **Vega-Lite** spec with\nthe `<VegaChart>` component. The chart engine ships in the dashboard runtime, so\nyou author only a JSON spec + a Malloy query \u2014 no library to load.\n\n**It is a COMPONENT, not a `#` tag.** There is no `# vega_lite` or\n`# scatter_chart` tag. `<VegaChart>` lives in a custom component \u2014 a flat sibling\n`dashboards/<name>.jsx` (or `.tsx`) next to the dashboard\'s\n`dashboards/<name>.malloy` \u2014 a different layer from the `#` renderer tags. (The\ndashboard\'s query is declared in the `.malloy` file; the component only\ncustomizes presentation. Preview with `malloyyo dashboard dev`, validate with\n`malloyyo lint`.)\n\n## The recipe\n\n```tsx\nimport { VegaChart } from "@malloyyo/dashboard";\n\n// Encodings point at the query\'s OUTPUT COLUMN NAMES (here: name, births).\nconst spec = {\n mark: { type: "bar", tooltip: true },\n encoding: {\n y: { field: "name", type: "nominal", sort: "-x" },\n x: { field: "births", type: "quantitative" },\n },\n};\n\nexport default function Dashboard({ givens }) {\n return <VegaChart spec={spec} query="births_by_name" givens={givens} />;\n}\n```\n\nThree ways to feed it data:\n- `<VegaChart spec={spec} query="births_by_name" givens={givens}/>` \u2014 a query\n defined in the dashboard\'s `.malloy` file (by name), or a `source -> view`\n- `<VegaChart spec={spec} malloy="source -> view" givens={givens}/>` \u2014 restricted\n Malloy text (same governance as the explore surface: no import / given: /\n connection.* / raw SQL / ##! flags)\n- `<VegaChart spec={spec} data={rows}/>` \u2014 rows you already have from `useQuery`\n\n## Gotchas (the ones that actually bite)\n\n- **Shape the data in Malloy; return FLAT rows.** Do ranking, share/percent\n (`all(x, dim)`), and label lookups (a `pick` for month names) in the QUERY.\n The spec just encodes columns \u2014 it is not the place to reshape data.\n- **Match column names character-for-character.** Run the query once with\n `query(execute:true)` and read the exact output column names; the spec\'s\n `field` values must match them exactly.\n- **The spec\'s `data` is ignored / any `url` is stripped.** The frame has no\n network \u2014 remote data URLs, transform lookups, and remote `image` marks are\n removed. Adapting a Vega-Lite gallery example = delete its\n `"data": {"url": \u2026}` and repoint the encodings; the query rows are inlined for\n you as the dataset.\n- **Nests come back as arrays.** Flatten to plottable rows in the query, or bind\n a nest to its own chart: `<VegaChart data={row.my_nest}/>`.\n- **Huge integers arrive as strings, on purpose.** Integers serialize as JSON\n numbers, but a value beyond \xB12^53 (a snowflake ID, a 64-bit hash) keeps its\n full precision by staying a string \u2014 JSON has no int64. Bound to a\n `quantitative` or `temporal` channel, Vega-Lite would sort such a column\n lexicographically (`"1","10","11","2"`). If a column can get that big and you\n need to plot it, narrow it in the QUERY \u2014 bucket it, rank it, or emit the\n value you actually want on the axis.\n- **Interactivity = setting given values**, never rewriting query text per\n interaction. Client-side chart interactions (tooltip, zoom, brush) work;\n anything that calls a server does not.\n- **Reads well:** for normalized/share data use a diverging color scale with\n `domainMid` (e.g. `1/12` for month-share), and sort a discrete axis by a\n companion numeric field (`month_name` sorted by `month_num`) rather than\n alphabetically.\n\n## Validate\n\n`malloyyo lint` checks the query, the givens, AND the component (it compiles,\nand each `query="\u2026"` it references resolves) \u2014 your only pre-browser check. Then\n`malloyyo dashboard dev` to see it render.\n',
@@ -250,7 +251,7 @@ var prompts = {
250
251
  "title": "Inspect a published source"
251
252
  },
252
253
  "list_sources": {
253
- "description": "List the sources you can query, grouped by the model that publishes them, with each model's named queries. Drill into a source with describe_source before writing a query.",
254
+ "description": "List the sources you can query, grouped by the model that publishes them, with each model's named queries. Drill into a source with describe_source before writing a query. A model may also report `dashboards` \u2014 pre-built pages for that model, each with a `url` a person can open; offer one when it already covers the question, and query the sources otherwise.",
254
255
  "title": "List sources"
255
256
  }
256
257
  }
@@ -630,31 +631,31 @@ function walkFields(fields, structDefFields, depth, ctx, anon) {
630
631
  const ef = f;
631
632
  const cls = classifyJoinTarget(ef, ctx.knownSources);
632
633
  const inlineMode = ctx.opts.expand === "inline";
633
- const join5 = { name: f.name, relationship: joinRel(ef) };
634
- applyDocs(join5, f.annotations);
635
- if (cls.kind === "ref") join5.source_ref = cls.name;
634
+ const join6 = { name: f.name, relationship: joinRel(ef) };
635
+ applyDocs(join6, f.annotations);
636
+ if (cls.kind === "ref") join6.source_ref = cls.name;
636
637
  else if (cls.kind === "anon" && !inlineMode) {
637
- join5.anon_src_index = allocAnon(ef, cls.refId, depth + 1, ctx, anon);
638
+ join6.anon_src_index = allocAnon(ef, cls.refId, depth + 1, ctx, anon);
638
639
  }
639
- if (needsQuote(f.name)) join5.must_quote = true;
640
- if (annotations.length > 0) join5.annotations = annotations;
641
- if (loc) join5.location = loc;
642
- if (access) join5.access = access;
640
+ if (needsQuote(f.name)) join6.must_quote = true;
641
+ if (annotations.length > 0) join6.annotations = annotations;
642
+ if (loc) join6.location = loc;
643
+ if (access) join6.access = access;
643
644
  const synthetic = isScalarArray(ef) || isRepeatedRecord(ef) || isAnonymousRecord(ef);
644
- if (isScalarArray(ef)) join5.column_shape = "scalar_array";
645
- else if (isRepeatedRecord(ef)) join5.column_shape = "record_array";
646
- else if (isAnonymousRecord(ef)) join5.column_shape = "record";
645
+ if (isScalarArray(ef)) join6.column_shape = "scalar_array";
646
+ else if (isRepeatedRecord(ef)) join6.column_shape = "record_array";
647
+ else if (isAnonymousRecord(ef)) join6.column_shape = "record";
647
648
  if (!synthetic && mLoc) {
648
649
  const body = sliceSource(ctx.readSource(mLoc.url), mLoc);
649
- if (body) join5.body = body;
650
+ if (body) join6.body = body;
650
651
  }
651
652
  const shouldInline = inlineMode || cls.kind === "own";
652
653
  if (shouldInline && depth < MAX_JOIN_DEPTH) {
653
654
  const childStructFields = ef.structDef.fields ?? [];
654
655
  const sub = walkFields(ef.allFields, childStructFields, depth + 1, ctx, anon);
655
- join5.fields = stripScalarArrayValue(ef, sub);
656
+ join6.fields = stripScalarArrayValue(ef, sub);
656
657
  }
657
- groups.joins.push(join5);
658
+ groups.joins.push(join6);
658
659
  continue;
659
660
  }
660
661
  if (f.isQueryField()) {
@@ -1812,6 +1813,17 @@ function listSourcesTool(host) {
1812
1813
  }
1813
1814
  m.sources = sources;
1814
1815
  }
1816
+ if (e.dashboards?.length) {
1817
+ const dashboards = /* @__PURE__ */ Object.create(null);
1818
+ for (const d of e.dashboards) {
1819
+ const o = {};
1820
+ if (d.title) o.title = d.title;
1821
+ if (d.description) o.description = d.description;
1822
+ if (d.url) o.url = d.url;
1823
+ dashboards[d.name] = o;
1824
+ }
1825
+ m.dashboards = dashboards;
1826
+ }
1815
1827
  models[e.model_ref] = m;
1816
1828
  }
1817
1829
  return { ok: true, guidance: prompts.explore.guidance, models };
@@ -2890,7 +2902,7 @@ function clearCreds(url6) {
2890
2902
  }
2891
2903
 
2892
2904
  // package.json
2893
- var version = "0.2.46";
2905
+ var version = "0.2.48";
2894
2906
 
2895
2907
  // src/http.ts
2896
2908
  var USER_AGENT = `malloyyo/${version}`;
@@ -3132,8 +3144,16 @@ async function getAccessToken(target, opts, env = process.env) {
3132
3144
  Run: malloyyo login ${target.name}`);
3133
3145
  }
3134
3146
  if (creds.expiresAt - Date.now() < 6e4) {
3147
+ const { clientId, refreshToken } = creds;
3148
+ if (!refreshToken || !clientId) {
3149
+ throw new Error(
3150
+ `The token stored for ${target.url} has expired.
3151
+ Get a new one (the instance's issue_cli_token tool, or ${target.url}/settings/tokens)
3152
+ and store it with: malloyyo login ${target.url} --token-stdin`
3153
+ );
3154
+ }
3135
3155
  try {
3136
- creds = await refresh(target.url, creds);
3156
+ creds = await refresh(target.url, { ...creds, clientId, refreshToken });
3137
3157
  } catch {
3138
3158
  throw new Error(`Session expired for ${target.url}.
3139
3159
  Run: malloyyo login ${target.name}`);
@@ -3146,8 +3166,8 @@ Run: malloyyo login ${target.name}`);
3146
3166
  import fs4 from "node:fs";
3147
3167
  import path5 from "node:path";
3148
3168
  import url4 from "node:url";
3149
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3150
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3169
+ import { McpServer } from "@modelcontextprotocol/server";
3170
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
3151
3171
  import {
3152
3172
  MalloyConfig as MalloyConfig2,
3153
3173
  Runtime as Runtime2,
@@ -3156,9 +3176,8 @@ import {
3156
3176
 
3157
3177
  // ../mcp-engine/dist/mcp-sdk.js
3158
3178
  import {
3159
- CallToolRequestSchema,
3160
- ListToolsRequestSchema
3161
- } from "@modelcontextprotocol/sdk/types.js";
3179
+ fromJsonSchema
3180
+ } from "@modelcontextprotocol/server";
3162
3181
  var HOST_ONLY2 = "host_only";
3163
3182
  function toContent(result) {
3164
3183
  const { malloy_text, [HOST_ONLY2]: _hostOnly, ...rest } = result;
@@ -3170,37 +3189,28 @@ function toContent(result) {
3170
3189
  }
3171
3190
  return { content, structuredContent: { ...rest } };
3172
3191
  }
3173
- function lowLevel(server) {
3174
- return "server" in server ? server.server : server;
3192
+ var PASS_THROUGH = {
3193
+ getValidator: () => (input) => ({ valid: true, data: input, errorMessage: void 0 })
3194
+ };
3195
+ function publishedSchema(schema) {
3196
+ return fromJsonSchema(schema, PASS_THROUGH);
3175
3197
  }
3176
3198
  function attachSurface(server, surface, opts = {}) {
3177
- const s = lowLevel(server);
3178
- const byName = new Map(surface.tools.map((t) => [t.name, t]));
3179
- s.setRequestHandler(ListToolsRequestSchema, async () => ({
3180
- tools: surface.tools.map((t) => ({
3181
- name: t.name,
3182
- title: t.title,
3183
- description: t.description,
3184
- inputSchema: t.inputSchema
3185
- }))
3186
- }));
3187
- s.setRequestHandler(CallToolRequestSchema, async (req) => {
3188
- const tool = byName.get(req.params.name);
3189
- if (!tool) {
3190
- return {
3191
- content: [{ type: "text", text: `unknown tool: ${req.params.name}` }],
3192
- isError: true
3193
- };
3194
- }
3195
- const result = await tool.handler(
3196
- req.params.arguments ?? {}
3199
+ for (const tool of surface.tools) {
3200
+ server.registerTool(
3201
+ tool.name,
3202
+ {
3203
+ title: tool.title,
3204
+ description: tool.description,
3205
+ inputSchema: publishedSchema(tool.inputSchema)
3206
+ },
3207
+ // Compile/run failures are data (problems[]), never protocol errors.
3208
+ async (args) => toContent(await tool.handler(args ?? {}))
3197
3209
  );
3198
- return toContent(result);
3199
- });
3200
- if (opts.registerSkillsAsPrompts && "registerPrompt" in server) {
3201
- const mcp = server;
3210
+ }
3211
+ if (opts.registerSkillsAsPrompts) {
3202
3212
  for (const skill of surface.skills) {
3203
- mcp.registerPrompt(
3213
+ server.registerPrompt(
3204
3214
  skill.name,
3205
3215
  { title: skill.name, description: skill.description },
3206
3216
  () => ({
@@ -3209,7 +3219,7 @@ function attachSurface(server, surface, opts = {}) {
3209
3219
  ]
3210
3220
  })
3211
3221
  );
3212
- mcp.registerResource(
3222
+ server.registerResource(
3213
3223
  skill.name,
3214
3224
  `malloy-skill://${skill.name}`,
3215
3225
  { title: skill.name, description: skill.description, mimeType: "text/markdown" },
@@ -3334,8 +3344,7 @@ async function serveMcp(opts) {
3334
3344
  const server = new McpServer(
3335
3345
  { name: serverName, version: opts.version },
3336
3346
  {
3337
- instructions: renderInstructions(surface.instructions, instanceName) + MODE_STUB[mode],
3338
- capabilities: { tools: {}, prompts: {}, resources: {} }
3347
+ instructions: renderInstructions(surface.instructions, instanceName) + MODE_STUB[mode]
3339
3348
  }
3340
3349
  );
3341
3350
  attachSurface(server, surface, { registerSkillsAsPrompts: true });
@@ -3809,7 +3818,7 @@ function serveStatic(dir, port) {
3809
3818
  res.writeHead(200, { "Content-Type": type, "Content-Length": st.size, "Accept-Ranges": "bytes" });
3810
3819
  fs6.createReadStream(file).pipe(res);
3811
3820
  });
3812
- return new Promise((resolve4, reject) => {
3821
+ return new Promise((resolve5, reject) => {
3813
3822
  let attempt = 0;
3814
3823
  const tryPort = (p) => {
3815
3824
  server.once("error", (err) => {
@@ -3825,7 +3834,7 @@ function serveStatic(dir, port) {
3825
3834
  (port ${port} busy \u2014 using ${p})`);
3826
3835
  console.log(`
3827
3836
  serving ${path7.basename(dir)}/ on http://localhost:${p} (ctrl-c to stop)`);
3828
- resolve4();
3837
+ resolve5();
3829
3838
  });
3830
3839
  };
3831
3840
  tryPort(port);
@@ -4501,22 +4510,151 @@ async function launchCmd(mode, opts) {
4501
4510
  stdio: "inherit",
4502
4511
  cwd: root
4503
4512
  });
4504
- await new Promise((resolve4) => {
4513
+ await new Promise((resolve5) => {
4505
4514
  child.on("error", (e) => {
4506
4515
  process.stderr.write(
4507
4516
  `\u2717 could not launch \`claude\`: ${e.message}
4508
4517
  (is Claude Code installed and on PATH?)
4509
4518
  `
4510
4519
  );
4511
- resolve4();
4520
+ resolve5();
4512
4521
  });
4513
- child.on("exit", () => resolve4());
4522
+ child.on("exit", () => resolve5());
4514
4523
  });
4515
4524
  fs10.rmSync(tmpDir, { recursive: true, force: true });
4516
4525
  }
4517
4526
 
4527
+ // src/draft.ts
4528
+ import { createHash } from "node:crypto";
4529
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
4530
+ import { join as join5, resolve as resolve2 } from "node:path";
4531
+ async function readStdin2() {
4532
+ if (process.stdin.isTTY) {
4533
+ throw new Error(`--token-stdin reads the token from stdin \u2014 pipe it in: printf '%s' "$TOKEN" | malloyyo login <url> --token-stdin`);
4534
+ }
4535
+ const chunks = [];
4536
+ for await (const c of process.stdin) chunks.push(c);
4537
+ return Buffer.concat(chunks).toString("utf8").trim();
4538
+ }
4539
+ async function loginWithToken(url6) {
4540
+ const token = await readStdin2();
4541
+ if (!token) throw new Error("no token on stdin");
4542
+ const res = await apiFetch(`${url6}/api/cli/whoami`, { headers: { authorization: `Bearer ${token}` } });
4543
+ const me = await res.json().catch(() => ({ ok: false }));
4544
+ if (!res.ok || !me.ok) {
4545
+ throw new Error(
4546
+ `${url6} did not accept that token: ${me.error ?? `${res.status} ${res.statusText}`}
4547
+ Is it from this instance? Tokens are per instance URL.`
4548
+ );
4549
+ }
4550
+ const expiresAt = me.expiresAt ? Date.parse(me.expiresAt) : Date.now() + 365 * 864e5;
4551
+ saveCreds(url6, { accessToken: token, expiresAt });
4552
+ const until = me.expiresAt ? `, expires ${new Date(expiresAt).toLocaleString()}` : "";
4553
+ console.log(`\u2713 logged in to ${url6} as ${me.email} (${(me.scopes ?? []).join(", ")}${until})`);
4554
+ }
4555
+ var DraftRequestError = class extends Error {
4556
+ constructor(message2, status2) {
4557
+ super(message2);
4558
+ this.status = status2;
4559
+ }
4560
+ };
4561
+ async function draftFetch(t, path12, bearer, init) {
4562
+ const res = await apiFetch(`${t.url}/api/datasets/${encodeURIComponent(t.dataset)}${path12}`, {
4563
+ ...init,
4564
+ headers: { ...init?.headers ?? {}, authorization: `Bearer ${bearer}` }
4565
+ });
4566
+ const out = await res.json().catch(() => ({ ok: false, error: `${res.status} ${res.statusText}` }));
4567
+ if (!out.ok) {
4568
+ const auth = res.status === 401 ? `
4569
+ Get a token for ${t.url} (its issue_cli_token tool) and run: malloyyo login ${t.url} --token-stdin` : "";
4570
+ throw new DraftRequestError(`${out.error ?? res.status}${auth}`, res.status);
4571
+ }
4572
+ return out;
4573
+ }
4574
+ async function draftList(dir, opts) {
4575
+ const t = resolvePublishTarget(resolve2(dir), void 0, { instance: opts.instance, dataset: opts.dataset });
4576
+ const bearer = await getAccessToken(t, { tokenFlag: opts.token });
4577
+ const { drafts } = await draftFetch(t, "/drafts", bearer);
4578
+ if (drafts.length === 0) {
4579
+ console.log(`no drafts on ${t.dataset} at ${t.url}`);
4580
+ return;
4581
+ }
4582
+ for (const d of drafts) {
4583
+ const files = [d.hasMalloy ? ".malloy" : null, d.hasComponent ? "component" : null].filter(Boolean).join(" + ");
4584
+ const promoted = d.promotedAs ? ` \u2192 promoted as ${d.promotedAs}` : "";
4585
+ console.log(`${d.slug} ${d.title} (${files}, ${d.updatedAt.slice(0, 10)})${promoted}`);
4586
+ }
4587
+ }
4588
+ function malloyScaffold(name, title, inline) {
4589
+ const candidates = inline.length ? inline.map((q) => q.split("\n").map((line) => `// ${line}`).join("\n")).join("\n//\n") : "// (none found \u2014 the component builds its queries at runtime)";
4590
+ return `import "../index.malloy"
4591
+
4592
+ // TODO promote: name each query below, then point the component at it with
4593
+ // useQuery({ query: "<name>" }). A repo dashboard's queries live here, not in
4594
+ // its component. See yo_help "dashboards/authoring".
4595
+ //
4596
+ // From ${name}'s component:
4597
+ ${candidates}
4598
+
4599
+ # artifact { title="${title.replace(/"/g, '\\"')}" }
4600
+ // query: ${name} is <source> -> { ... }
4601
+ `;
4602
+ }
4603
+ async function draftPromote(slug, dir, opts) {
4604
+ const root = resolve2(dir);
4605
+ const t = resolvePublishTarget(root, void 0, { instance: opts.instance, dataset: opts.dataset });
4606
+ const bearer = await getAccessToken(t, { tokenFlag: opts.token });
4607
+ const { draft: draft2 } = await draftFetch(t, `/drafts/${encodeURIComponent(slug)}`, bearer);
4608
+ const name = opts.name ?? draft2.name;
4609
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(name)) {
4610
+ throw new Error(`--name must be letters, digits, '-' or '_' (a dashboard's file basename), not "${name}"`);
4611
+ }
4612
+ const dashboards = join5(root, "dashboards");
4613
+ mkdirSync2(dashboards, { recursive: true });
4614
+ const written = [];
4615
+ const malloyPath = join5(dashboards, `${name}.malloy`);
4616
+ const componentPath = join5(dashboards, `${name}.${opts.tsx ? "tsx" : "jsx"}`);
4617
+ const existing = [malloyPath, componentPath].filter((p) => existsSync5(p));
4618
+ if (existing.length > 0 && !opts.force) {
4619
+ throw new Error(
4620
+ `${existing.map((p) => p.replace(`${root}/`, "")).join(", ")} already exist(s) \u2014 pass --name to promote under another name, or --force to overwrite`
4621
+ );
4622
+ }
4623
+ const malloy = draft2.malloy.trim() ? draft2.malloy : malloyScaffold(name, draft2.title, draft2.inline);
4624
+ written.push({ path: malloyPath, content: malloy });
4625
+ if (draft2.source.trim()) written.push({ path: componentPath, content: draft2.source });
4626
+ const hash = createHash("sha256");
4627
+ for (const f of written) hash.update(f.content).update("\0");
4628
+ let unrecorded = "";
4629
+ try {
4630
+ await draftFetch(t, `/drafts/${encodeURIComponent(slug)}`, bearer, {
4631
+ method: "POST",
4632
+ headers: { "content-type": "application/json" },
4633
+ body: JSON.stringify({ name, hash: hash.digest("hex").slice(0, 16) })
4634
+ });
4635
+ } catch (e) {
4636
+ if (e instanceof DraftRequestError && e.status === 403) unrecorded = e.message;
4637
+ else throw e;
4638
+ }
4639
+ for (const f of written) writeFileSync2(f.path, f.content.endsWith("\n") ? f.content : `${f.content}
4640
+ `);
4641
+ console.log(`\u2713 promoted '${draft2.title}' into ${root.replace(process.env.HOME ?? "", "~")}`);
4642
+ for (const f of written) console.log(` ${f.path.replace(`${root}/`, "")}`);
4643
+ console.log(` the draft stays live at ${t.url}/datasets/${t.dataset}/dashboard/${draft2.dashboard}`);
4644
+ if (unrecorded) console.log(` (not recorded on the draft: ${unrecorded})`);
4645
+ if (!draft2.malloy.trim()) {
4646
+ console.log(
4647
+ `
4648
+ Next: lift ${draft2.inline.length || "the"} inline quer${draft2.inline.length === 1 ? "y" : "ies"} out of dashboards/${name}.${opts.tsx ? "tsx" : "jsx"} into dashboards/${name}.malloy as named queries, point the component at them with useQuery({ query: "<name>" }), then run: malloyyo lint`
4649
+ );
4650
+ } else {
4651
+ console.log(`
4652
+ Next: malloyyo lint`);
4653
+ }
4654
+ }
4655
+
4518
4656
  // src/cloud/index.ts
4519
- import { resolve as resolve2 } from "node:path";
4657
+ import { resolve as resolve3 } from "node:path";
4520
4658
 
4521
4659
  // src/cloud/infer.ts
4522
4660
  var HOSTED_DOMAIN_SUFFIX = ".malloyyo.com";
@@ -4586,7 +4724,7 @@ function parseBody(text) {
4586
4724
  function createControlPlaneClient(options) {
4587
4725
  const doFetch = options.fetch ?? apiFetch;
4588
4726
  const base = options.apiUrl.replace(/\/+$/, "");
4589
- const sleep = options.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms)));
4727
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
4590
4728
  const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
4591
4729
  async function attempt(method, path12, extra) {
4592
4730
  const token = await options.getAccessToken();
@@ -4762,7 +4900,7 @@ function formatDuration(ms) {
4762
4900
  return minutes === 0 ? `${seconds}s` : `${minutes}m ${seconds % 60}s`;
4763
4901
  }
4764
4902
  async function waitForOperation(ctx, operation) {
4765
- const sleep = ctx.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms)));
4903
+ const sleep = ctx.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
4766
4904
  const now = ctx.now ?? Date.now;
4767
4905
  const interval = ctx.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4768
4906
  const maxWait = ctx.maxOperationWaitMs ?? DEFAULT_MAX_OPERATION_WAIT_MS;
@@ -4953,7 +5091,7 @@ async function secretsSetCommand(ctx, args) {
4953
5091
  const values = await resolveSecretValues(ctx, args);
4954
5092
  const names = Object.keys(values);
4955
5093
  const idempotencyKey = (ctx.newIdempotencyKey ?? randomUUID)();
4956
- const sleep = ctx.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms)));
5094
+ const sleep = ctx.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
4957
5095
  const now = ctx.now ?? Date.now;
4958
5096
  const deadline = now() + (ctx.maxBusyWaitMs ?? DEFAULT_MAX_BUSY_WAIT_MS);
4959
5097
  let result;
@@ -5001,7 +5139,7 @@ async function secretsUnsetCommand(ctx, args) {
5001
5139
  names.map((name) => ({ name }))
5002
5140
  );
5003
5141
  const idempotencyKey = (ctx.newIdempotencyKey ?? randomUUID)();
5004
- const sleep = ctx.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms)));
5142
+ const sleep = ctx.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
5005
5143
  const now = ctx.now ?? Date.now;
5006
5144
  const deadline = now() + (ctx.maxBusyWaitMs ?? DEFAULT_MAX_BUSY_WAIT_MS);
5007
5145
  let result;
@@ -5263,7 +5401,7 @@ async function runCloud(invocation, deps) {
5263
5401
  }
5264
5402
 
5265
5403
  // src/cloud/index.ts
5266
- async function readStdin2() {
5404
+ async function readStdin3() {
5267
5405
  process.stdin.setEncoding("utf8");
5268
5406
  let text = "";
5269
5407
  for await (const chunk of process.stdin) text += chunk;
@@ -5283,7 +5421,7 @@ async function promptSecret(name) {
5283
5421
  function resolveOrInferInstance(given) {
5284
5422
  if (given !== void 0) return given;
5285
5423
  try {
5286
- const inferred = inferInstance(resolve2("."));
5424
+ const inferred = inferInstance(resolve3("."));
5287
5425
  process.stderr.write(
5288
5426
  `using instance ${inferred.slug} (from malloy-config.json target "${inferred.targetName}")
5289
5427
  `
@@ -5307,7 +5445,7 @@ async function dispatch(invocation, json) {
5307
5445
  err: (line) => process.stderr.write(`${line}
5308
5446
  `),
5309
5447
  json,
5310
- readStdin: readStdin2,
5448
+ readStdin: readStdin3,
5311
5449
  // Only when there is a terminal to prompt on. Its absence is what lets a bare `NAME`
5312
5450
  // under a pipe fail with "use --stdin" instead of hanging forever on input that is never
5313
5451
  // coming.
@@ -5461,7 +5599,7 @@ var PUBLISH_HELP = `Target resolution:
5461
5599
  \`malloyyo login <url>\`, or set $MALLOYYO_TOKEN (mint one at
5462
5600
  <url>/settings/tokens \u2014 that is what CI wants), or pass --token.`;
5463
5601
  async function publish(target, dir, opts) {
5464
- const root = resolve3(dir);
5602
+ const root = resolve4(dir);
5465
5603
  const t = resolvePublishTarget(root, target, {
5466
5604
  instance: opts.instance,
5467
5605
  dataset: opts.dataset
@@ -5512,7 +5650,7 @@ async function publish(target, dir, opts) {
5512
5650
  );
5513
5651
  }
5514
5652
  async function status(target, opts) {
5515
- const t = resolveTarget(resolve3("."), target);
5653
+ const t = resolveTarget(resolve4("."), target);
5516
5654
  const source = tokenSource(t, { tokenFlag: opts.token });
5517
5655
  const bearer = await getAccessToken(t, { tokenFlag: opts.token });
5518
5656
  const res = await apiFetch(`${t.url}/api/datasets/${t.dataset}/model/status`, {
@@ -5529,17 +5667,21 @@ async function status(target, opts) {
5529
5667
  console.log(` ${s.compileError ? `\u2717 ${s.compileError}` : `\u2713 compiled ${s.compiledAt ?? ""}`}`);
5530
5668
  }
5531
5669
  async function loginCmd(target, opts) {
5532
- const inst = resolveInstance(resolve3("."), target);
5670
+ const inst = resolveInstance(resolve4("."), target);
5671
+ if (opts.tokenStdin) return loginWithToken(inst.url);
5533
5672
  await login(inst.url, { noBrowser: opts.browser === false });
5534
5673
  console.log(`\u2713 logged in to ${inst.name} (${inst.url})`);
5535
5674
  }
5536
5675
  async function logoutCmd(target) {
5537
- const inst = resolveInstance(resolve3("."), target);
5676
+ const inst = resolveInstance(resolve4("."), target);
5538
5677
  console.log(clearCreds(inst.url) ? `\u2713 logged out of ${inst.url}` : `not logged in to ${inst.url}`);
5539
5678
  }
5540
5679
  var program = new Command();
5541
5680
  program.name("malloyyo").description("Publish Malloy models to a Malloyyo instance").version(version);
5542
- program.command("login").argument("[target]", "target name or instance URL (optional if the config has one target)").option("--no-browser", "print the sign-in URL instead of launching a browser").description("sign in to an instance in your browser (stores a token)").action(loginCmd);
5681
+ program.command("login").argument("[target]", "target name or instance URL (optional if the config has one target)").option("--no-browser", "print the sign-in URL instead of launching a browser").option("--token-stdin", "store a token read from stdin (checked against the instance first)").description("sign in to an instance in your browser (stores a token)").action(loginCmd);
5682
+ var draft = program.command("draft").description("draft dashboards made on an instance, before they live in the model repo");
5683
+ draft.command("list").argument("[dir]", "model directory", ".").option("-i, --instance <instance>", "instance URL, or a configured target name").option("--dataset <dataset>", "dataset whose drafts to list; overrides the config").option("--token <token>", "bearer token (overrides login/env)").description("list your drafts on an instance").action(draftList);
5684
+ draft.command("promote").argument("<slug>", "draft slug, as `malloyyo draft list` prints it").argument("[dir]", "model directory to write into", ".").option("-i, --instance <instance>", "instance URL, or a configured target name").option("--dataset <dataset>", "dataset the draft belongs to; overrides the config").option("--token <token>", "bearer token (overrides login/env)").option("--name <name>", "dashboard name to write as (default: the draft's own)").option("--tsx", "write the component as .tsx instead of .jsx").option("--force", "overwrite existing dashboard files of that name").description("write a draft into this repo as dashboards/<name>.malloy + component").action(draftPromote);
5543
5685
  program.command("logout").argument("[target]", "target name or instance URL (optional if the config has one target)").description("forget the stored token for an instance").action(logoutCmd);
5544
5686
  program.command("publish").argument(
5545
5687
  "[target]",
@@ -5551,7 +5693,7 @@ program.command("publish").argument(
5551
5693
  ${PUBLISH_HELP}
5552
5694
  `).action(publish);
5553
5695
  program.command("lint").argument("[dir]", "directory to lint", ".").description("validate ./dashboards against the model (manifest, query, givens, Dashboard.tsx)").action(async (dir) => {
5554
- const root = resolve3(dir);
5696
+ const root = resolve4(dir);
5555
5697
  const report = await lintDashboards(root);
5556
5698
  if (report.dashboards.length === 0) {
5557
5699
  console.log("no dashboards to lint");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/malloyyo",
3
- "version": "0.2.46",
3
+ "version": "0.2.48",
4
4
  "description": "Publish Malloy models to a Malloyyo instance",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -39,7 +39,7 @@
39
39
  "@malloydata/malloy-connections": "^0.0.431",
40
40
  "@malloydata/malloy-filter": "^0.0.431",
41
41
  "@malloydata/render": "^0.0.431",
42
- "@modelcontextprotocol/sdk": "^1.29.0",
42
+ "@modelcontextprotocol/server": "^2.0.0",
43
43
  "commander": "^12.1.0",
44
44
  "esbuild": "^0.24.0",
45
45
  "react": "19.2.4",