@malloydata/malloyyo 0.2.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.
Files changed (3) hide show
  1. package/README.md +83 -0
  2. package/dist/index.js +1895 -0
  3. package/package.json +47 -0
package/dist/index.js ADDED
@@ -0,0 +1,1895 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+ import { resolve } from "node:path";
6
+
7
+ // src/config.ts
8
+ import { readFileSync, existsSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ function readTargetMap(dir) {
11
+ const malloyConfig = join(dir, "malloy-config.json");
12
+ if (existsSync(malloyConfig)) {
13
+ const json = JSON.parse(readFileSync(malloyConfig, "utf8"));
14
+ if (json.malloyyo && typeof json.malloyyo === "object") return json.malloyyo;
15
+ }
16
+ const standalone = join(dir, "malloyyo.json");
17
+ if (existsSync(standalone)) {
18
+ return JSON.parse(readFileSync(standalone, "utf8"));
19
+ }
20
+ throw new Error(
21
+ `No \`malloyyo\` config found in ${dir} (looked for a "malloyyo" block in malloy-config.json, then malloyyo.json).`
22
+ );
23
+ }
24
+ var normalizeUrl = (u) => u.replace(/\/+$/, "");
25
+ function resolveTarget(dir, name) {
26
+ const targets = readTargetMap(dir);
27
+ const cfg = targets[name];
28
+ if (!cfg) {
29
+ const available = Object.keys(targets).join(", ") || "(none defined)";
30
+ throw new Error(`Unknown target "${name}". Available: ${available}`);
31
+ }
32
+ return {
33
+ name,
34
+ url: normalizeUrl(cfg.url),
35
+ dataset: cfg.dataset,
36
+ tokenEnv: cfg.malloyyo_token?.env
37
+ };
38
+ }
39
+ function resolveInstance(dir, arg) {
40
+ if (arg && /^https?:\/\//i.test(arg)) {
41
+ const url3 = normalizeUrl(arg);
42
+ return { name: url3, url: url3 };
43
+ }
44
+ const targets = readTargetMap(dir);
45
+ const entries = Object.entries(targets);
46
+ if (arg) {
47
+ const cfg = targets[arg];
48
+ if (!cfg) {
49
+ const available = entries.map(([n]) => n).join(", ") || "(none defined)";
50
+ throw new Error(`Unknown target "${arg}". Pass a target name, a URL, or one of: ${available}`);
51
+ }
52
+ return { name: arg, url: normalizeUrl(cfg.url) };
53
+ }
54
+ if (entries.length === 0) throw new Error("No targets defined. Pass a target name or a URL.");
55
+ if (entries.length === 1) return { name: entries[0][0], url: normalizeUrl(entries[0][1].url) };
56
+ const urls = new Set(entries.map(([, c]) => normalizeUrl(c.url)));
57
+ if (urls.size === 1) return { name: entries.map(([n]) => n).join("/"), url: [...urls][0] };
58
+ throw new Error(`Multiple targets \u2014 specify which: ${entries.map(([n]) => n).join(", ")} (or a URL).`);
59
+ }
60
+
61
+ // src/gather.ts
62
+ import { readFileSync as readFileSync2, existsSync as existsSync2, readdirSync, statSync } from "node:fs";
63
+ import { join as join2, relative, sep } from "node:path";
64
+ import { execFileSync } from "node:child_process";
65
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
66
+ function gatherDirectory(dir) {
67
+ const files = [];
68
+ const walk = (cur) => {
69
+ for (const entry of readdirSync(cur)) {
70
+ if (entry.startsWith(".") || SKIP_DIRS.has(entry)) continue;
71
+ const full = join2(cur, entry);
72
+ if (statSync(full).isDirectory()) {
73
+ walk(full);
74
+ } else if (entry.endsWith(".malloy")) {
75
+ files.push({
76
+ path: relative(dir, full).split(sep).join("/"),
77
+ content: readFileSync2(full, "utf8")
78
+ });
79
+ }
80
+ }
81
+ };
82
+ walk(dir);
83
+ const configPath = join2(dir, "malloy-config.json");
84
+ const config = existsSync2(configPath) ? readFileSync2(configPath, "utf8") : void 0;
85
+ return { files, config };
86
+ }
87
+ function gitInfo(dir) {
88
+ const git = (args) => execFileSync("git", args, {
89
+ cwd: dir,
90
+ encoding: "utf8",
91
+ stdio: ["ignore", "pipe", "ignore"]
92
+ // suppress git's own stderr (e.g. "no remote 'origin'")
93
+ }).trim();
94
+ try {
95
+ let repo;
96
+ try {
97
+ repo = git(["remote", "get-url", "origin"]).replace(
98
+ /^.*[:/]([^/]+\/[^/]+?)(?:\.git)?$/,
99
+ "$1"
100
+ );
101
+ } catch {
102
+ }
103
+ return {
104
+ repo,
105
+ branch: git(["rev-parse", "--abbrev-ref", "HEAD"]),
106
+ sha: git(["rev-parse", "HEAD"]),
107
+ dirty: git(["status", "--porcelain"]).length > 0
108
+ };
109
+ } catch {
110
+ return {};
111
+ }
112
+ }
113
+
114
+ // src/oauth.ts
115
+ import http from "node:http";
116
+ import crypto from "node:crypto";
117
+ import { spawn } from "node:child_process";
118
+
119
+ // src/store.ts
120
+ import { homedir } from "node:os";
121
+ import { dirname, join as join3 } from "node:path";
122
+ import { mkdirSync, readFileSync as readFileSync3, writeFileSync, existsSync as existsSync3, chmodSync } from "node:fs";
123
+ function credsPath() {
124
+ const base = process.env.XDG_CONFIG_HOME || join3(homedir(), ".config");
125
+ return join3(base, "malloyyo", "credentials.json");
126
+ }
127
+ function readAll() {
128
+ const p = credsPath();
129
+ if (!existsSync3(p)) return {};
130
+ try {
131
+ return JSON.parse(readFileSync3(p, "utf8"));
132
+ } catch {
133
+ return {};
134
+ }
135
+ }
136
+ function loadCreds(url3) {
137
+ return readAll()[url3];
138
+ }
139
+ function saveCreds(url3, creds) {
140
+ const p = credsPath();
141
+ mkdirSync(dirname(p), { recursive: true });
142
+ const all = readAll();
143
+ all[url3] = creds;
144
+ writeFileSync(p, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
145
+ try {
146
+ chmodSync(p, 384);
147
+ } catch {
148
+ }
149
+ }
150
+ function clearCreds(url3) {
151
+ const all = readAll();
152
+ if (!(url3 in all)) return false;
153
+ delete all[url3];
154
+ writeFileSync(credsPath(), JSON.stringify(all, null, 2) + "\n", { mode: 384 });
155
+ return true;
156
+ }
157
+
158
+ // src/oauth.ts
159
+ var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
160
+ async function discover(baseUrl) {
161
+ const res = await fetch(`${baseUrl}/api/oauth/discovery/authorization-server`);
162
+ if (!res.ok) throw new Error(`OAuth discovery failed at ${baseUrl}: ${res.status} ${res.statusText}`);
163
+ return await res.json();
164
+ }
165
+ function pkce() {
166
+ const verifier = crypto.randomBytes(32).toString("base64url");
167
+ const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
168
+ return { verifier, challenge };
169
+ }
170
+ async function registerClient(registrationEndpoint, redirectUri) {
171
+ const res = await fetch(registrationEndpoint, {
172
+ method: "POST",
173
+ headers: { "content-type": "application/json" },
174
+ body: JSON.stringify({
175
+ client_name: "malloyyo CLI",
176
+ redirect_uris: [redirectUri],
177
+ token_endpoint_auth_method: "none",
178
+ grant_types: ["authorization_code", "refresh_token"],
179
+ response_types: ["code"],
180
+ scope: "mcp"
181
+ })
182
+ });
183
+ if (!res.ok) throw new Error(`client registration failed: ${res.status} ${await res.text()}`);
184
+ return (await res.json()).client_id;
185
+ }
186
+ function openBrowser(url3) {
187
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url3]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url3]] : ["xdg-open", [url3]];
188
+ try {
189
+ spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
190
+ } catch {
191
+ }
192
+ }
193
+ function awaitRedirect(state) {
194
+ return new Promise((resolveServer) => {
195
+ let resolveCode;
196
+ let rejectCode;
197
+ const code = new Promise((res, rej) => {
198
+ resolveCode = res;
199
+ rejectCode = rej;
200
+ });
201
+ const timer = setTimeout(() => rejectCode(new Error("timed out waiting for browser sign-in")), LOGIN_TIMEOUT_MS);
202
+ const server = http.createServer((req, res) => {
203
+ const u = new URL(req.url ?? "/", "http://localhost");
204
+ if (u.pathname !== "/callback") {
205
+ res.writeHead(404).end();
206
+ return;
207
+ }
208
+ const err = u.searchParams.get("error");
209
+ const got = u.searchParams.get("code");
210
+ const ok = !err && !!got && u.searchParams.get("state") === state;
211
+ res.writeHead(ok ? 200 : 400, { "content-type": "text/html" });
212
+ res.end(
213
+ `<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;padding:3rem;text-align:center"><h2>${ok ? "\u2713 Signed in to malloyyo" : "Sign-in failed"}</h2><p>${ok ? "You can close this tab and return to the terminal." : err ?? "state mismatch"}</p></body>`
214
+ );
215
+ clearTimeout(timer);
216
+ if (ok) resolveCode(got);
217
+ else rejectCode(new Error(err ?? "state mismatch or missing code"));
218
+ });
219
+ server.listen(0, "127.0.0.1", () => {
220
+ const port = server.address().port;
221
+ resolveServer({ port, code, close: () => server.close() });
222
+ });
223
+ });
224
+ }
225
+ async function login(baseUrl) {
226
+ const ep = await discover(baseUrl);
227
+ const { verifier, challenge } = pkce();
228
+ const state = crypto.randomBytes(16).toString("base64url");
229
+ const { port, code, close } = await awaitRedirect(state);
230
+ try {
231
+ const redirectUri = `http://localhost:${port}/callback`;
232
+ const clientId = await registerClient(ep.registration_endpoint, redirectUri);
233
+ const authUrl = new URL(ep.authorization_endpoint);
234
+ authUrl.search = new URLSearchParams({
235
+ response_type: "code",
236
+ client_id: clientId,
237
+ redirect_uri: redirectUri,
238
+ code_challenge: challenge,
239
+ code_challenge_method: "S256",
240
+ scope: "mcp",
241
+ state
242
+ }).toString();
243
+ console.log("Opening your browser to sign in\u2026");
244
+ console.log(`If it doesn't open, visit:
245
+ ${authUrl.toString()}
246
+ `);
247
+ openBrowser(authUrl.toString());
248
+ const authCode = await code;
249
+ const res = await fetch(ep.token_endpoint, {
250
+ method: "POST",
251
+ headers: { "content-type": "application/x-www-form-urlencoded" },
252
+ body: new URLSearchParams({
253
+ grant_type: "authorization_code",
254
+ code: authCode,
255
+ redirect_uri: redirectUri,
256
+ client_id: clientId,
257
+ code_verifier: verifier
258
+ })
259
+ });
260
+ if (!res.ok) throw new Error(`token exchange failed: ${res.status} ${await res.text()}`);
261
+ const grant = await res.json();
262
+ const creds = {
263
+ clientId,
264
+ accessToken: grant.access_token,
265
+ refreshToken: grant.refresh_token,
266
+ expiresAt: Date.now() + (grant.expires_in ?? 86400) * 1e3
267
+ };
268
+ saveCreds(baseUrl, creds);
269
+ return creds;
270
+ } finally {
271
+ close();
272
+ }
273
+ }
274
+ async function refresh(baseUrl, creds) {
275
+ const ep = await discover(baseUrl);
276
+ const res = await fetch(ep.token_endpoint, {
277
+ method: "POST",
278
+ headers: { "content-type": "application/x-www-form-urlencoded" },
279
+ body: new URLSearchParams({
280
+ grant_type: "refresh_token",
281
+ refresh_token: creds.refreshToken,
282
+ client_id: creds.clientId
283
+ })
284
+ });
285
+ if (!res.ok) throw new Error(`refresh failed: ${res.status}`);
286
+ const grant = await res.json();
287
+ const updated = {
288
+ clientId: creds.clientId,
289
+ accessToken: grant.access_token,
290
+ refreshToken: grant.refresh_token,
291
+ expiresAt: Date.now() + (grant.expires_in ?? 86400) * 1e3
292
+ };
293
+ saveCreds(baseUrl, updated);
294
+ return updated;
295
+ }
296
+ async function getAccessToken(target, opts) {
297
+ if (opts.tokenFlag) return opts.tokenFlag;
298
+ if (target.tokenEnv && process.env[target.tokenEnv]) return process.env[target.tokenEnv];
299
+ let creds = loadCreds(target.url);
300
+ if (!creds) {
301
+ throw new Error(`Not authenticated for ${target.url}.
302
+ Run: malloyyo login ${target.name}`);
303
+ }
304
+ if (creds.expiresAt - Date.now() < 6e4) {
305
+ try {
306
+ creds = await refresh(target.url, creds);
307
+ } catch {
308
+ throw new Error(`Session expired for ${target.url}.
309
+ Run: malloyyo login ${target.name}`);
310
+ }
311
+ }
312
+ return creds.accessToken;
313
+ }
314
+
315
+ // src/mcp.ts
316
+ import fs from "node:fs";
317
+ import path2 from "node:path";
318
+ import url2 from "node:url";
319
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
320
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
321
+ import {
322
+ MalloyConfig,
323
+ Runtime,
324
+ discoverConfig
325
+ } from "@malloydata/malloy";
326
+
327
+ // ../mcp-engine/dist/index.js
328
+ import {
329
+ MalloyError,
330
+ expressionIsAggregate,
331
+ expressionIsAnalytic
332
+ } from "@malloydata/malloy";
333
+ import { prettify as internalPrettify } from "@malloydata/malloy/internal";
334
+ import { API, MalloyError as MalloyError2 } from "@malloydata/malloy";
335
+ import { MalloyError as MalloyError3 } from "@malloydata/malloy";
336
+ import path from "node:path";
337
+ import url from "node:url";
338
+ var HOST_ONLY = "host_only";
339
+ var contentFiles = {
340
+ "develop/connection-setup.md": '---\ndescription: Setting up a data connection (malloy-config.json)\n---\n\n# Setting up a data connection\n\nA model reaches its data through a **connection** declared in\n`malloy-config.json` at the **root of the model** (next to `index.malloy`). This\nis Malloy\'s standard connection config \u2014 the full reference, with every\nconnector\'s properties, is at\n<https://docs.malloydata.dev/documentation/setup/config>. The essentials:\n\n## The file\n\n```json\n{\n "connections": {\n "mydb": { "is": "duckdb" }\n }\n}\n```\n\n- A connection has a **name** (the key) and a type (`is`). Sources refer to it by\n that name \u2014 `source: x is mydb.table("orders")` or `mydb.sql("SELECT \u2026")` \u2014 so\n the name in the config must match the name in the model.\n- Supported types (`is`): `duckdb` (incl. MotherDuck), `bigquery`, `postgres`,\n `mysql`, `snowflake`, `databricks`, `trino`, `presto`. Each has its own\n properties \u2014 see the full docs.\n\n## Default connections (and when they apply)\n\nSetting `"includeDefaultConnections": true` makes one connection available for\n**each registered database type, named by the type** \u2014 a `duckdb` connection\nnamed `duckdb`, a `postgres` named `postgres`, and so on. Each uses that\nconnector\'s default settings, which for several backends means picking up\ncredentials from the environment (e.g. BigQuery\'s application-default\ncredentials \u2014 see the per-connector setup docs). Connections you name explicitly\nin `connections` always win; the defaults only fill in types you didn\'t list.\n\n```json\n{\n "includeDefaultConnections": true,\n "connections": { "warehouse": { "is": "postgres", "host": "\u2026" } }\n}\n```\n\nmalloyyo has one rule worth knowing:\n\n- **No `malloy-config.json` at all \u2192 defaults are ON.** `duckdb` just works with\n zero setup.\n- **Write a `malloy-config.json` and they turn OFF** unless you add\n `"includeDefaultConnections": true`. A config that only defines, say, a\n `postgres` connection will report *No connection named "duckdb"* if a source\n still references `duckdb`.\n\nThis is deliberate \u2014 your local connections then resolve exactly the way the\npublished server\'s will, rather than silently leaning on a default that would not\nexist in production. (It differs from `malloy-cli`, which forces the defaults on\nunconditionally.)\n\nGive a connection a **custom name** \u2014 not the bare type default \u2014 whenever you\nhave more than one connection of the same type, or need non-default parameters.\n\n## DuckDB and local files (the common case)\n\nDuckDB can either open a **DuckDB database file** or read **local data files**\n(CSV, Parquet, \u2026) directly.\n\n**A pre-loaded database file** \u2014 point `databasePath` at a `.duckdb` file and\nreference its tables by name (an absolute path is safest):\n\n```json\n{ "connections": { "warehouse": { "is": "duckdb", "databasePath": "/data/warehouse.duckdb" } } }\n```\n\n**Local files, by path** \u2014 read a CSV or Parquet file straight into a source.\nThese paths are **project-relative** \u2014 resolved against the model root, so they\nsurvive publishing:\n\n source: my_csv is duckdb.table(\'data/my_file.csv\')\n source: my_parquet is duckdb.table(\'data/my_file.parquet\')\n\n`.table()` names a single file. When you need something it can\'t express \u2014 a\nglob, a union, any SQL \u2014 wrap it in `.sql()` (its paths are project-relative too):\n\n source: payments is duckdb.sql(\n "SELECT * FROM read_parquet(\'data/payments-*.parquet\')"\n )\n\nThe default `duckdb` connection is **in-memory** \u2014 nothing persists between runs;\nyour data lives in the files (or the `databasePath` database) you read.\n\n**MotherDuck:** a DuckDB connection against an `md:` database; set the\n`MOTHERDUCK_TOKEN` environment variable.\n\n## Secrets \u2014 keep them out of the file\n\nAny property value may be written as `{ "env": "VAR_NAME" }`. It resolves from\n`process.env.VAR_NAME` when the connection opens, so passwords and tokens never\nget committed:\n\n```json\n{\n "connections": {\n "analytics": {\n "is": "postgres",\n "host": "db.internal",\n "databaseName": "analytics",\n "username": "reader",\n "password": { "env": "PG_PASSWORD" }\n }\n }\n}\n```\n\n(The non-secret property names here are illustrative \u2014 each connector\'s exact\nproperties are in the full docs. The `{ "env": \u2026 }` form is the part that\nmatters: it works for any value.)\n\n## malloyyo specifics\n\n- **One file, one place.** Only the `malloy-config.json` at the model root is\n read \u2014 there is no walk-up to parent directories.\n- **Local override:** a `malloy-config-local.json` (do **not** commit it)\n **replaces** `malloy-config.json` entirely when present \u2014 your private variant\n for local credentials or a different database.\n- **The same file ships to production.** Publishing uploads this exact\n `malloy-config.json`, so it must resolve the same way locally and on the\n server \u2014 put anything environment-specific behind `{ "env": \u2026 }` rather than\n hard-coding it. That is what makes the local test window faithful to\n production.\n- Edits are picked up **without a restart** \u2014 the server re-reads the file when\n it changes.\n\n## When a connection will not resolve\n\nFix the connection **first**: a broken connection yields an empty schema and then\na cascade of misleading `field-not-found` errors \u2014 ignore those and fix the\nconnection. A fast check is to compile a probe and see if it alone compiles:\n\n source: _probe is mydb.sql("SELECT 1 AS one")\n',
341
+ "develop/getting-started.md": '---\ndescription: Getting started \u2014 build a Malloy model step by step\n---\n\n# Building a Malloy model, step by step\n\nA model is a `malloy-config.json` (the connection to the data) and an\n`index.malloy` (the published query surface), optionally with other `.malloy`\nfiles that `index.malloy` imports. You edit these with your own file tools; the\nMCP tools compile, inspect, and test what you wrote. Never read `.malloy` as\ntext \u2014 compiling a bare source is how you read a table\'s schema.\n\n## 1. Verify the connection first\n\nConfirm the connection named in `malloy-config.json` resolves \u2014 compile a\nthrowaway probe inline with `compile` (no file needed):\n\n source: _probe is CONN.sql("SELECT 1 AS one")\n\nIf it compiles, the connection is good. If not, fix the connection / config\nbefore going further \u2014 a broken connection produces an empty schema and then a\ncascade of misleading `field-not-found` errors; ignore the cascade and fix the\nconnection. Call `yo_help("develop/connection-setup")` for how to set up or repair a connection.\n\n## 2. Identify the tables the model needs\n\nIf you are unsure which tables matter, ask the fox \u2014 they own the data and know\nwhere it lives.\n\n## 3. Get a base source per table\n\nA base is "what\'s in the table and what\'s computable from it" \u2014 no joins.\nDiscover the schema by compiling a bare stub inline with `compile`:\n\n source: users_base is CONN.table("users")\n\n`compile` returns the full column list + types \u2014 that is your schema browser.\nThen write the base into its own file and iterate with `compile_file`, adding\nonly the dimensions and measures intrinsic to that one table:\n\n // users_base.malloy\n source: users_base is CONN.table("users") extend {\n measure: user_count is count()\n }\n\nIf the data lives in files rather than database tables \u2014 common when the\nconnection is DuckDB \u2014 DuckDB lets you name a file path as the table (a\nproject-relative path):\n\n source: users_base is CONN.table(\'data/users.parquet\')\n\nOnly drop to a `.sql()` block when a single file-as-table can\'t express what you\nneed \u2014 e.g. globbing or unioning several files:\n\n source: users_base is CONN.sql("SELECT * FROM read_parquet(\'data/users-*.parquet\')")\n\n(`read_parquet` there is DuckDB SQL, not Malloy \u2014 see `yo_help("develop/connection-setup")`.)\n\n## 4. Assemble index.malloy \u2014 the published surface\n\nImport the bases, join them into the consumer-facing sources, and explicitly\nexport what consumers may query:\n\n import "users_base.malloy"\n import "orders_base.malloy"\n\n source: users is users_base extend {\n join_many: orders is orders_base on id = orders.user_id\n }\n source: orders is orders_base extend { }\n\n export { users, orders }\n\n**Export discipline** \u2014 the model is a published artifact, so be deliberate about\nits public surface:\n\n- Imported names are private. Base sources stay internal scaffolding unless you\n export them.\n- Without an `export` statement, everything you define is public. Add one and the\n surface becomes explicit: only the names you list \u2014 defined or imported \u2014 are\n public.\n- Hide intermediates. A staging source you define only so other sources can build\n on it should not be exported.\n- The export list is the consumer\'s menu \u2014 exactly what the test window and real\n consumers can query, nothing more.\n\n## The loop\n\nEdit a file \u2192 `compile_file` \u2192 fix `problems[]` \u2192 `query` (pass the model file\'s\npath as `ref`; `execute: false` validates first and reports the givens the query\nneeds, supplied via `givens`). Query text is restricted \u2014 `import`, `given:`\ndeclarations, `connection.table`/`connection.sql`, raw SQL, and `##!` flags\nbelong in the model file, not the query. When `compile`/`compile_file` returns\n`formatted: false`, call `prettify` and save its output. Use project-relative\ndata paths, not absolute \u2014 they resolve against the project root and survive\npublishing the model.\n',
342
+ "develop/working-with-models.md": "---\ndescription: Working with an existing Malloy model\n---\n\n# Working with an existing model\n\nAn existing model is an `index.malloy` (plus any `.malloy` files it imports) and\na `malloy-config.json`.\n\n## Understand the model\n\n- **Read `malloy-config.json` directly** \u2014 it is JSON, so read it as text. It\n lists the connection(s) the model queries against; `yo_help(\"develop/connection-setup\")` explains\n the format (and how to set one up or repair it).\n- **Do NOT read `.malloy` as text \u2014 compile it.** `compile_file` returns the\n structured model: each source with its fields, joins, views, and named queries,\n plus `problems[]`. That is how you describe what is in the model. (Compiling a\n bare source \u2014 no `extend` block \u2014 likewise reads a raw table's schema.)\n\n## The loop\n\nEdit a file \u2192 `compile_file` \u2192 fix `problems[]` \u2192 `query`. Pass the model file's\npath as `ref`; `execute: false` validates first and reports the givens the query\nneeds (supplied via `givens`). Query text is restricted \u2014 `import`, `given:`\ndeclarations, `connection.table`/`connection.sql`, raw SQL, and `##!` flags\nbelong in the model file, not the query. When `compile`/`compile_file` returns\n`formatted: false`, run `prettify` and save its output. Use project-relative data\npaths, not absolute.\n",
343
+ "explore/how-to.md": "---\ndescription: Extended instructions working with this MCP server\n---\n# General Notes\nMalloy is a combined semantic layer/query language. It describes data and analysis, and it can generate and execute SQL.\n\nYou answer questions from published Malloy semantic models. A model publishes sources and queries.\n\n* Some tools return problems[] to indicate invalid Malloy. problems may have a `help_topic` field \u2014 call `yo_help(help_topic)` for detailed guidance.\n* `yo_help()` with no topic will show an index which include error explanations, examples of Malloy syntax for common patterns, and a language reference manual (Malloy syntax is still evolving).\n* Tools that inspect Malloy code return objects with schemas, among other things. An entry with a name which requires `back-tick-quoting` (reserved word, special characters), will have `must_quote: true`\n* When limiting queries, do ranking, top-N, and member selection in Malloy, not in client code. Results are byte-budgeted: oversized results are truncated (the response says so and may link the full result). Reading aggregated rows is better analysis and the only way to see everything.\n* Compose your answer from what the model publishes. When composing a query, you can make new sources, extending existing sources with measures dimensions and joins. If the model's surface genuinely cannot answer a question, that is useful signal about the model.\n\n# Answering A Question\nTo answer a question you need to see what sources are available which pertain to the question.\n\n`list_sources` (when available) \u2014 see the sources you can query, grouped by model, with each model's named queries. If you already know the source, go straight to describe_source.\n\n# Build the Query\n* `describe_source(source, model_ref)` \u2014 always describe a source before querying it (`model_ref` optional when the name is unique). Returns:\n * `described_source` \u2014 the source's `dimensions` (columns), `measures`, and `views` (the author's saved queries). A dimension's `type` is a scalar or a nested record (`origin.city`); an array column has no `type` \u2014 it shows up as a `joins` entry at its `path`.\n * `joins` \u2014 keyed by path, the arrays and source-joins this source reaches. `fans_out` marks a path that fans out. Each entry is one of: `{ source }` (fields in `join_source_map`), `{ source_def }` (an anonymous source's fields, inline), or an array `{ is_array, source_def }` \u2014 a record array's fields are used directly (`parcels.sku`), a scalar array's element is `each` (`tags.each`). To write a reference, use the entry's `quoted_path` if it has one, else the key.\n * `join_source_map` \u2014 the named sources those `{ source }` joins resolve to, deduped.\n * In its own content block, the source's raw Malloy, for anything the structured output above doesn't cover.\n* `query(source: \"...\", malloy: \"run: source -> { ... }\", execute: false)` \u2014 validate without running; it returns the SQL. Iterate until clean. (`model_ref` optional, needed only when the source name is ambiguous.)\n* Some queries accept parameters (givens). More info if needed: yo_help(\"language/givens-model-level-parameters\")\n\n# Run the query\n* Pass a plain-English question with EVERY query, describing what that specific query answers. Queries are recorded/shared independently. Don't try to group related queries.\n* query(source: \"...\", malloy: \"run: source -> { ... }\", question: \"...\") \u2014 run it; get the rows.\n\n# Displaying Results\n* Lead with a natural-language restatement of the query \u2014 a short heading works well.\n* A successful query comes back with an ltool_link \u2014 {text, url}, already assembled. It opens this exact query so the user can keep exploring, or share the insight. Follow the data with a markdown link, [\u2197 text](url).\n* When it helps the reader add a short note on how you got the answer: the Malloy logic (filters, grouping, aggregation, ordering, pipeline stages), and any post-processing done outside Malloy.",
344
+ "explore/restricted-queries.md": "# Restricted Query Explanation\n\nThe `query` tool runs your Malloy against a **published model**. You have that\nmodel's entire published surface to work with \u2014 and you can build on it. The\nmodel is an inentionally curated subset of the data available in the\ndatabase.\n\n## You can\n\n- Use everything the model defines: its **sources, dimensions, measures, views,\n joins, and named queries**. `describe_source` shows exactly what's there.\n- **Run a named query and refine it** \u2014\n `run: top_carriers + { where: dep_year = 2024 }`.\n- **Define your own** dimensions, measures, and **your own sources and joins** \u2014\n as long as they are *derived from the model's sources*. You are not limited to\n the author's fields; compose new ones from them.\n- Reference the model's `$NAME` givens and supply values via the `givens` map on\n the `query` call (use `execute: false` to discover which a query needs).\n- Use a model field that was itself defined with raw SQL \u2014 the author vouched\n for the model's own definitions.\n\n## What is \"Restricted\"\n\nIf you see `restricted-construct-forbidden`, the query used something that\nreaches *outside* the published model: pulling in another file (`import`),\nopening a raw connection (`connection.table(...)` / `connection.sql(...)`),\nwriting raw SQL (`name!type(...)` or the `sql_*` functions), declaring new\n`given:`s, or setting `##!` compiler flags.\n\nThe fix is never to work around it \u2014 express the answer in terms of what the\nmodel publishes (define derived sources, joins, dimensions, and measures from\nthe model's sources). If something fundamental is missing, that's feedback for\nthe model's author.\n",
345
+ "language/malloy-language-reference.md": '<!-- Copied from malloy-cli (jrtipton/malloy-cli) skills/malloy-language-reference.md on 2026-06-11.\n Deliberate temporary fork \u2014 converge when the engine is extracted to @malloydata. -->\n---\ndescription: Malloy language reference \u2014 concepts, syntax, compilation model. Load this before writing or reviewing Malloy code.\n---\n# Malloy Language Reference\n\nMalloy is a semantic data modeling and query language. It compiles to SQL and runs against existing database engines (DuckDB, BigQuery, Snowflake, PostgreSQL, MySQL, Trino, Presto). It is not a SQL wrapper or abstraction layer \u2014 it has its own type system, scoping rules, expression semantics, and compilation pipeline.\n\nMalloy is designed around how humans think about data, not how data computations are mechanically accomplished. SQL is oriented around the machine \u2014 you specify joins, group-by columns, subqueries, and window functions in terms of what the database needs to do. Malloy is oriented around the analyst \u2014 you describe relationships, name computations, and compose questions in terms of what the data means. Malloy bridges the gap between these two by compiling the human-oriented description into correct, efficient SQL.\n\nA core design principle is that **most queries are themselves designing a new semantic model.** Formulating a question about data \u2014 choosing what to group by, what to aggregate, what to nest \u2014 is inherently an act of defining a new way to look at that data. Malloy is built around this idea: the output of every query is not just a result set but a new source with its own schema, and data comprehension is an ongoing iterative process where later stages want not only the data from a previous stage but how that data came into being. This is why query output carries metadata, why queries can be used as sources, and why views and pipelines compose naturally.\n\n## Documents and Statements\n\nA Malloy file (`.malloy`) is a sequence of statements, optionally separated by semicolons. There are five statement types:\n\n- **`import`** \u2014 import sources and queries from another `.malloy` file\n- **`source:`** \u2014 define a named, reusable data source with its schema and extensions\n- **`query:`** \u2014 define a named query (source + view) for reuse\n- **`run:`** \u2014 execute a query (the "do it now" statement)\n- **`given:`** \u2014 declare model-level parameters supplied at run time (experimental, see Givens)\n\n```malloy\nimport "shared_model.malloy"\n\nsource: flights is duckdb.table(\'flights.parquet\') extend {\n measure: flight_count is count()\n}\n\nquery: carrier_summary is flights -> {\n group_by: carrier\n aggregate: flight_count\n}\n\nrun: carrier_summary\n```\n\nComments use `//` or `--` (both are line comments).\n\n## Sources\n\nA **source** is anything you can hand a SQL database and get a schema back \u2014 a table name, a SQL SELECT, or the output of another Malloy query. The columns in that schema become the source\'s initial fields (all dimensions).\n\n```malloy\nsource: flights is duckdb.table(\'flights.parquet\')\nsource: limited is duckdb.sql("""SELECT * FROM flights LIMIT 100""")\nsource: carrier_facts is carrier_summary -- a query used as a source\n```\n\nWhat makes sources central to Malloy is **extension**. The `extend` block lets you layer on dimensions, measures, views, joins, filters, primary keys, field restrictions, and renames. These extensions travel with the source \u2014 any query against it gets them for free.\n\n```malloy\nsource: flights is duckdb.table(\'flights.parquet\') extend {\n primary_key: id\n\n dimension: distance_km is distance * 1.609344\n\n measure:\n flight_count is count()\n total_distance is sum(distance)\n\n join_one: carriers with carrier\n join_one: origin_airport is airports on origin_airport.code = origin\n\n where: dep_time > @2001\n\n view: by_carrier is {\n group_by: carrier\n aggregate: flight_count, total_distance\n }\n}\n```\n\nSources can extend other sources, creating a refinement chain:\n\n```malloy\nsource: ca_flights is flights extend {\n where: origin.state = \'CA\'\n}\n```\n\nField access control uses `accept:` (allowlist) or `except:` (denylist) to restrict which inherited columns are visible. Fields can be renamed with `rename: new_name is old_name`.\n\n## Joins\n\nJoins are declared in the source, not reconstructed in every query. This is a fundamental design difference from SQL: the graph structure of your data is a property of the model.\n\n```malloy\njoin_one: carriers with carrier -- FK \u2192 PK shorthand\njoin_one: origin_airport is airports on origin_airport.code = origin -- explicit ON\njoin_many: line_items on line_items.order_id = id -- one-to-many\njoin_cross: other_table on other_table.key = key -- cross join\n```\n\n- `join_one` \u2014 the joined source has at most one row per source row (many-to-one or one-to-one)\n- `join_many` \u2014 the joined source has potentially many rows per source row\n- `join_cross` \u2014 a full cross product\n\nThe `with` shorthand requires the joined source to have a declared `primary_key`. All joins are left outer by default. There is no right join \u2014 Malloy\'s graph model doesn\'t need one.\n\n**Choosing `join_one` vs `join_many`:** Ask "for a single row in the base source, can the joined source match more than one row?" If yes \u2192 `join_many`. If no (or at most one) \u2192 `join_one`. The common mistake is reaching for `join_many` when joining a *lookup or summary table* (e.g., joining an inventory snapshot to a purchase history on a wine key). Even though the joined table may have many rows overall, if each base row resolves to *at most one* joined row, use `join_one`. Use `join_many` only when the join genuinely fans out the base rows \u2014 e.g., joining line items to orders, or notes to a wine catalog.\n\nWhen you reference a joined source\'s fields, you use dot notation: `carriers.nickname`, `origin_airport.state`. This is one of Malloy\'s most important abstractions: **the access path to nested data is identical regardless of how the nesting is physically stored.** An array of records embedded in a column, a `join_many` to a separate table, a record-typed column \u2014 all are navigated with the same dot notation. The SQL required to traverse these different physical arrangements varies wildly (unnesting arrays, LEFT JOINs, correlated subqueries, ARRAY_AGG), but Malloy hides all of that. You think about the logical shape of your data \u2014 "flights have carriers, carriers have a nickname" \u2014 and write `carriers.nickname`. The compiler figures out what SQL is needed to get there. This means you can restructure your physical schema (normalize a nested array into a separate table, or denormalize a joined table into a record column) without changing any of the Malloy that references that data.\n\n## Fields\n\nMalloy has four kinds of fields: **dimensions**, **measures**, **views**, and **calculations**.\n\n### Dimensions\n\nScalar expressions \u2014 they compute a value per row. All columns inherited from a table are dimensions. Computed dimensions reference other dimensions or columns:\n\n```malloy\ndimension: full_name is concat(first_name, \' \', last_name)\ndimension: is_long_haul is distance > 1000\n```\n\n### Measures\n\nAggregate expressions \u2014 they compute a value across a set of rows. A field is a measure when its defining expression contains an aggregate function (`count`, `sum`, `avg`, `min`, `max`):\n\n```malloy\nmeasure:\n flight_count is count()\n total_distance is sum(distance)\n avg_distance is avg(distance)\n pct_delayed is count() { where: dep_delay > 30 } / count()\n```\n\n**`count(expr)` counts distinct values.** Unlike SQL\'s `COUNT(DISTINCT expr)`, Malloy uses `count(expr)` for distinct counting. The `count(distinct expr)` form is a deprecated syntax that will produce an error. Use `count()` for total row count, `count(field)` for distinct values of that field:\n\n```malloy\naggregate:\n total_rows is count() -- all rows\n unique_carriers is count(carrier) -- distinct carriers\n```\n\nMeasures can be filtered inline with `{ where: ... }`, which is how you build things like "percent of flights delayed" without subqueries.\n\n### Views\n\nA view is a query saved into the source \u2014 a reusable transformation:\n\n```malloy\nview: by_carrier is {\n group_by: carrier\n aggregate: flight_count, total_distance\n limit: 10\n}\n```\n\nViews can reference other views from the same source as a starting point, and can be extended with `+`.\n\n### Calculations\n\nWindow functions over the grouped result. Calculations can only be defined in a query stage with `calculate:`, never in a source definition, because they depend on the output columns of the query:\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count\n calculate: carrier_rank is rank()\n}\n```\n\n## Queries and Views\n\nA query pairs a source with a view (the transformation). Everything after the first `->` is the view.\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count\n}\n```\n\n### Reduction vs. Projection\n\nEach stage of a view performs exactly one of:\n\n- **Reduction** \u2014 uses `group_by:` and/or `aggregate:` to reduce grain. Analogous to `SELECT ... GROUP BY` in SQL.\n- **Projection** \u2014 uses `select:` to pick fields without aggregation. Analogous to `SELECT` without `GROUP BY`.\n\nThese cannot be mixed in a single stage. A stage with `group_by:` cannot have `select:`, and vice versa.\n\n### Source-level definitions vs. query-level operations\n\nThe same `name is expression` syntax defines fields in both sources and queries:\n\n```malloy\n-- In a source (reusable):\nsource: flights is ... extend {\n measure: flight_count is count() -- defines a measure in the model\n}\n\n-- In a query (ad hoc):\nrun: flights -> {\n aggregate: flight_count is count() -- defines the same measure inline\n}\n```\n\nWhen used in a source, `measure:` and `dimension:` are **definition statements** \u2014 they add named fields to the source\'s schema. When used in a query, `group_by:`, `aggregate:`, `select:`, `nest:`, and `calculate:` are **query operations** \u2014 they specify what the query does. The field definitions are syntactically identical in both contexts, but the enclosing keyword determines the role:\n\n| Source keyword | Query keyword | What it holds |\n|---|---|---|\n| `dimension:` | `group_by:` or `select:` | scalar expressions |\n| `measure:` | `aggregate:` | aggregate expressions |\n| `view:` | `nest:` | sub-queries |\n| _(n/a)_ | `calculate:` | window functions |\n\nThis is why `measure` and `aggregate` are separate keywords. `measure:` is a *modeling* statement \u2014 "this source has a reusable aggregate computation called X." `aggregate:` is a *query* statement \u2014 "in this query, include these aggregate values in the output." A query\'s `aggregate:` can reference a previously defined measure by name, or define one inline. The distinction parallels the separation between defining a dimension in a source and using it via `group_by:` in a query.\n\n### Multi-stage Pipelines\n\nStages chain with `->`. Each stage\'s output becomes the next stage\'s source:\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count is count()\n} -> {\n where: flight_count > 1000\n select: *\n}\n```\n\n### Refinement with `+`\n\nThe refinement operator `+` merges query operations together. It works both within a view and at the top level on a named query:\n\n```malloy\n-- Refining a view within a query:\nrun: flights -> by_carrier + { limit: 5 } + { nest: by_destination }\n\n-- Refining a named query at the top level:\nrun: carrier_summary + { group_by: origin } -- add origin grouping to existing query\n```\n\nWhen a dimension name appears as a bare reference, it expands to `{ group_by: name }`. A measure name expands to `{ aggregate: name }`:\n\n```malloy\nrun: flights -> carrier + flight_count + { limit: 10 }\n-- equivalent to: flights -> { group_by: carrier; aggregate: flight_count; limit: 10 }\n```\n\nFor multi-stage queries, refinement semantics get more complex \u2014 but for single-stage queries, `+` straightforwardly merges operations into the stage.\n\n### Nesting\n\n`nest:` embeds an aggregating subquery inside a reduction. Each row of the outer query gets a subtable from the nested query. Nests can nest arbitrarily deep:\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count\n nest: top_routes is {\n group_by: origin, destination\n aggregate: flight_count\n limit: 3\n }\n}\n```\n\n### Other query operations\n\n- **`where:`** \u2014 filter rows (pre-aggregation). Comma-separated filters are ANDed.\n- **`having:`** \u2014 filter groups (post-aggregation), like SQL\'s HAVING.\n- **`limit:`** / **`order_by:`** \u2014 limit and sort output.\n- **`extend`** \u2014 add fields or joins to a source inline within a query expression.\n\n## Aggregate Locality (Symmetric Aggregates)\n\nThis is one of Malloy\'s most important features. In SQL, when you join tables and aggregate, you risk double-counting (the "fan trap"). Malloy solves this with **aggregate locality** \u2014 you specify *where in the join graph* an aggregation should be computed.\n\n```malloy\nrun: flights -> {\n aggregate:\n -- avg seats weighted by number of flights (locality: source, i.e. flights)\n avg_seats_per_flight is source.avg(aircraft.aircraft_models.seats)\n -- avg seats per aircraft model (locality: aircraft_models)\n avg_seats_per_model is aircraft.aircraft_models.seats.avg()\n}\n```\n\nThree syntactic forms:\n\n- `avg(expr)` \u2014 aggregate at the current source (implicit locality)\n- `joined_source.avg(expr)` \u2014 aggregate at the specified join point (explicit locality)\n- `joined_source.field.avg()` \u2014 shorthand for aggregating the field at its parent source\n\nFor `sum` and `avg` (asymmetric aggregates), when the expression crosses a join boundary, Malloy *requires* explicit locality \u2014 it won\'t silently give you a wrong answer. For `min`, `max`, and `count` (symmetric), locality doesn\'t change the result, so implicit is always fine.\n\nMalloy implements this with a technique called **symmetric aggregates** \u2014 it internally de-duplicates rows based on primary keys at the appropriate join level, so aggregations are always mathematically correct regardless of join fan-out.\n\n## Ungrouped Aggregates\n\n`all()` and `exclude()` allow computing aggregates at different grouping levels within a single query:\n\n```malloy\nrun: airports -> {\n group_by: state, faa_region\n aggregate:\n airport_count is count()\n total_airports is all(count()) -- ungrouped: total across all rows\n region_airports is all(count(), faa_region) -- grouped only by faa_region\n pct_of_total is count() / all(count())\n}\n```\n\n`all(expr)` removes all grouping. `all(expr, dim1, dim2)` keeps only the specified grouping dimensions. `exclude(expr, dim)` removes the specified dimension from grouping.\n\n**Important:** `all(expr, dim)` takes the **local alias name** as defined in the query\'s `group_by:`, not a dotted path. If you want to partition by a joined field, alias it first:\n\n```malloy\n-- WRONG: all(count(), director.primaryName) -- dot paths don\'t work here\n-- RIGHT:\nrun: movies -> {\n group_by: director is director.primaryName -- alias it\n aggregate:\n movies is count()\n director_total is all(count(), director) -- reference the alias\n pct is count() / all(count(), director)\n}\n```\n\n## Expressions\n\nMalloy expressions include arithmetic, comparison, logical operators, function calls, type casts, and several Malloy-specific forms.\n\n### Evaluation Spaces\n\nEvery expression has an evaluation space: **literal**, **constant**, **input**, or **output**. Input expressions reference source columns/dimensions. Output expressions reference the results of the current query stage (used in `calculate:`). Some functions constrain their arguments \u2014 e.g., `lag(expr)` requires an output expression, `avg(expr)` requires an input expression.\n\n### Application and Partial Comparison\n\nThe `?` operator applies a condition to a value. Partial comparisons are conditions without a left-hand side:\n\n```malloy\nwhere: state ? \'CA\' | \'NY\' -- state is \'CA\' or \'NY\'\nwhere: distance ? > 500 & < 2000 -- distance between 500 and 2000\n```\n\n`|` is alternation (OR), `&` is conjunction (AND) within partials.\n\n### Pick Expressions\n\nMalloy\'s equivalent of CASE:\n\n```malloy\ndimension: size_bucket is\n pick \'short\' when distance < 500\n pick \'medium\' when distance < 1500\n else \'long\'\n```\n\n### Filtered Aggregate Expressions\n\nAny aggregate can be filtered inline:\n\n```malloy\nmeasure: ca_flights is count() { where: origin.state = \'CA\' }\n```\n\n### Type Casting\n\n```malloy\ntotal_distance::string -- Malloy type cast\nname::"VARCHAR(32)" -- database-native type cast\n```\n\n### Time Literals and Ranges\n\n```malloy\n@2003 -- the year 2003\n@2003-Q2 -- second quarter of 2003\n@2024-01-15 10:30:00 -- timestamp literal\ndep_time ? @2003 to @2005 -- range comparison\nnow -- current timestamp\n```\n\n## Data Types\n\nMalloy\'s type system: `string`, `number`, `boolean`, `date`, `timestamp`, `timestamptz`, `json`, and `sql native` (for unsupported database types). Compound types: `type[]` for arrays, `{ name :: type, ... }` for records, nesting arbitrarily: `{ x :: number, tags :: string[] }[]`.\n\n## Annotations and Tags\n\nThese are related but distinct concepts.\n\n### Annotations\n\nAnnotations are **text strings** attached to objects during compilation. They are metadata \u2014 they never affect query execution or SQL generation. An annotation starts with `#` and continues to end of line:\n\n```malloy\n# bar_chart\nview: by_carrier is { ... }\n```\n\n- `#` annotations attach to the next object defined below them\n- `##` annotations attach to the model (the file)\n- Block annotations use `#|` ... `|#` for multi-line content (closing delimiter must match the column position of the opener)\n\nAnnotations distribute over definition lists:\n\n```malloy\n# currency\nmeasure: -- all three measures get the # currency annotation\n revenue is sum(amount)\n # percent -- this measure also gets # percent\n margin is revenue / cost\n cost is sum(amount)\n```\n\n### Tags (a use of annotations)\n\nTags are the primary *consumer* of annotation strings. They interpret annotation text using a structured property language (MOTLY). The key distinction: **annotations are the transport mechanism (raw strings attached to objects), tags are the interpretation layer (parsed key-value properties).**\n\nNot all annotations are tags. An annotation is just text. Tags are annotations that happen to be written in the tag property language and parsed by an application.\n\n### Annotation prefixes (routing)\n\nThe character(s) immediately after `#` route the annotation to different consumers:\n\n- `# ` (hash-space) \u2014 renderer tags, parsed by the Malloy VS Code extension for visualization\n- `##!` \u2014 compiler directives (e.g., `##! experimental.parameters`, `##! experimental.givens`)\n- `#"` \u2014 reserved for documentation strings\n- `#(appName)` \u2014 application-specific tags (e.g., `#(docs) hidden`)\n\n```malloy\n# bar_chart size=large -- renderer tag: tells VS Code how to render\n##! experimental.parameters -- compiler tag: enables a feature flag\n#(myApp) priority=high -- custom app tag: ignored by renderer/compiler\n```\n\n### Tag property syntax\n\n```\ntName -- boolean flag (exists = true)\ntName=value -- set property value\ntName=[a, b, c] -- array value\ntName: { p1=v1 p2=v2 } -- nested properties (replaces)\ntName { p1=v1 } -- nested properties (merges)\n-tName -- delete a property\ntName.sub.path=value -- deep path assignment\n```\n\nValues can be unquoted identifiers, quoted strings, numbers, or typed values prefixed with `@` (`@true`, `@false`, `@2024-01-15`).\n\n## Givens (Model-Level Parameters)\n\n**Status: experimental, gated by `##! experimental.givens`.** Naming is provisional.\n\nGivens are values supplied at run time that the model can reference in any expression. The motivating use case is row-level access control \u2014 a model written once with `where: x.tenant_id = $TENANT` and the tenant supplied per API call \u2014 but they also fit configuration values, session context, and any "one compiled model, many invocations with varying context" pattern.\n\nGivens are model-wide: a single namespace, one value per name per compilation. They are *complementary to* source/query parameters (`source: foo(x :: string) is ...`), not a replacement. Use a parameter when you want two differently-bound copies of the same source side-by-side in one model; use a given when you want one value visible everywhere in the compilation.\n\n### Declaration\n\nThe `given:` top-level statement introduces givens, with a name, a type, and an optional default:\n\n```malloy\ngiven:\n TENANT :: string\n MAX_ROWS :: number is 1000\n CUTOFF_DATE :: date is @2024-01-01\n```\n\nType can be any Malloy atomic type or compound type, including `filter<T>`:\n\n```malloy\ngiven:\n ROLE :: string\n ALLOWED_ROLES :: string[]\n SESSION :: { user_id :: string, tenant :: string }\n TENANT_FILTER :: filter<string>\n```\n\nDefaults are expressions over constants and other givens. Annotations attach to given declarations the same way they attach to sources or measures.\n\n### Reference: the `$` sigil\n\nInside any expression, a given is referenced with a leading `$`:\n\n```malloy\nsource: orders_for_user is orders extend {\n where: orders.tenant_id = $TENANT\n}\n\nquery: recent_orders is orders_for_user -> {\n where: order_date >= $CUTOFF_DATE\n limit: $MAX_ROWS\n}\n```\n\n`$` appears *only* at expression references. The other three sites where a given\'s name appears \u2014 declaration, import, and supply (caller side) \u2014 use the bare name, because syntactic position already disambiguates. Givens share the top-level declaration namespace with sources/queries/views, so `source: x is ...` plus `given: x :: string` is a name-conflict error.\n\n### Set membership: `expr in $arrayGiven`\n\nThe RHS of `in` is either a parenthesized list of expressions (`in (1, 2, x, y * 7)`, same as SQL) or a given with an array value (`in $ARR`). A bare array-typed expression \u2014 a dimension, a joined array field, an inline `[a, b, c]` literal \u2014 is *not* legal on the RHS; arrays only reach the RHS via the given form.\n\nWhen a given has array type, `expr in $ARR` tests `expr` against the runtime-bound array; `not in $ARR` is the negation. The left-hand side must match the array\'s element type (`string in $string[]`, `number in $number[]`, etc.); mismatches are translate-time errors. Records and nested arrays are out of scope.\n\n```malloy\ngiven:\n ALLOWED_STATES :: string[]\n URGENT_STATUSES :: string[]\n\nsource: orders extend {\n where: state in $ALLOWED_STATES\n dimension: is_urgent is order_status in $URGENT_STATUSES\n}\n```\n\nAt SQL emit, the array\'s contents land in a generated `IN (...)` clause. Empty or `null` arrays collapse to the obvious result (`IN` \u2192 `FALSE`, `NOT IN` \u2192 `TRUE`). NULL elements inside a non-empty array follow standard SQL `IN` semantics.\n\nTo derive a value from an array \u2014 typically a boolean gate \u2014 *without* the array itself reaching row-position SQL, use an inline given (below).\n\n### Inline givens\n\nAn `inline` given is evaluated at **bind time**, before SQL is emitted: its default expression runs against the resolved given values and reduces to a literal, and that literal is what reaches SQL.\n\n```malloy\ngiven:\n CAPABILITIES :: string[]\n inline CAN_READ_ORDERS :: boolean is \'read_orders\' in $CAPABILITIES\n inline CAN_MUTATE :: boolean\n is \'write_orders\' in $CAPABILITIES or \'admin\' in $CAPABILITIES\n\nsource: orders extend {\n where: $CAN_READ_ORDERS -- SQL sees: WHERE ... AND TRUE (or FALSE)\n}\n```\n\nThis is the **row-level access-control gate** pattern: the host supplies a capability list as a regular given, an inline given derives a boolean from it, and only the boolean \u2014 not the list \u2014 crosses into row-position SQL. The query planner sees a constant predicate.\n\nRules:\n\n- An inline given **must** have a default. `inline FOO :: number` with no `is` clause is a translate-time error.\n- The default may use:\n - Boolean and comparison operators: `and`, `or`, `not`, `=`, `!=`, `<`, `<=`, `>`, `>=`\n - The `in $array` test against another given\n - Literals (string, number, boolean, null, array) and references to other givens\n- The default cannot call SQL functions, reference fields, or use any operator outside that list. Disallowed operators are reported at translate time with the offending operator names.\n- Inline givens are filtered out of `Model.givens` and `PreparedQuery.givens` \u2014 they\'re computed, not supplied \u2014 so introspection-driven UIs don\'t render editors for them. A caller can still shadow one by binding it explicitly (useful in tests).\n- `inline` is a context-sensitive modifier, not a reserved keyword: fields, sources, views, dimensions, and joins can still be named `inline`.\n\n### Imports\n\nGivens behave like every other top-level named thing under import:\n\n- **Bare import** (`import "b.malloy"`) brings B\'s full export surface in, including all of B\'s givens, under their original names.\n- **Selective import** (`import { source1 } from "b.malloy"`) brings in only what\'s listed. To surface a given to your callers, list it: `import { source1, MAX_ROWS } from "b.malloy"`.\n- **Rename** uses the existing `LOCAL is REMOTE` form: `import { CAP is MAX_ROWS } from "b.malloy"`.\n\nSurfacing controls *who can supply a value*, not whether internal references work. An imported source can reference a given the importer didn\'t surface; the reference still resolves internally, and at run time the unsurfaced given relies on its declaration-site default.\n\nA common project convention is a shared `tenant_givens.malloy` (declaring `$TENANT`, `$USER_ROLE`, etc.) that every root file bare-imports on line 1, so the project\'s given contract is visible at the top of any model.\n\n### Satisfiability\n\nA query referencing `$X` is satisfiable if either `$X` is in the model\'s namespace (so a caller can supply a value) or `$X` has a default at its declaration site. Otherwise the query is unsatisfiable and errors. Latent definitions (views, dimensions, measures) that reference `$X` are fine if no query actually invokes them \u2014 satisfiability is a property of running queries.\n\n### Supplying values\n\nValues can be supplied at two layers, which compose (per-query overrides per-runtime):\n\n**Per-runtime** \u2014 bound to a `Runtime`, applied as defaults to every query through it. Two paths:\n\n1. **`givensPath` in `malloy-config.json`** points at a JSON file of `name \u2192 value`:\n ```jsonc\n { "givensPath": "./local-givens.json" }\n // or env-var indirection (resolved at config load):\n { "givensPath": { "env": "GAME_STORE_GIVENS" } }\n ```\n The values file is a flat JSON map, keys are caller-facing surface names:\n ```jsonc\n { "TENANT": "acme", "USER_ROLE": "admin", "CUTOFF_DATE": "2024-01-01" }\n ```\n\n2. **Direct on the Runtime constructor** (for per-request multi-tenant servers, tests, scripts):\n ```typescript\n const runtime = new Runtime({\n config,\n givens: { TENANT: claims.tenant_id, USER_ROLE: claims.role },\n urlReader,\n });\n ```\n Constructor values *merge over* the file at `givensPath` per-key.\n\n**Per-query** \u2014 supplied on a single `.run({ givens: ... })` call:\n```typescript\nawait query.run({ givens: { STATE_FILTER: "CA", LIMIT_OVERRIDE: 50 } })\n```\nAvailable on every compile-or-run entry point (`runtime.loadQuery(...).run(options)`, `preparedQuery.getPreparedResult(options)`, `preparedQuery.getSQL(options)`).\n\nThe resolved per-runtime values are exposed on `runtime.givens` (read-only) for diagnostics.\n\n### Finalized givens (security primitive)\n\nA multi-tenant deployment usually wants `TENANT`/`USER_ROLE`/`REGION` to be runtime-bound and **un-overridable per-query** \u2014 otherwise a downstream endpoint that accidentally accepts user-controlled query params and plumbs them into `.run({ givens: ... })` becomes a tenant-leak vulnerability.\n\n`finalizeGivens` in the config locks names at the API surface:\n\n```jsonc\n{\n "givensPath": { "env": "GAME_STORE_GIVENS" },\n "finalizeGivens": ["TENANT", "USER_ROLE", "REGION"]\n}\n```\n\nFinalize doesn\'t change *what* a given resolves to \u2014 only *who* can supply it. A `.run({ givens: { TENANT: ... } })` for a finalized name throws at API entry (named, not silently dropped). Finalized givens are filtered out of `Model.givens` and `PreparedQuery.givens` so introspection-driven UIs don\'t render editors for locked names.\n\n### JS shapes for supplied values\n\nBoth the JSON values file and per-query `givens` maps accept the same per-type shapes:\n\n| Malloy type | JS |\n|---|---|\n| `string` | string |\n| `number` | `number`, `bigint`, or string (precision escape hatch) |\n| `boolean` | boolean |\n| `date` | ISO date string `"2024-01-15"` |\n| `timestamp` (naive) | ISO string without offset \u2014 *not* a JS `Date` |\n| `timestamptz` | JS `Date` or ISO string with offset (string preferred \u2014 makes TZ choice visible) |\n| `T[]` | JS array |\n| `{ name :: T, ... }` | JS object |\n| `filter<T>` | JS string (Malloy filter expression source) |\n\nNaive timestamp givens reject `Date` because `Date` represents a UTC instant, not a wall-clock value, and `new Date("2001-01-01T00:00:00")` silently picks up the system\'s local TZ. Type mismatches throw at the boundary with a path that points at the offending location (e.g., `givens.SESSION.user_id: expected string, got number`). `null` is legal for any given type.\n\n### Introspection\n\n`Model.givens` and `PreparedQuery.givens` expose, to the host, the supplyable givens \u2014 for whole-model parameter editors and per-query "run this" forms respectively. Each entry carries name, type, default expression (or undefined if the caller must supply), location, and access to declaration-site annotations via `tagParse`/`getTaglines`.\n\n## How a Malloy Query Becomes SQL\n\nThe compilation pipeline has two phases:\n\n### Phase 1: Translation (source code \u2192 IR)\n\n```\nMalloy source \u2192 ANTLR lexer/parser \u2192 parse tree \u2192 AST builder \u2192 AST \u2192 IR generator \u2192 IR\n```\n\nThe **Intermediate Representation (IR)** is a plain, serializable data structure (JSON-compatible) that fully describes the semantic model and query. Note that IR is *not* dialect-agnostic \u2014 the same Malloy source compiled against different databases can produce different IR, because schema information, type mappings, and available functions vary by backend. It can be cached, transmitted, and reused. Key IR types:\n\n- **`SourceDef`** \u2014 a source\'s complete definition: schema, fields, joins, filters\n- **`Query`** \u2014 a source paired with a pipeline of operations\n- **`FieldDef`** \u2014 definition of any field (dimension, measure, join, calculation)\n- **`Expr`** \u2014 expression tree (arithmetic, comparisons, aggregates, function calls, field references)\n\nThe translator handles all language-level semantics: scoping, name resolution, type checking, evaluation space validation.\n\n### Phase 2: Compilation (IR \u2192 SQL)\n\n```\nIR \u2192 query compiler \u2192 expression compiler \u2192 dialect-specific SQL generator \u2192 SQL + metadata\n```\n\nThe compiler walks the IR query pipeline, translating each stage into SQL constructs (CTEs, subqueries, GROUP BY, window functions). A **Dialect** layer handles database-specific SQL generation.\n\nThe compiler also produces **metadata** alongside the SQL \u2014 structural information needed to interpret the result set (column types, nesting structure, annotation data). This metadata is what allows Malloy renderers to reconstruct nested/hierarchical results from the flat SQL result set and apply visualization tags.\n\n### Key architectural consequences\n\n- Because the IR is serializable, it can be cached and reused across compilations (though IR is database-specific \u2014 the same source compiled against different backends may produce different IR).\n- Because joins are declared in the source (not the query), the compiler knows the full join graph and can compute symmetric aggregates correctly.\n- Because nested queries are first-class, the compiler generates the appropriate SQL (correlated subqueries or ARRAY_AGG patterns depending on dialect) automatically.\n- Because measures are typed as aggregates in the IR, the compiler can validate that they only appear in aggregate context and enforce locality rules.\n\n## Where to Go Deeper\n\nThis document is a conceptual reference \u2014 enough to reason about the language and its design, but not exhaustive. Here\'s where to find more detail.\n\n### Language Documentation\n\nThe full docs live at [https://docs.malloydata.dev](https://docs.malloydata.dev). Key pages by topic:\n\n| Topic | URL |\n|---|---|\n| Sources, extensions, joins, primary keys | [documentation/language/source](https://docs.malloydata.dev/documentation/language/source) |\n| Queries, views, reduction vs projection | [documentation/language/query](https://docs.malloydata.dev/documentation/language/query), [views](https://docs.malloydata.dev/documentation/language/views) |\n| Fields: dimensions, measures, views, calculations | [documentation/language/fields](https://docs.malloydata.dev/documentation/language/fields) |\n| Aggregate functions and aggregate locality | [documentation/language/aggregates](https://docs.malloydata.dev/documentation/language/aggregates) |\n| Ungrouped aggregates (`all`, `exclude`) | [documentation/language/ungrouped-aggregates](https://docs.malloydata.dev/documentation/language/ungrouped-aggregates) |\n| Nested views / aggregating subqueries | [documentation/language/nesting](https://docs.malloydata.dev/documentation/language/nesting) |\n| Joins | [documentation/language/join](https://docs.malloydata.dev/documentation/language/join) |\n| Expressions, operators, pick, apply | [documentation/language/expressions](https://docs.malloydata.dev/documentation/language/expressions) |\n| Evaluation spaces (literal, constant, input, output) | [documentation/language/eval_space](https://docs.malloydata.dev/documentation/language/eval_space) |\n| Filters and filter placement | [documentation/language/filters](https://docs.malloydata.dev/documentation/language/filters) |\n| Annotations and tags | [documentation/language/tags](https://docs.malloydata.dev/documentation/language/tags) |\n| Calculations and window functions | [documentation/language/calculations_windows](https://docs.malloydata.dev/documentation/language/calculations_windows) |\n| Data types | [documentation/language/datatypes](https://docs.malloydata.dev/documentation/language/datatypes) |\n| Time operations, ranges, timezones | [documentation/language/timestamp-operations](https://docs.malloydata.dev/documentation/language/timestamp-operations), [time-ranges](https://docs.malloydata.dev/documentation/language/time-ranges), [timezones](https://docs.malloydata.dev/documentation/language/timezones) |\n| Imports | [documentation/language/imports](https://docs.malloydata.dev/documentation/language/imports) |\n| Top-level statements and model structure | [documentation/language/statement](https://docs.malloydata.dev/documentation/language/statement) |\n| Functions reference | [documentation/language/functions](https://docs.malloydata.dev/documentation/language/functions) |\n\n### Examples and Patterns\n\nThe docs site includes worked examples of common analytical patterns at [documentation/patterns](https://docs.malloydata.dev/documentation/patterns/): percent-of-total, year-over-year, cohort analysis, sessionization, moving averages, nested subtotals, and more.\n\nEnd-to-end guides are at [documentation/user_guides](https://docs.malloydata.dev/documentation/user_guides/), including [Malloy by Example](https://docs.malloydata.dev/documentation/user_guides/malloy_by_example) (a comprehensive walkthrough) and a three-part series for SQL users ([part 1](https://docs.malloydata.dev/documentation/user_guides/sql_experts1), [part 2](https://docs.malloydata.dev/documentation/user_guides/sql_experts2), [part 3](https://docs.malloydata.dev/documentation/user_guides/sql_experts3)).\n\n### Source Code\n\nThe Malloy implementation lives at [github.com/malloydata/malloy](https://github.com/malloydata/malloy). Key entry points:\n\n| What | Where |\n|---|---|\n| ANTLR grammar (lexer + parser) | `packages/malloy/src/lang/grammar/` |\n| AST node hierarchy | `packages/malloy/src/lang/ast/` |\n| Parse tree \u2192 AST builder | `packages/malloy/src/lang/malloy-to-ast.ts` |\n| IR type definitions | `packages/malloy/src/model/malloy_types.ts` |\n| IR \u2192 SQL compiler | `packages/malloy/src/model/` |\n| Dialect-specific SQL generation | `packages/malloy/src/dialect/` |\n| Tag/annotation parsing (MOTLY) | `packages/malloy-tag/` |\n| Renderer | `packages/malloy-render/` |\n| Architecture overview | `CONTEXT.md` (root and in each package) |\n',
346
+ "language/pick.md": "---\ndescription: pick expressions \u2014 Malloy's CASE/if-then-else\n---\n\n`pick` is Malloy's equivalent of SQL `CASE WHEN`. Each branch is its own\n`pick` keyword; the `else` clause catches the remainder.\n\nThere are two forms of pick. In the first the `when` expression is any\nboolean expression.\n\n```malloy\n pick 'Female' when upper(first_name) in ('JENNIFER', 'ELIZABETH', 'AMY', 'JESSICA')\n pick 'Male' when upper(first_name) in ('JAMES', 'JOHN', 'ROBERT', 'MICHAEL')\n else 'Unknown'\n```\n\n## Example usage in a query\n\n```malloy\nrun: payments -> {\n group_by: tier is\n pick 'high' when total_amount > 10000\n pick 'medium' when total_amount > 1000\n else 'low'\n aggregate: payment_count is count()\n}\n```\n\n## Common mistakes\n\n- **Every branch needs its own `pick` keyword** \u2014 there is no `when \u2026 then`:\n ```malloy\n -- WRONG:\n pick 'a' when x = 1 'b' when x = 2 else 'c'\n\n -- RIGHT:\n pick 'a' when x = 1\n pick 'b' when x = 2\n else 'c'\n ```\n\n- **`else` is required** when the branches don't cover all cases \u2014 omitting it\n returns `null` for unmatched rows.\n",
347
+ "writing-malloy-with-mcp.md": "---\ndescription: How to write Malloy over an MCP surface \u2014 the compiler-in-the-loop discipline, common errors, and givens. Tool-agnostic; read once.\n---\n# Writing Malloy over MCP\n\nMalloy is a semantic language: a source already carries measures, dimensions,\nviews, and joins, and the compiler typechecks every query against them. The\nsingle most useful habit is **let the compiler be ground truth** \u2014 don't guess\nsyntax or field names. Read the source's shape first, validate before you run,\nand read the `problems[]` the surface returns.\n\nThe exact tools differ by surface (an explore surface exposes describe + query;\nan authoring surface adds compile/prettify), but the loop is the same:\n\n1. **Read the shape.** Describe the source you're querying \u2014 its measures,\n dimensions, views, and joins. The model usually already defines the\n aggregation you want; reuse it instead of re-deriving it.\n2. **Validate, then run.** Compile/validate the query first (no execution) to\n confirm it typechecks and to see the generated SQL or the givens it needs;\n fix any `problems[]`, then execute to get rows.\n3. **Recover from problems[].** Every failure \u2014 parse, field-not-found,\n aggregate-locality, runtime \u2014 comes back as a uniform `problems[]` with a\n `code` and (when known) a `help_topic`. Pull that topic with `yo_help`.\n\n## Common errors and how to read them\n\n- **Unknown field** \u2014 describe the source and check its dimensions / measures /\n views / joins for what actually exists. A join rendered by `source_ref` is\n described under that name in the same response.\n- **Aggregate locality** \u2014 `sum(joined.x)` across a join needs explicit\n locality: `source.sum(joined.x)` or `joined.x.sum()`.\n- **Mixed reduction / projection** \u2014 one query stage is either\n `group_by:`/`aggregate:` OR `select:`, never both.\n- **Calculation in a source** \u2014 `calculate:` (window functions) lives in\n queries, not in source definitions.\n\n## Givens (`$NAME` parameters)\n\nSome models declare given parameters (`$TENANT`, `$MAX_ROWS`, \u2026). Validate a\nquery with execution off to learn which givens it references (with their types\nand whether a default exists), then supply values keyed by surface name (no\n`$`). A given with a default is optional; one without must be supplied. For the\nper-type value shapes (dates as ISO strings, records as objects, `filter<T>` as\na Malloy filter string, \u2026) pull `yo_help(\"givens\")` \u2014 don't guess; the compiler\nvalidates and points at the offending field.\n\n## Before writing non-trivial Malloy\n\nBrowse the `language/*` topics first (start with `yo_help(\"language/overview\")`).\nThe language has real scoping and typing rules the compiler enforces \u2014 reading\nthe reference beats guessing.\n"
348
+ };
349
+ var prompts = {
350
+ "core": {
351
+ "instructions": ""
352
+ },
353
+ "develop": {
354
+ "instructions": 'You are helping someone publish a Malloy model for their data. The model will be\nserved through an MCP query tool like yours.\n\nA working model is an `index.malloy` (the published query surface) and a\n`malloy-config.json`, plus any `.malloy` files `index.malloy` imports.\nYou edit these with your file tools; the MCP tools compile, inspect, and test them.\n\nWhen interacting with a .malloy file, use the compile() or compile_file() tools,\ndon\'t read the file. The tools can both inspect and diagnose problems in a file.\n\nYou are probably doing one of these two things; read the guidance for the\nappropriate one with `yo_help`.\n\n- New model (no `index.malloy` / `malloy-config.json` yet)? -> yo_help("develop/getting-started")\n- Existing model (or setup complete) -> yo_help("develop/working-with-models")',
355
+ "tools": {
356
+ "compile": {
357
+ "description": 'Compile inline Malloy text (no file needed). Good for PROBING data: compiling `source: x is conn.sql("SELECT \u2026")` or `run: conn.sql("SELECT \u2026")` resolves and returns the schema \u2014 column names and types \u2014 without writing a file or fetching rows. Also checks a throwaway draft before it lands in a file. Same output shape as compile_file.',
358
+ "title": "Compile inline Malloy \u2014 probe data or check a draft"
359
+ },
360
+ "compile_file": {
361
+ "description": "Compile a .malloy file and return the structured model \u2014 sources, queries, runs, givens \u2014 plus problems[]. PREFER THIS over reading the file as text: reading shows syntax, compiling shows semantics.",
362
+ "title": "Compile and inspect a Malloy file"
363
+ },
364
+ "prettify": {
365
+ "description": "Reformat Malloy source to canonical form. Returns formatted text + parse problems (best-effort when problems is non-empty).",
366
+ "title": "Pretty-print Malloy source"
367
+ }
368
+ }
369
+ },
370
+ "explore": {
371
+ "guidance": 'Workflow: describe_source a source \u2014 learn its real dimensions, measures, and joins \u2014 before you query it. Validate with query(execute:false) and iterate until clean, then run with a plain-English question describing what that query answers. A successful run returns a shareable link; present results by restating the question, then the rows, then the link. Do ranking, top-N, and member selection in Malloy, not in client code. Full detail: yo_help("explore/how-to").',
372
+ "instructions": "Malloy semantic-layer analytics for {{INSTANCE_NAME}}. Start with `list_sources` or `describe_source` \u2014 every tool result carries the workflow and points you to `yo_help`.",
373
+ "tools": {
374
+ "describe_source": {
375
+ "description": "Get a source's queryable surface before writing a query: `dimensions` (its columns \u2014 scalars, records, and arrays), `measures`, `views`, the `joins` it reaches (keyed by path; `fans_out` flags paths that multiply rows), and a deduped `join_source_map` of the named sources those joins resolve to. `source` is required; `model_ref` is optional when the source name is unique across the catalog.",
376
+ "title": "Inspect a published source"
377
+ },
378
+ "list_sources": {
379
+ "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.",
380
+ "title": "List sources"
381
+ }
382
+ }
383
+ },
384
+ "shared": {
385
+ "errors": {
386
+ "no-model-ref": "No model_ref provided. Use `list_sources` to discover sources and the `model_ref` each lives in, then pass `model_ref` + `source`. (On a local develop server, `model_ref` is the path to a .malloy file, e.g. `index.malloy`.)"
387
+ },
388
+ "tools": {
389
+ "query": {
390
+ "description": "Run Malloy text against a model: `model_ref` is the model, `malloy` is the Malloy text (e.g. `run: source -> { ... }`). Set `execute:false` to validate only. Inspect the model first.",
391
+ "title": "Query a Malloy model"
392
+ },
393
+ "yo_help": {
394
+ "description": "Malloy guidance by topic: the language reference, how-to topics (setup, connections, querying), and error explanations. No topic \u2192 list topics. Use before guessing syntax and after a compile error (problems[] carry a help_topic pointer).",
395
+ "title": "Malloy reference and how-to guidance (by topic)"
396
+ }
397
+ }
398
+ }
399
+ };
400
+ function slugify(s) {
401
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
402
+ }
403
+ function nameFromKey(key) {
404
+ return key.replace(/\.md$/, "").split("/").map(slugify).join("/");
405
+ }
406
+ function parseFrontMatter(name, raw) {
407
+ const withoutProvenance = raw.replace(/^<!--[\s\S]*?-->\s*\n/, "");
408
+ const m = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(withoutProvenance);
409
+ if (!m) return { name, description: name, body: withoutProvenance };
410
+ const d = /^description:\s*(.+)$/m.exec(m[1] ?? "");
411
+ return {
412
+ name,
413
+ description: d?.[1]?.trim() ?? name,
414
+ body: m[2] ?? ""
415
+ };
416
+ }
417
+ var LANGUAGE_REFERENCE = "language/malloy-language-reference.md";
418
+ function splitReference(ns, raw, out) {
419
+ let name = `${ns}/overview`;
420
+ const bodyLines = [];
421
+ const flush = () => {
422
+ const body = bodyLines.join("\n").trim();
423
+ if (body) out.push({ name, body });
424
+ bodyLines.length = 0;
425
+ };
426
+ for (const line of raw.split("\n")) {
427
+ const m = /^## (?!# )(.+)$/.exec(line);
428
+ if (m) {
429
+ flush();
430
+ name = `${ns}/${slugify((m[1] ?? "").trim())}`;
431
+ continue;
432
+ }
433
+ if (line.startsWith("---")) continue;
434
+ if (/^<!--/.test(line) || /-->\s*$/.test(line)) continue;
435
+ bodyLines.push(line);
436
+ }
437
+ flush();
438
+ }
439
+ function buildIndex() {
440
+ const topics = [];
441
+ for (const [key, raw] of Object.entries(contentFiles)) {
442
+ if (key === LANGUAGE_REFERENCE) {
443
+ const ns = nameFromKey(key.replace(/\/[^/]+$/, ""));
444
+ splitReference(ns, raw, topics);
445
+ } else {
446
+ topics.push({ name: nameFromKey(key), body: parseFrontMatter(key, raw).body.trim() });
447
+ }
448
+ }
449
+ return topics;
450
+ }
451
+ var cachedIndex = null;
452
+ function index() {
453
+ if (!cachedIndex) cachedIndex = buildIndex();
454
+ return cachedIndex;
455
+ }
456
+ function listHelpTopics() {
457
+ return index().map((t) => t.name);
458
+ }
459
+ function getHelpTopic(query) {
460
+ const q = query.toLowerCase().trim();
461
+ const all = index();
462
+ const direct = all.find((t) => t.name === q) ?? all.find((t) => t.name.includes(q));
463
+ if (direct) return direct;
464
+ const tokens = q.split(/\s+/).filter(Boolean);
465
+ if (tokens.length === 0) return void 0;
466
+ return all.find((t) => {
467
+ const body = t.body.toLowerCase();
468
+ return tokens.every((tok) => body.includes(tok));
469
+ });
470
+ }
471
+ var ERROR_TOPIC_MAP = {
472
+ "field-not-found": "language/fields",
473
+ "aggregate-in-calculate": "language/expressions",
474
+ "not-an-aggregate": "language/fields",
475
+ "mixed-reduction-projection": "language/queries-and-views",
476
+ "calculation-in-source": "language/fields",
477
+ "missing-aggregate-locality": "language/aggregate-locality-symmetric-aggregates",
478
+ "asymmetric-aggregate-needs-locality": "language/aggregate-locality-symmetric-aggregates",
479
+ "restricted-construct-forbidden": "explore/restricted-queries"
480
+ };
481
+ function helpTopicForCode(code) {
482
+ return ERROR_TOPIC_MAP[code];
483
+ }
484
+ function engineSkills() {
485
+ const raw = contentFiles["writing-malloy-with-mcp.md"];
486
+ if (!raw) return [];
487
+ return [parseFrontMatter("writing-malloy-with-mcp", raw)];
488
+ }
489
+ function mapProblems(problems) {
490
+ return problems.map((p) => {
491
+ const out = {
492
+ severity: p.severity,
493
+ message: p.message,
494
+ code: p.code,
495
+ uri: p.at?.url,
496
+ line: p.at?.range.start.line,
497
+ column: p.at?.range.start.character,
498
+ end_line: p.at?.range.end.line,
499
+ end_column: p.at?.range.end.character
500
+ };
501
+ const topic = helpTopicForCode(p.code);
502
+ if (topic) out.help_topic = topic;
503
+ return out;
504
+ });
505
+ }
506
+ function errorProblem(e, uri) {
507
+ return {
508
+ severity: "error",
509
+ message: e instanceof Error ? e.message : String(e),
510
+ code: "internal-error",
511
+ uri
512
+ };
513
+ }
514
+ function codeProblem(code, message, uri) {
515
+ const out = { severity: "error", code, message, uri };
516
+ const topic = helpTopicForCode(code);
517
+ if (topic) out.help_topic = topic;
518
+ return out;
519
+ }
520
+ function hasError(problems) {
521
+ return problems.some((p) => p.severity === "error");
522
+ }
523
+ async function gateConfigProblems(configProblems, run2) {
524
+ if (hasError(configProblems)) {
525
+ return { ok: false, problems: configProblems };
526
+ }
527
+ const result = await run2();
528
+ if (configProblems.length === 0) return result;
529
+ const r = result;
530
+ if (Array.isArray(r.problems)) {
531
+ return { ...result, problems: [...configProblems, ...r.problems] };
532
+ }
533
+ return result;
534
+ }
535
+ function prettify(source) {
536
+ const { result, errors } = internalPrettify(source);
537
+ const problems = errors.map((e) => ({
538
+ severity: "error",
539
+ code: "parse-error",
540
+ message: e.message,
541
+ line: e.line,
542
+ column: e.column
543
+ }));
544
+ return { formatted: result, problems };
545
+ }
546
+ var RESERVED_WORDS = /* @__PURE__ */ new Set([
547
+ "all",
548
+ "and",
549
+ "as",
550
+ "asc",
551
+ "avg",
552
+ "boolean",
553
+ "by",
554
+ "case",
555
+ "cast",
556
+ "compose",
557
+ "count",
558
+ "date",
559
+ "day",
560
+ "days",
561
+ "desc",
562
+ "distinct",
563
+ "else",
564
+ "end",
565
+ "exclude",
566
+ "export",
567
+ "extend",
568
+ "false",
569
+ "filter",
570
+ "for",
571
+ "from",
572
+ "full",
573
+ "has",
574
+ "hour",
575
+ "hours",
576
+ "import",
577
+ "in",
578
+ "include",
579
+ "inner",
580
+ "internal",
581
+ "is",
582
+ "json",
583
+ "left",
584
+ "like",
585
+ "max",
586
+ "min",
587
+ "minute",
588
+ "minutes",
589
+ "month",
590
+ "months",
591
+ "not",
592
+ "now",
593
+ "null",
594
+ "number",
595
+ "on",
596
+ "or",
597
+ "pick",
598
+ "private",
599
+ "public",
600
+ "quarter",
601
+ "quarters",
602
+ "right",
603
+ "second",
604
+ "seconds",
605
+ "source",
606
+ "sql",
607
+ "string",
608
+ "sum",
609
+ "table",
610
+ "then",
611
+ "this",
612
+ "timestamp",
613
+ "timestamptz",
614
+ "to",
615
+ "true",
616
+ "virtual",
617
+ "week",
618
+ "weeks",
619
+ "when",
620
+ "with",
621
+ "year",
622
+ "years"
623
+ ]);
624
+ var BARE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
625
+ function needsQuote(name) {
626
+ return !BARE_IDENTIFIER.test(name) || RESERVED_WORDS.has(name.toLowerCase());
627
+ }
628
+ var MAX_JOIN_DEPTH = 4;
629
+ function toLoc(loc) {
630
+ if (!loc) return void 0;
631
+ return [loc.range.start.line, loc.range.start.character];
632
+ }
633
+ function annotationList(a) {
634
+ if (!a) return [];
635
+ return a.forRoute().map((n) => ({ route: n.route, text: n.content }));
636
+ }
637
+ function descriptionOf(a) {
638
+ const docs = (a?.forRoute('"') ?? []).map((n) => n.content.trim()).filter(Boolean);
639
+ return docs.length ? docs.join("\n") : void 0;
640
+ }
641
+ function agentNotesOf(a) {
642
+ const notes = (a?.forRoute("agent") ?? []).map((n) => n.content.trim()).filter(Boolean);
643
+ return notes.length ? notes.join("\n") : void 0;
644
+ }
645
+ function applyDocs(obj, a) {
646
+ const d = descriptionOf(a);
647
+ if (d) obj.description = d;
648
+ const i = agentNotesOf(a);
649
+ if (i) obj.instructions = i;
650
+ return obj;
651
+ }
652
+ function isLocal(loc, rootUri) {
653
+ return !!loc && loc.url === rootUri;
654
+ }
655
+ function sliceSource(src, loc) {
656
+ if (!src || !loc) return void 0;
657
+ const lines = src.split("\n");
658
+ const { start, end } = loc.range;
659
+ if (start.line < 0 || start.line >= lines.length) return void 0;
660
+ if (end.line < 0 || end.line >= lines.length) return void 0;
661
+ if (start.line === end.line) {
662
+ return lines[start.line]?.slice(start.character, end.character);
663
+ }
664
+ const out = [lines[start.line]?.slice(start.character) ?? ""];
665
+ for (let i = start.line + 1; i < end.line; i++) out.push(lines[i] ?? "");
666
+ out.push(lines[end.line]?.slice(0, end.character) ?? "");
667
+ return out.join("\n");
668
+ }
669
+ function joinRel(ef) {
670
+ const j = ef.structDef.join;
671
+ if (j === "many") return "one_to_many";
672
+ if (j === "cross") return "cross";
673
+ return "many_to_one";
674
+ }
675
+ function isScalarArray(parent) {
676
+ const sd = parent.structDef;
677
+ return sd.type === "array" && sd.elementTypeDef?.type !== "record_element";
678
+ }
679
+ function isRepeatedRecord(parent) {
680
+ const sd = parent.structDef;
681
+ return sd.type === "array" && sd.elementTypeDef?.type === "record_element";
682
+ }
683
+ function isAnonymousRecord(parent) {
684
+ return parent.structDef.type === "record";
685
+ }
686
+ function stripScalarArrayValue(parent, groups) {
687
+ if (!isScalarArray(parent)) return groups;
688
+ return { ...groups, dimensions: groups.dimensions.filter((f) => f.name !== "value") };
689
+ }
690
+ function fieldKind(af, structDefFields) {
691
+ const raw = structDefFields.find((x) => x.name === af.name);
692
+ const et = raw?.expressionType;
693
+ if (et && (expressionIsAggregate(et) || expressionIsAnalytic(et))) {
694
+ return "measure";
695
+ }
696
+ return "dimension";
697
+ }
698
+ function safeReferencedSource(ef) {
699
+ try {
700
+ return ef.referencedSource?.();
701
+ } catch {
702
+ return void 0;
703
+ }
704
+ }
705
+ function classifyJoinTarget(ef, knownSources) {
706
+ const refId = ef.referenceSourceID;
707
+ if (refId === void 0) return { kind: "own" };
708
+ const ref = safeReferencedSource(ef);
709
+ if (ref) {
710
+ if (knownSources.has(ref.name)) return { kind: "ref", name: ref.name };
711
+ return { kind: "own" };
712
+ }
713
+ return { kind: "anon", refId };
714
+ }
715
+ function emptyGroups() {
716
+ return { dimensions: [], measures: [], views: [], joins: [] };
717
+ }
718
+ function allocAnon(ef, refId, depth, ctx, anon) {
719
+ const existing = anon.byId.get(refId);
720
+ if (existing !== void 0) return existing;
721
+ const idx = anon.srcs.length;
722
+ anon.byId.set(refId, idx);
723
+ anon.srcs.push(void 0);
724
+ anon.srcs[idx] = buildAnonSource(ef, refId, depth, ctx, anon);
725
+ return idx;
726
+ }
727
+ function buildAnonSource(ef, refId, depth, ctx, anon) {
728
+ const structDefFields = ef.structDef.fields ?? [];
729
+ const groups = walkFields(ef.allFields, structDefFields, depth, ctx, anon);
730
+ const name = refId.split("@")[0] || ef.name;
731
+ const out = {
732
+ name,
733
+ primary_key: ef.primaryKey ?? null,
734
+ ...groups
735
+ };
736
+ applyDocs(out, ef.annotations);
737
+ if (needsQuote(name)) out.must_quote = true;
738
+ const annotations = annotationList(ef.annotations);
739
+ if (annotations.length > 0) out.annotations = annotations;
740
+ return out;
741
+ }
742
+ function walkFields(fields, structDefFields, depth, ctx, anon) {
743
+ const groups = emptyGroups();
744
+ for (const f of fields) {
745
+ const annotations = annotationList(f.annotations);
746
+ const mLoc = f.location;
747
+ const local = isLocal(mLoc, ctx.rootUri);
748
+ const loc = local ? toLoc(mLoc) : void 0;
749
+ if (f.isExploreField()) {
750
+ const ef = f;
751
+ const cls = classifyJoinTarget(ef, ctx.knownSources);
752
+ const inlineMode = ctx.opts.expand === "inline";
753
+ const join4 = { name: f.name, relationship: joinRel(ef) };
754
+ applyDocs(join4, f.annotations);
755
+ if (cls.kind === "ref") join4.source_ref = cls.name;
756
+ else if (cls.kind === "anon" && !inlineMode) {
757
+ join4.anon_src_index = allocAnon(ef, cls.refId, depth + 1, ctx, anon);
758
+ }
759
+ if (needsQuote(f.name)) join4.must_quote = true;
760
+ if (annotations.length > 0) join4.annotations = annotations;
761
+ if (loc) join4.location = loc;
762
+ const synthetic = isScalarArray(ef) || isRepeatedRecord(ef) || isAnonymousRecord(ef);
763
+ if (isScalarArray(ef)) join4.column_shape = "scalar_array";
764
+ else if (isRepeatedRecord(ef)) join4.column_shape = "record_array";
765
+ else if (isAnonymousRecord(ef)) join4.column_shape = "record";
766
+ if (!synthetic && mLoc) {
767
+ const body = sliceSource(ctx.readSource(mLoc.url), mLoc);
768
+ if (body) join4.body = body;
769
+ }
770
+ const shouldInline = inlineMode || cls.kind === "own";
771
+ if (shouldInline && depth < MAX_JOIN_DEPTH) {
772
+ const childStructFields = ef.structDef.fields ?? [];
773
+ const sub = walkFields(ef.allFields, childStructFields, depth + 1, ctx, anon);
774
+ join4.fields = stripScalarArrayValue(ef, sub);
775
+ }
776
+ groups.joins.push(join4);
777
+ continue;
778
+ }
779
+ if (f.isQueryField()) {
780
+ const view = { name: f.name };
781
+ applyDocs(view, f.annotations);
782
+ if (needsQuote(f.name)) view.must_quote = true;
783
+ if (annotations.length > 0) view.annotations = annotations;
784
+ if (loc) view.location = loc;
785
+ if (mLoc) {
786
+ const body = sliceSource(ctx.readSource(mLoc.url), mLoc);
787
+ if (body) view.body = body;
788
+ }
789
+ groups.views.push(view);
790
+ continue;
791
+ }
792
+ const af = f;
793
+ const info = { name: f.name, type: af.type };
794
+ applyDocs(info, f.annotations);
795
+ if (needsQuote(f.name)) info.must_quote = true;
796
+ const raw = structDefFields.find((x) => x.name === f.name);
797
+ const expr = raw?.code?.trim() || void 0;
798
+ if (expr && expr !== f.name) info.expression = expr;
799
+ if (annotations.length > 0) info.annotations = annotations;
800
+ if (loc) info.location = loc;
801
+ if (fieldKind(af, structDefFields) === "measure") groups.measures.push(info);
802
+ else groups.dimensions.push(info);
803
+ }
804
+ return groups;
805
+ }
806
+ function walkExplore(e, ctx) {
807
+ const structDefFields = e.structDef.fields ?? [];
808
+ const anon = { byId: /* @__PURE__ */ new Map(), srcs: [] };
809
+ const groups = walkFields(e.allFields, structDefFields, 0, ctx, anon);
810
+ const annotations = annotationList(e.annotations);
811
+ const out = {
812
+ name: e.name,
813
+ primary_key: e.primaryKey ?? null,
814
+ ...groups
815
+ };
816
+ applyDocs(out, e.annotations);
817
+ if (needsQuote(e.name)) out.must_quote = true;
818
+ if (annotations.length > 0) out.annotations = annotations;
819
+ const mLoc = e.location;
820
+ if (isLocal(mLoc, ctx.rootUri)) {
821
+ const loc = toLoc(mLoc);
822
+ if (loc) out.location = loc;
823
+ }
824
+ if (mLoc) {
825
+ const body = sliceSource(ctx.readSource(mLoc.url), mLoc);
826
+ if (body) out.body = body;
827
+ }
828
+ if (anon.srcs.length > 0) out.anon_srcs = anon.srcs;
829
+ return out;
830
+ }
831
+ function renderGivenType(t) {
832
+ if (t.type === "filter expression") {
833
+ return t.filterType ? `filter<${t.filterType}>` : "filter";
834
+ }
835
+ if (t.type === "array") {
836
+ const elem = t.elementTypeDef;
837
+ if (!elem) return "array";
838
+ if (elem.type === "record_element") return "record[]";
839
+ return `${renderGivenType(elem)}[]`;
840
+ }
841
+ return t.type;
842
+ }
843
+ function describeGiven(g, surfaceName, ctx) {
844
+ const annotations = annotationList(g.annotations);
845
+ const info = {
846
+ name: surfaceName,
847
+ type: renderGivenType(g.type),
848
+ has_default: g.default !== void 0
849
+ };
850
+ applyDocs(info, g.annotations);
851
+ if (annotations.length > 0) info.annotations = annotations;
852
+ const loc = g.location;
853
+ if (ctx && loc) {
854
+ if (isLocal(loc, ctx.rootUri)) {
855
+ const l = toLoc(loc);
856
+ if (l) info.location = l;
857
+ }
858
+ const body = sliceSource(ctx.readSource(loc.url), loc);
859
+ if (body) info.body = body;
860
+ }
861
+ return info;
862
+ }
863
+ function readQueryGivens(getPq) {
864
+ try {
865
+ return [...getPq().givens.keys()];
866
+ } catch {
867
+ return [];
868
+ }
869
+ }
870
+ function walkModel(model, rootUri, opts, readSource) {
871
+ const modelQueries = model.queries();
872
+ const topLevel = (opts.exportedOnly ? model.exportedExplores : void 0) ?? model.explores;
873
+ const knownSources = /* @__PURE__ */ new Set([
874
+ ...topLevel.map((e) => e.name),
875
+ ...modelQueries.named
876
+ ]);
877
+ const ctx = { rootUri, knownSources, opts, readSource };
878
+ const sources = {};
879
+ for (const e of topLevel) {
880
+ sources[e.name] = walkExplore(e, ctx);
881
+ }
882
+ const queries = [];
883
+ for (const queryName of modelQueries.named) {
884
+ const pq = model.getPreparedQueryByName(queryName);
885
+ const annotations = annotationList(pq.annotations);
886
+ const info = { name: queryName };
887
+ applyDocs(info, pq.annotations);
888
+ if (needsQuote(queryName)) info.must_quote = true;
889
+ if (annotations.length > 0) info.annotations = annotations;
890
+ const loc = pq.location;
891
+ if (isLocal(loc, rootUri)) {
892
+ const l = toLoc(loc);
893
+ if (l) info.location = l;
894
+ }
895
+ if (loc) {
896
+ const body = sliceSource(readSource(loc.url), loc);
897
+ if (body) info.body = body;
898
+ }
899
+ const givenNames = readQueryGivens(() => pq);
900
+ if (givenNames.length > 0) info.givens = givenNames;
901
+ queries.push(info);
902
+ }
903
+ const runs = [];
904
+ for (let idx = 0; idx < modelQueries.unnamed; idx++) {
905
+ const pq = model.getPreparedQueryByIndex(idx);
906
+ const info = { index: idx };
907
+ const annotations = annotationList(pq.annotations);
908
+ if (annotations.length > 0) info.annotations = annotations;
909
+ const l = toLoc(pq.location);
910
+ if (l) info.location = l;
911
+ try {
912
+ const givenNames = [...pq.givens.keys()];
913
+ if (givenNames.length > 0) info.givens = givenNames;
914
+ if (opts.emitRunSql) info.sql = pq.preparedResult.sql.trim();
915
+ } catch (e) {
916
+ if (opts.emitRunSql) info.error = e instanceof Error ? e.message : String(e);
917
+ }
918
+ runs.push(info);
919
+ }
920
+ const out = { entry: rootUri, sources, queries, runs };
921
+ const modelAnnotations = annotationList(model.annotations);
922
+ if (modelAnnotations.length > 0) out.annotations = modelAnnotations;
923
+ const givens = [];
924
+ for (const [surfaceName, g] of model.givens) {
925
+ givens.push(describeGiven(
926
+ g,
927
+ surfaceName,
928
+ { rootUri, readSource }
929
+ ));
930
+ }
931
+ if (givens.length > 0) out.givens = givens;
932
+ return out;
933
+ }
934
+ function isCanonicalForm(source) {
935
+ const { formatted, problems } = prettify(source);
936
+ if (problems.length > 0) return void 0;
937
+ const norm = (s) => s.replace(/\r\n/g, "\n").trimEnd();
938
+ return norm(formatted) === norm(source);
939
+ }
940
+ async function compile(runtime, entry, opts = {}) {
941
+ const readSource = opts.readSource ?? (() => void 0);
942
+ try {
943
+ const model = await runtime.loadModel(entry).getModel();
944
+ try {
945
+ const info = walkModel(model, entry.href, {
946
+ expand: opts.expand ?? "ref",
947
+ emitRunSql: opts.emitRunSql ?? false,
948
+ exportedOnly: opts.exportedOnly ?? false,
949
+ readSource
950
+ }, readSource);
951
+ const out = {
952
+ ok: true,
953
+ model: info,
954
+ problems: mapProblems(model.problems)
955
+ };
956
+ const entryText = readSource(entry.href);
957
+ if (entryText !== void 0) {
958
+ const canonical = isCanonicalForm(entryText);
959
+ if (canonical !== void 0) out.formatted = canonical;
960
+ }
961
+ return out;
962
+ } catch (e) {
963
+ return { ok: false, problems: [...mapProblems(model.problems), errorProblem(e, entry.href)] };
964
+ }
965
+ } catch (e) {
966
+ if (e instanceof MalloyError) {
967
+ return { ok: false, problems: mapProblems(e.problems) };
968
+ }
969
+ return { ok: false, problems: [errorProblem(e, entry.href)] };
970
+ }
971
+ }
972
+ var EMPTY_GROUPS = { dimensions: [], measures: [], views: [], joins: [] };
973
+ var seg = (m) => m.must_quote ? `\`${m.name}\`` : m.name;
974
+ var barePath = (prefix, j) => prefix ? `${prefix}.${j.name}` : j.name;
975
+ function joinCode(j) {
976
+ if (!j.body) return void 0;
977
+ const kw = j.relationship === "one_to_many" ? "join_many" : j.relationship === "cross" ? "join_cross" : "join_one";
978
+ return `${kw}: ${j.body}`;
979
+ }
980
+ function fieldDescriptor(f) {
981
+ const d = { type: f.type };
982
+ if (f.must_quote) d.must_quote = true;
983
+ if (f.expression) d.expression = f.expression;
984
+ if (f.description) d.description = f.description;
985
+ if (f.instructions) d.instructions = f.instructions;
986
+ return d;
987
+ }
988
+ function buildColumns(groups, pathPrefix) {
989
+ const out = /* @__PURE__ */ Object.create(null);
990
+ for (const f of groups.dimensions) out[f.name] = fieldDescriptor(f);
991
+ for (const j of groups.joins) {
992
+ if (j.column_shape === "record") {
993
+ const childPath = pathPrefix === null ? null : barePath(pathPrefix, j);
994
+ const rec = { type: buildColumns(j.fields ?? EMPTY_GROUPS, childPath) };
995
+ if (j.must_quote) rec.must_quote = true;
996
+ if (j.description) rec.description = j.description;
997
+ if (j.instructions) rec.instructions = j.instructions;
998
+ out[j.name] = rec;
999
+ } else if (j.column_shape === "scalar_array" || j.column_shape === "record_array") {
1000
+ const stub = { is_array: true, fans_out: true };
1001
+ if (pathPrefix !== null) stub.path = barePath(pathPrefix, j);
1002
+ if (j.must_quote) stub.must_quote = true;
1003
+ out[j.name] = stub;
1004
+ }
1005
+ }
1006
+ return out;
1007
+ }
1008
+ function measuresMap(measures) {
1009
+ const out = /* @__PURE__ */ Object.create(null);
1010
+ for (const m of measures) out[m.name] = fieldDescriptor(m);
1011
+ return out;
1012
+ }
1013
+ function buildSchema(groups, pathPrefix, meta) {
1014
+ const s = {};
1015
+ if (meta?.primary_key) s.primary_key = meta.primary_key;
1016
+ if (meta?.description) s.description = meta.description;
1017
+ if (meta?.instructions) s.instructions = meta.instructions;
1018
+ s.dimensions = buildColumns(groups, pathPrefix);
1019
+ s.measures = measuresMap(groups.measures);
1020
+ return s;
1021
+ }
1022
+ function viewsMap(views) {
1023
+ const out = /* @__PURE__ */ Object.create(null);
1024
+ for (const v of views) out[seg(v)] = v.description ?? null;
1025
+ return out;
1026
+ }
1027
+ function emitJoins(groups, anonScope, bare, quoted, fans, namedOnPath, anonOnPath, ctx) {
1028
+ for (const j of groups.joins) {
1029
+ const cBare = barePath(bare, j);
1030
+ const cQuoted = quoted ? `${quoted}.${seg(j)}` : seg(j);
1031
+ if (j.column_shape === "record") {
1032
+ emitJoins(j.fields ?? EMPTY_GROUPS, anonScope, cBare, cQuoted, fans, namedOnPath, anonOnPath, ctx);
1033
+ } else if (j.column_shape === "scalar_array" || j.column_shape === "record_array") {
1034
+ emitArray(j, cBare, cQuoted, anonScope, namedOnPath, anonOnPath, ctx);
1035
+ } else {
1036
+ emitSourceJoin(j, cBare, cQuoted, anonScope, fans, namedOnPath, anonOnPath, ctx);
1037
+ }
1038
+ }
1039
+ }
1040
+ function withQuoted(entry, bare, quoted) {
1041
+ if (quoted !== bare) entry.quoted_path = quoted;
1042
+ return entry;
1043
+ }
1044
+ function emitArray(j, bare, quoted, anonScope, namedOnPath, anonOnPath, ctx) {
1045
+ const fields = j.fields ?? EMPTY_GROUPS;
1046
+ ctx.joins[bare] = withQuoted({ is_array: true, fans_out: true, source_def: buildSchema(fields, bare) }, bare, quoted);
1047
+ emitJoins(fields, anonScope, bare, quoted, true, namedOnPath, anonOnPath, ctx);
1048
+ }
1049
+ function emitSourceJoin(j, bare, quoted, anonScope, fans, namedOnPath, anonOnPath, ctx) {
1050
+ const entryFans = fans || j.relationship !== "many_to_one";
1051
+ const entry = {};
1052
+ if (entryFans) entry.fans_out = true;
1053
+ withQuoted(entry, bare, quoted);
1054
+ if (j.source_ref) {
1055
+ entry.source = j.source_ref;
1056
+ const namedCode = joinCode(j);
1057
+ if (namedCode) entry.code = namedCode;
1058
+ const target = ctx.model.sources[j.source_ref];
1059
+ if (target && !(j.source_ref in ctx.map)) {
1060
+ ctx.map[j.source_ref] = buildSchema(target, null, target);
1061
+ }
1062
+ if (namedOnPath.has(j.source_ref)) {
1063
+ entry.cycle = true;
1064
+ ctx.joins[bare] = entry;
1065
+ return;
1066
+ }
1067
+ ctx.joins[bare] = entry;
1068
+ if (target) {
1069
+ emitJoins(
1070
+ target,
1071
+ target.anon_srcs ?? [],
1072
+ bare,
1073
+ quoted,
1074
+ entryFans,
1075
+ /* @__PURE__ */ new Set([...namedOnPath, j.source_ref]),
1076
+ /* @__PURE__ */ new Set(),
1077
+ ctx
1078
+ );
1079
+ }
1080
+ return;
1081
+ }
1082
+ let fields;
1083
+ let meta;
1084
+ let anonIdx;
1085
+ if (j.anon_src_index !== void 0) {
1086
+ anonIdx = j.anon_src_index;
1087
+ const a = anonScope[anonIdx];
1088
+ if (a) {
1089
+ fields = a;
1090
+ meta = a;
1091
+ }
1092
+ } else if (j.fields) {
1093
+ fields = j.fields;
1094
+ meta = { description: j.description, instructions: j.instructions };
1095
+ }
1096
+ if (fields) entry.source_def = buildSchema(fields, bare, meta);
1097
+ const anonCode = joinCode(j);
1098
+ if (anonCode) entry.code = anonCode;
1099
+ if (anonIdx !== void 0 && anonOnPath.has(anonIdx)) {
1100
+ entry.cycle = true;
1101
+ ctx.joins[bare] = entry;
1102
+ return;
1103
+ }
1104
+ ctx.joins[bare] = entry;
1105
+ if (fields) {
1106
+ emitJoins(
1107
+ fields,
1108
+ anonScope,
1109
+ bare,
1110
+ quoted,
1111
+ entryFans,
1112
+ namedOnPath,
1113
+ anonIdx !== void 0 ? /* @__PURE__ */ new Set([...anonOnPath, anonIdx]) : anonOnPath,
1114
+ ctx
1115
+ );
1116
+ }
1117
+ }
1118
+ function buildSourceDescribe(model, name) {
1119
+ const root = model.sources[name];
1120
+ if (!root) return void 0;
1121
+ const ctx = { model, joins: /* @__PURE__ */ Object.create(null), map: /* @__PURE__ */ Object.create(null) };
1122
+ const described_source = {
1123
+ name,
1124
+ ...buildSchema(root, "", root),
1125
+ views: viewsMap(root.views)
1126
+ };
1127
+ emitJoins(root, root.anon_srcs ?? [], "", "", false, /* @__PURE__ */ new Set([name]), /* @__PURE__ */ new Set(), ctx);
1128
+ return { described_source, joins: ctx.joins, join_source_map: ctx.map };
1129
+ }
1130
+ function sourceEntryOf(s) {
1131
+ const e = { source_ref: s.name };
1132
+ if (s.description) e.description = s.description;
1133
+ if (s.instructions) e.instructions = s.instructions;
1134
+ if (s.must_quote) e.must_quote = true;
1135
+ return e;
1136
+ }
1137
+ function modelCatalogEntry(model_ref, model) {
1138
+ const entry = { model_ref };
1139
+ const sources = Object.values(model.sources).map(sourceEntryOf);
1140
+ if (sources.length) entry.sources = sources;
1141
+ return entry;
1142
+ }
1143
+ var DEFAULT_ROW_LIMIT = 1e4;
1144
+ async function executeMaterialized(query, opts, loadProblems, decorate = (p) => p, uri) {
1145
+ const rowLimit = opts.rowLimit ?? DEFAULT_ROW_LIMIT;
1146
+ const retry = opts.retry ?? ((op) => op());
1147
+ const compileOpts = opts.givens ? { givens: opts.givens } : void 0;
1148
+ try {
1149
+ const t0 = Date.now();
1150
+ const sql = (await query.getSQL(compileOpts)).trim();
1151
+ const t1 = Date.now();
1152
+ const results = await retry(() => query.run({ rowLimit, ...compileOpts }));
1153
+ const t2 = Date.now();
1154
+ const rows = results.toJSON().queryResult.result;
1155
+ const out = {
1156
+ ok: true,
1157
+ sql,
1158
+ rows,
1159
+ row_count: rows.length,
1160
+ rows_returned: rows.length,
1161
+ compile_time_ms: t1 - t0,
1162
+ total_time_ms: t2 - t0,
1163
+ problems: loadProblems
1164
+ };
1165
+ if (rows.length === rowLimit) {
1166
+ out.truncated = {
1167
+ reason: "row_limit",
1168
+ hint: `Result hit the ${rowLimit}-row limit; more rows may exist. Aggregate, filter, or do top-N in Malloy rather than fetching rows to post-process.`
1169
+ };
1170
+ }
1171
+ if (opts.stableResult) out.stable_result = API.util.wrapResult(results);
1172
+ return out;
1173
+ } catch (e) {
1174
+ if (e instanceof MalloyError2) {
1175
+ return { ok: false, problems: [...loadProblems, ...mapProblems(e.problems).map(decorate)] };
1176
+ }
1177
+ return { ok: false, problems: [...loadProblems, errorProblem(e, uri)] };
1178
+ }
1179
+ }
1180
+ async function queryGivens(q) {
1181
+ try {
1182
+ const pq = await q.getPreparedQuery();
1183
+ const out = [];
1184
+ for (const [name, g] of pq.givens) {
1185
+ out.push(describeGiven(g, name));
1186
+ }
1187
+ return out.length > 0 ? out : void 0;
1188
+ } catch {
1189
+ return void 0;
1190
+ }
1191
+ }
1192
+ async function validateRestricted(runtime, entry, query) {
1193
+ let loadProblems;
1194
+ let materializer;
1195
+ try {
1196
+ materializer = runtime.loadModel(entry);
1197
+ const model = await materializer.getModel();
1198
+ loadProblems = mapProblems(model.problems);
1199
+ } catch (e) {
1200
+ if (e instanceof MalloyError3) {
1201
+ return { ok: false, problems: mapProblems(e.problems) };
1202
+ }
1203
+ return { ok: false, problems: [errorProblem(e, entry.href)] };
1204
+ }
1205
+ try {
1206
+ const q = materializer.loadRestrictedQuery(query);
1207
+ const problems = [...loadProblems, ...mapProblems(await q.validate())];
1208
+ const ok = !hasError(problems);
1209
+ const out = { ok, problems };
1210
+ if (ok) {
1211
+ try {
1212
+ out.sql = (await q.getSQL()).trim();
1213
+ } catch {
1214
+ }
1215
+ const givens = await queryGivens(q);
1216
+ if (givens) out.givens = givens;
1217
+ }
1218
+ return out;
1219
+ } catch (e) {
1220
+ if (e instanceof MalloyError3) {
1221
+ return { ok: false, problems: [...loadProblems, ...mapProblems(e.problems)] };
1222
+ }
1223
+ return { ok: false, problems: [...loadProblems, errorProblem(e, entry.href)] };
1224
+ }
1225
+ }
1226
+ async function runRestricted(runtime, entry, query, opts = {}) {
1227
+ let loadProblems;
1228
+ let materializer;
1229
+ try {
1230
+ materializer = runtime.loadModel(entry);
1231
+ const model = await materializer.getModel();
1232
+ loadProblems = mapProblems(model.problems);
1233
+ } catch (e) {
1234
+ if (e instanceof MalloyError3) {
1235
+ return { ok: false, problems: mapProblems(e.problems) };
1236
+ }
1237
+ return { ok: false, problems: [errorProblem(e, entry.href)] };
1238
+ }
1239
+ try {
1240
+ const q = materializer.loadRestrictedQuery(query);
1241
+ return await executeMaterialized(q, opts, loadProblems, (p) => p, entry.href);
1242
+ } catch (e) {
1243
+ if (e instanceof MalloyError3) {
1244
+ return { ok: false, problems: [...loadProblems, ...mapProblems(e.problems)] };
1245
+ }
1246
+ return { ok: false, problems: [...loadProblems, errorProblem(e, entry.href)] };
1247
+ }
1248
+ }
1249
+ var INSTANCE_PLACEHOLDER = "{{INSTANCE_NAME}}";
1250
+ function renderInstructions(text, instanceName) {
1251
+ return text.replaceAll(INSTANCE_PLACEHOLDER, instanceName);
1252
+ }
1253
+ var VIRTUAL_BASE = "memory://mcp-engine/";
1254
+ function normalizeUrl2(u) {
1255
+ if (u.includes("://")) return new URL(u);
1256
+ return url.pathToFileURL(path.resolve(u));
1257
+ }
1258
+ function inlineVirtualUrl(baseUrl) {
1259
+ if (baseUrl) return new URL("__inline__.malloy", normalizeUrl2(baseUrl));
1260
+ return new URL(VIRTUAL_BASE + "__inline__.malloy");
1261
+ }
1262
+ function prepareSource(base, input) {
1263
+ const inline = "source" in input;
1264
+ const entry = inline ? inlineVirtualUrl(input.baseUrl) : normalizeUrl2(input.url);
1265
+ const cache = /* @__PURE__ */ new Map();
1266
+ if (inline) cache.set(entry.href, input.source);
1267
+ const reader = {
1268
+ readURL: async (u) => {
1269
+ const cached = cache.get(u.href);
1270
+ if (cached !== void 0) return cached;
1271
+ const text = await base.readURL(u);
1272
+ const str = typeof text === "string" ? text : String(text);
1273
+ cache.set(u.href, str);
1274
+ return str;
1275
+ }
1276
+ };
1277
+ return { reader, entry, readSource: (href) => cache.get(href) };
1278
+ }
1279
+ var DEFAULT_RESULT_BYTES = 25e3;
1280
+ function argString(args, key) {
1281
+ const v = args[key];
1282
+ return v === void 0 || v === null ? "" : String(v);
1283
+ }
1284
+ function argOptString(args, key) {
1285
+ const v = args[key];
1286
+ return v === void 0 || v === null || v === "" ? void 0 : String(v);
1287
+ }
1288
+ function argOptNumber(args, key) {
1289
+ const v = args[key];
1290
+ if (v === void 0 || v === null) return void 0;
1291
+ const n = Number(v);
1292
+ return Number.isFinite(n) ? n : void 0;
1293
+ }
1294
+ function argOptBool(args, key) {
1295
+ const v = args[key];
1296
+ if (v === void 0 || v === null) return void 0;
1297
+ return v === true || v === "true";
1298
+ }
1299
+ function argRecord(args, key) {
1300
+ const v = args[key];
1301
+ if (v && typeof v === "object" && !Array.isArray(v)) {
1302
+ return v;
1303
+ }
1304
+ return void 0;
1305
+ }
1306
+ function yoHelpTool() {
1307
+ return {
1308
+ name: "yo_help",
1309
+ title: prompts.shared.tools.yo_help.title,
1310
+ description: prompts.shared.tools.yo_help.description,
1311
+ inputSchema: {
1312
+ type: "object",
1313
+ properties: {
1314
+ topic: {
1315
+ type: "string",
1316
+ description: 'A topic name from the index, e.g. "explore/how-to" or "language/joins" (case-insensitive). Omit to list all topic names.'
1317
+ }
1318
+ },
1319
+ additionalProperties: false
1320
+ },
1321
+ handler: async (args) => {
1322
+ const topic = argOptString(args, "topic");
1323
+ if (!topic) return { topics: listHelpTopics() };
1324
+ const hit = getHelpTopic(topic);
1325
+ if (!hit) {
1326
+ return { error: `No topic matches '${topic}'.`, topics: listHelpTopics() };
1327
+ }
1328
+ return { name: hit.name, body: hit.body };
1329
+ }
1330
+ };
1331
+ }
1332
+ function sharedSkills() {
1333
+ return engineSkills();
1334
+ }
1335
+ function attachHelp(result) {
1336
+ const problems = result.problems;
1337
+ if (!Array.isArray(problems) || problems.length === 0) return result;
1338
+ const help = [];
1339
+ const seen = /* @__PURE__ */ new Set();
1340
+ for (const p of problems) {
1341
+ if (!p.help_topic || seen.has(p.help_topic)) continue;
1342
+ seen.add(p.help_topic);
1343
+ const hit = getHelpTopic(p.help_topic);
1344
+ if (hit) help.push(hit);
1345
+ }
1346
+ return help.length ? { ...result, help } : result;
1347
+ }
1348
+ function withHelp(tool) {
1349
+ return { ...tool, handler: async (args) => attachHelp(await tool.handler(args)) };
1350
+ }
1351
+ var REFINE_HINT = "Aggregate, filter, or do top-N in Malloy rather than fetching rows to post-process; select fewer columns if rows are wide.";
1352
+ function fittingPrefix(rows, maxBytes) {
1353
+ let bytes = 2;
1354
+ for (let i = 0; i < rows.length; i++) {
1355
+ const rowBytes = Buffer.byteLength(JSON.stringify(rows[i]) ?? "null", "utf8");
1356
+ if (bytes + rowBytes + 1 > maxBytes) return i;
1357
+ bytes += rowBytes + 1;
1358
+ }
1359
+ return rows.length;
1360
+ }
1361
+ async function applyResultBudget(full, policy, ctx) {
1362
+ const { stable_result, ...wire } = full;
1363
+ if (!wire.ok || !wire.rows) return wire;
1364
+ const maxBytes = policy?.maxResultBytes ?? DEFAULT_RESULT_BYTES;
1365
+ const keep = fittingPrefix(wire.rows, maxBytes);
1366
+ if (keep >= wire.rows.length) return wire;
1367
+ let fullResultUri;
1368
+ if (policy?.spill) {
1369
+ try {
1370
+ fullResultUri = (await policy.spill(full, ctx))?.uri;
1371
+ } catch {
1372
+ }
1373
+ }
1374
+ const out = {
1375
+ ...wire,
1376
+ rows: wire.rows.slice(0, keep),
1377
+ rows_returned: keep,
1378
+ truncated: {
1379
+ reason: "byte_budget",
1380
+ hint: keep === 0 ? "A single row exceeds the response byte budget \u2014 project fewer columns or un-nest the result. " + REFINE_HINT : `Result truncated to ${keep} of ${wire.row_count} rows to fit the response byte budget. ` + REFINE_HINT,
1381
+ ...fullResultUri ? { full_result: fullResultUri } : {}
1382
+ }
1383
+ };
1384
+ return out;
1385
+ }
1386
+ var guidance = {
1387
+ core: prompts.core.instructions,
1388
+ develop: prompts.develop.instructions,
1389
+ explore: prompts.explore.instructions
1390
+ };
1391
+ function assembleInstructions(kind) {
1392
+ const surface = kind === "develop" ? guidance.develop : guidance.explore;
1393
+ return [surface, guidance.core].filter(Boolean).join("\n\n");
1394
+ }
1395
+ function refModelProblem(ref, e) {
1396
+ const msg = e instanceof Error ? e.message : String(e);
1397
+ return codeProblem("model-not-found", `Cannot use model '${ref}': ${msg}`);
1398
+ }
1399
+ async function executeQuery(m, args, fix, result) {
1400
+ const malloy = argString(args, "malloy");
1401
+ const execute = argOptBool(args, "execute") ?? true;
1402
+ const givens = argRecord(args, "givens");
1403
+ const rowLimit = Math.max(1, Math.min(1e4, argOptNumber(args, "max_rows") ?? DEFAULT_ROW_LIMIT));
1404
+ if (!execute) {
1405
+ const v = await validateRestricted(m.runtime, m.entry, malloy);
1406
+ return { ...v, problems: v.problems.map(fix) };
1407
+ }
1408
+ const full = await runRestricted(m.runtime, m.entry, malloy, { rowLimit, givens });
1409
+ const budgeted = await applyResultBudget(full, result, { toolName: "query", args });
1410
+ return { ...budgeted, problems: budgeted.problems.map(fix) };
1411
+ }
1412
+ async function resolveModel(host, source, modelRef) {
1413
+ if (modelRef) return { model_ref: modelRef };
1414
+ if (!host.list) {
1415
+ return {
1416
+ problem: codeProblem(
1417
+ "model-ref-required",
1418
+ "Pass model_ref + source. Use list_sources to see which model a source lives in."
1419
+ )
1420
+ };
1421
+ }
1422
+ const entries = (await host.list()).entries;
1423
+ const hits = entries.filter((e) => e.sources?.some((s) => s.source_ref === source));
1424
+ if (hits.length === 1) return { model_ref: hits[0].model_ref };
1425
+ if (hits.length === 0) {
1426
+ return {
1427
+ problem: codeProblem(
1428
+ "source-not-found",
1429
+ `No exported source named '${source}' in any model you can see. Call list_sources, or pass model_ref if it is an internal source.`
1430
+ )
1431
+ };
1432
+ }
1433
+ return {
1434
+ problem: codeProblem(
1435
+ "source-ambiguous",
1436
+ `Source '${source}' exists in more than one model: ${hits.map((h) => h.model_ref).join(", ")}. Pass model_ref to pick one.`
1437
+ )
1438
+ };
1439
+ }
1440
+ function srcNudge(modelRef, source) {
1441
+ return (p) => {
1442
+ if (p.code !== "field-not-found") return p;
1443
+ return {
1444
+ ...p,
1445
+ message: `${p.message} \u2014 call describe_source with source="${source}"` + (modelRef ? ` model_ref="${modelRef}"` : "") + " to see what fields, measures, views, and joins exist.",
1446
+ help_topic: p.help_topic ?? "language/fields"
1447
+ };
1448
+ };
1449
+ }
1450
+ function sourceAsMalloy(s) {
1451
+ return s?.body ? `source: ${s.body}` : "";
1452
+ }
1453
+ function listSourcesTool(host) {
1454
+ return {
1455
+ name: "list_sources",
1456
+ title: prompts.explore.tools.list_sources.title,
1457
+ description: prompts.explore.tools.list_sources.description,
1458
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1459
+ handler: async () => {
1460
+ const { entries } = await host.list();
1461
+ const models = /* @__PURE__ */ Object.create(null);
1462
+ for (const e of entries) {
1463
+ const m = {};
1464
+ if (e.description) m.description = e.description;
1465
+ if (e.instructions) m.instructions = e.instructions;
1466
+ if (e.sources?.length) {
1467
+ const sources = /* @__PURE__ */ Object.create(null);
1468
+ for (const s of e.sources) {
1469
+ const o = {};
1470
+ if (s.description) o.description = s.description;
1471
+ if (s.instructions) o.instructions = s.instructions;
1472
+ if (s.must_quote) o.must_quote = true;
1473
+ sources[s.source_ref] = o;
1474
+ }
1475
+ m.sources = sources;
1476
+ }
1477
+ models[e.model_ref] = m;
1478
+ }
1479
+ return { ok: true, guidance: prompts.explore.guidance, models };
1480
+ }
1481
+ };
1482
+ }
1483
+ function describeSourceTool(host) {
1484
+ return {
1485
+ name: "describe_source",
1486
+ title: prompts.explore.tools.describe_source.title,
1487
+ description: prompts.explore.tools.describe_source.description,
1488
+ inputSchema: {
1489
+ type: "object",
1490
+ properties: {
1491
+ source: { type: "string", description: "The source to describe (a source the model publishes)." },
1492
+ model_ref: {
1493
+ type: "string",
1494
+ description: "The model the source lives in (the model_ref from list_sources). Optional when the source name is unique across the catalog."
1495
+ }
1496
+ },
1497
+ required: ["source"],
1498
+ additionalProperties: false
1499
+ },
1500
+ handler: async (args) => {
1501
+ const source = argString(args, "source");
1502
+ const modelRefArg = argOptString(args, "model_ref");
1503
+ if (!source.trim()) {
1504
+ return {
1505
+ ok: false,
1506
+ model_ref: modelRefArg ?? "",
1507
+ source,
1508
+ problems: [codeProblem("source-required", "A source name is required. Use list_sources to see them.")]
1509
+ };
1510
+ }
1511
+ const r = await resolveModel(host, source, modelRefArg);
1512
+ if ("problem" in r) {
1513
+ return { ok: false, model_ref: modelRefArg ?? "", source, problems: [r.problem] };
1514
+ }
1515
+ const modelRef = r.model_ref;
1516
+ try {
1517
+ return await host.withModel(modelRef, async (m) => {
1518
+ const compiled = await compile(m.runtime, m.entry, { readSource: m.readSource });
1519
+ if (!compiled.ok || !compiled.model) {
1520
+ return { ok: false, model_ref: modelRef, source, problems: compiled.problems };
1521
+ }
1522
+ const built = buildSourceDescribe(compiled.model, source);
1523
+ if (!built) {
1524
+ const available = Object.keys(compiled.model.sources);
1525
+ return {
1526
+ ok: false,
1527
+ model_ref: modelRef,
1528
+ source,
1529
+ problems: [
1530
+ ...compiled.problems,
1531
+ codeProblem(
1532
+ "source-not-found",
1533
+ `No source named '${source}' in '${modelRef}'. Sources: ${available.join(", ") || "(none)"}.`
1534
+ )
1535
+ ]
1536
+ };
1537
+ }
1538
+ const malloy_text = sourceAsMalloy(compiled.model.sources[source]);
1539
+ const base = {
1540
+ ok: true,
1541
+ model_ref: modelRef,
1542
+ source,
1543
+ guidance: prompts.explore.guidance,
1544
+ described_source: built.described_source,
1545
+ problems: compiled.problems
1546
+ };
1547
+ if (Object.keys(built.joins).length) base.joins = built.joins;
1548
+ if (Object.keys(built.join_source_map).length) base.join_source_map = built.join_source_map;
1549
+ return malloy_text ? { ...base, malloy_text } : base;
1550
+ });
1551
+ } catch (e) {
1552
+ return { ok: false, model_ref: modelRef, source, problems: [refModelProblem(modelRef, e)] };
1553
+ }
1554
+ }
1555
+ };
1556
+ }
1557
+ function exploreQueryTool(host, opts) {
1558
+ return {
1559
+ name: "query",
1560
+ title: prompts.shared.tools.query.title,
1561
+ description: prompts.shared.tools.query.description,
1562
+ inputSchema: {
1563
+ type: "object",
1564
+ properties: {
1565
+ source: { type: "string", description: "The source the query runs against." },
1566
+ malloy: { type: "string", description: "Malloy query text, e.g. `run: orders -> { ... }`." },
1567
+ model_ref: {
1568
+ type: "string",
1569
+ description: "The model the source lives in (optional when the source name is unique)."
1570
+ },
1571
+ question: {
1572
+ type: "string",
1573
+ description: "Plain-English description of what this query answers; hosts may record or share it."
1574
+ },
1575
+ givens: {
1576
+ type: "object",
1577
+ description: "Values for $NAME givens, keyed by name (no $). Discover which a query needs with execute:false."
1578
+ },
1579
+ execute: {
1580
+ type: "boolean",
1581
+ description: "Default true. false \u2192 compile/validate only (returns SQL + the givens the query references)."
1582
+ },
1583
+ max_rows: { type: "integer", minimum: 1, maximum: 1e4, description: `Row cap (default ${DEFAULT_ROW_LIMIT}).` }
1584
+ },
1585
+ required: ["source", "malloy"],
1586
+ additionalProperties: false
1587
+ },
1588
+ handler: async (args) => {
1589
+ const source = argString(args, "source");
1590
+ const modelRefArg = argOptString(args, "model_ref");
1591
+ const execute = argOptBool(args, "execute") ?? true;
1592
+ const r = await resolveModel(host, source, modelRefArg);
1593
+ if ("problem" in r) return { ok: false, problems: [r.problem] };
1594
+ const modelRef = r.model_ref;
1595
+ if (modelRefArg && host.list) {
1596
+ const entries = (await host.list()).entries;
1597
+ const here = entries.find((e) => e.model_ref === modelRef);
1598
+ const inModel = here?.sources?.some((s) => s.source_ref === source) ?? false;
1599
+ const elsewhere = entries.filter((e) => e.model_ref !== modelRef && e.sources?.some((s) => s.source_ref === source)).map((e) => e.model_ref);
1600
+ if (here && !inModel && elsewhere.length > 0) {
1601
+ return {
1602
+ ok: false,
1603
+ problems: [
1604
+ codeProblem(
1605
+ "source-not-in-model",
1606
+ `Model '${modelRef}' has no source '${source}' \u2014 it's in: ${elsewhere.join(", ")}. Pass that model_ref, or fix the source name.`
1607
+ )
1608
+ ]
1609
+ };
1610
+ }
1611
+ }
1612
+ try {
1613
+ return await host.withModel(modelRef, async (m) => {
1614
+ const res = await executeQuery(m, args, srcNudge(modelRef, source), opts.result);
1615
+ if (!execute) return { ...res, model_ref: modelRef };
1616
+ const { sql, ...rest } = res;
1617
+ const out = { ...rest, model_ref: modelRef };
1618
+ if (sql !== void 0) out[HOST_ONLY] = { sql };
1619
+ return out;
1620
+ });
1621
+ } catch (e) {
1622
+ return { ok: false, problems: [refModelProblem(modelRef, e)] };
1623
+ }
1624
+ }
1625
+ };
1626
+ }
1627
+ function exploreSurface(host, opts = {}) {
1628
+ const tools = [];
1629
+ if (host.list) tools.push(listSourcesTool(host));
1630
+ tools.push(describeSourceTool(host));
1631
+ tools.push(exploreQueryTool(host, opts));
1632
+ tools.push(yoHelpTool());
1633
+ return {
1634
+ tools: tools.map(withHelp),
1635
+ instructions: assembleInstructions("explore"),
1636
+ skills: sharedSkills()
1637
+ };
1638
+ }
1639
+
1640
+ // ../mcp-engine/dist/mcp-sdk.js
1641
+ import {
1642
+ CallToolRequestSchema,
1643
+ ListToolsRequestSchema
1644
+ } from "@modelcontextprotocol/sdk/types.js";
1645
+ var HOST_ONLY2 = "host_only";
1646
+ function toContent(result) {
1647
+ const { malloy_text, [HOST_ONLY2]: _hostOnly, ...rest } = result;
1648
+ const content = [
1649
+ { type: "text", text: JSON.stringify(rest, null, 2) }
1650
+ ];
1651
+ if (typeof malloy_text === "string" && malloy_text.length > 0) {
1652
+ content.push({ type: "text", text: malloy_text });
1653
+ }
1654
+ return { content, structuredContent: { ...rest } };
1655
+ }
1656
+ function lowLevel(server) {
1657
+ return "server" in server ? server.server : server;
1658
+ }
1659
+ function attachSurface(server, surface, opts = {}) {
1660
+ const s = lowLevel(server);
1661
+ const byName = new Map(surface.tools.map((t) => [t.name, t]));
1662
+ s.setRequestHandler(ListToolsRequestSchema, async () => ({
1663
+ tools: surface.tools.map((t) => ({
1664
+ name: t.name,
1665
+ title: t.title,
1666
+ description: t.description,
1667
+ inputSchema: t.inputSchema
1668
+ }))
1669
+ }));
1670
+ s.setRequestHandler(CallToolRequestSchema, async (req) => {
1671
+ const tool = byName.get(req.params.name);
1672
+ if (!tool) {
1673
+ return {
1674
+ content: [{ type: "text", text: `unknown tool: ${req.params.name}` }],
1675
+ isError: true
1676
+ };
1677
+ }
1678
+ const result = await tool.handler(
1679
+ req.params.arguments ?? {}
1680
+ );
1681
+ return toContent(result);
1682
+ });
1683
+ if (opts.registerSkillsAsPrompts && "registerPrompt" in server) {
1684
+ const mcp = server;
1685
+ for (const skill of surface.skills) {
1686
+ mcp.registerPrompt(
1687
+ skill.name,
1688
+ { title: skill.name, description: skill.description },
1689
+ () => ({
1690
+ messages: [
1691
+ { role: "user", content: { type: "text", text: skill.body } }
1692
+ ]
1693
+ })
1694
+ );
1695
+ mcp.registerResource(
1696
+ skill.name,
1697
+ `malloy-skill://${skill.name}`,
1698
+ { title: skill.name, description: skill.description, mimeType: "text/markdown" },
1699
+ async (uri) => ({
1700
+ contents: [{ uri: uri.href, mimeType: "text/markdown", text: skill.body }]
1701
+ })
1702
+ );
1703
+ }
1704
+ }
1705
+ }
1706
+
1707
+ // src/mcp.ts
1708
+ var ENTRY = "index.malloy";
1709
+ function defaultConfig(rootUrl) {
1710
+ return new MalloyConfig({ includeDefaultConnections: true }, {
1711
+ rootDirectory: rootUrl.toString()
1712
+ });
1713
+ }
1714
+ async function loadConfig(root, reader) {
1715
+ const rootUrl = url2.pathToFileURL(root + path2.sep);
1716
+ let discovered;
1717
+ try {
1718
+ discovered = await discoverConfig(rootUrl, rootUrl, reader);
1719
+ } catch (e) {
1720
+ return {
1721
+ config: defaultConfig(rootUrl),
1722
+ problems: [codeProblem("config-validation", e instanceof Error ? e.message : String(e))]
1723
+ };
1724
+ }
1725
+ if (discovered) {
1726
+ const log = discovered.log ?? [];
1727
+ return { config: discovered, problems: mapProblems([...log]) };
1728
+ }
1729
+ return { config: defaultConfig(rootUrl), problems: [] };
1730
+ }
1731
+ function fsReader() {
1732
+ return {
1733
+ readURL: async (u) => {
1734
+ if (u.protocol !== "file:") {
1735
+ throw new Error(`unsupported URL scheme for import: ${u.href}`);
1736
+ }
1737
+ return fs.promises.readFile(u, "utf8");
1738
+ }
1739
+ };
1740
+ }
1741
+ function resolveUnderRoot(root, p) {
1742
+ const abs = p.includes("://") ? path2.resolve(decodeURIComponent(new URL(p).pathname)) : path2.resolve(root, p);
1743
+ if (abs !== root && !abs.startsWith(root + path2.sep)) {
1744
+ throw new Error(`path is outside the project root: ${p}`);
1745
+ }
1746
+ return abs;
1747
+ }
1748
+ function makeConfigSource(root) {
1749
+ let cached;
1750
+ const signature = () => ["malloy-config.json", "malloy-config-local.json"].map((name) => {
1751
+ try {
1752
+ const st = fs.statSync(path2.join(root, name));
1753
+ return `${name}:${st.mtimeMs}:${st.size}`;
1754
+ } catch {
1755
+ return `${name}:absent`;
1756
+ }
1757
+ }).join("|");
1758
+ return async () => {
1759
+ const sig = signature();
1760
+ if (cached?.sig !== sig) {
1761
+ cached = { sig, loaded: await loadConfig(root, fsReader()) };
1762
+ }
1763
+ return cached.loaded;
1764
+ };
1765
+ }
1766
+ function makeWithRuntime(root, currentConfig) {
1767
+ return async function withRuntime(input, fn) {
1768
+ const { config, problems } = await currentConfig();
1769
+ return gateConfigProblems(problems, async () => {
1770
+ const resolved = "url" in input ? { url: resolveUnderRoot(root, input.url) } : {
1771
+ source: input.source,
1772
+ baseUrl: input.baseUrl ? resolveUnderRoot(root, input.baseUrl) : root + path2.sep
1773
+ };
1774
+ const { reader, entry, readSource } = prepareSource(fsReader(), resolved);
1775
+ const runtime = new Runtime({ config, urlReader: reader });
1776
+ try {
1777
+ return await fn({ runtime, entry, readSource });
1778
+ } finally {
1779
+ await config.shutdown("idle");
1780
+ }
1781
+ });
1782
+ };
1783
+ }
1784
+ function makeExploreHost(root, currentConfig) {
1785
+ const withRuntime = makeWithRuntime(root, currentConfig);
1786
+ const published = (ref) => ref === ENTRY && fs.existsSync(path2.join(root, ENTRY));
1787
+ return {
1788
+ withModel: (ref, fn) => {
1789
+ if (!published(ref)) throw new Error(`no published model '${ref}'`);
1790
+ return withRuntime({ url: ENTRY }, fn);
1791
+ },
1792
+ list: async () => {
1793
+ if (!published(ENTRY)) return { entries: [] };
1794
+ const entry = await withRuntime({ url: ENTRY }, async (m) => {
1795
+ const compiled = await compile(m.runtime, m.entry, { exportedOnly: true });
1796
+ return compiled.ok && compiled.model ? modelCatalogEntry(ENTRY, compiled.model) : { model_ref: ENTRY };
1797
+ });
1798
+ return { entries: [entry] };
1799
+ }
1800
+ };
1801
+ }
1802
+ async function serveMcp(opts) {
1803
+ await import("@malloydata/malloy-connections");
1804
+ const root = path2.resolve(opts.root ?? process.cwd());
1805
+ const currentConfig = makeConfigSource(root);
1806
+ const surface = exploreSurface(makeExploreHost(root, currentConfig));
1807
+ const instanceName = process.env.INSTANCE_NAME || "Malloyyo";
1808
+ const server = new McpServer(
1809
+ { name: "malloyyo-explore", version: opts.version },
1810
+ {
1811
+ instructions: renderInstructions(surface.instructions, instanceName),
1812
+ capabilities: { tools: {}, prompts: {}, resources: {} }
1813
+ }
1814
+ );
1815
+ attachSurface(server, surface, { registerSkillsAsPrompts: true });
1816
+ await server.connect(new StdioServerTransport());
1817
+ await new Promise((resolveDone) => {
1818
+ server.server.onclose = () => resolveDone();
1819
+ });
1820
+ await (await currentConfig()).config.shutdown("close").catch(() => {
1821
+ });
1822
+ }
1823
+
1824
+ // src/index.ts
1825
+ var VERSION = "0.2.0";
1826
+ function shortSha(sha) {
1827
+ return sha ? sha.slice(0, 7) : "";
1828
+ }
1829
+ async function publish(target, dir, opts) {
1830
+ const root = resolve(dir);
1831
+ const t = resolveTarget(root, target);
1832
+ const bearer = await getAccessToken(t, { tokenFlag: opts.token });
1833
+ const { files, config } = gatherDirectory(root);
1834
+ if (files.length === 0) {
1835
+ throw new Error(`No .malloy files found under ${root}`);
1836
+ }
1837
+ const git = gitInfo(root);
1838
+ const body = { files, config, git };
1839
+ const provenance = git.sha ? `${git.branch}@${shortSha(git.sha)}${git.dirty ? " (dirty)" : ""}` : "(no git)";
1840
+ console.log(`\u2192 ${t.url} dataset=${t.dataset}`);
1841
+ console.log(` ${files.length} file(s) ${provenance}`);
1842
+ if (opts.dryRun) {
1843
+ console.log("dry run \u2014 not sending");
1844
+ return;
1845
+ }
1846
+ const res = await fetch(`${t.url}/api/datasets/${t.dataset}/model/push`, {
1847
+ method: "POST",
1848
+ headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` },
1849
+ body: JSON.stringify(body)
1850
+ });
1851
+ const out = await res.json().catch(() => ({}));
1852
+ if (!res.ok || !out.ok) {
1853
+ throw new Error(`publish failed: ${out.error ?? `${res.status} ${res.statusText}`}`);
1854
+ }
1855
+ console.log(`\u2713 published version ${out.version} \u2014 ${out.sources?.length ?? 0} source(s)`);
1856
+ }
1857
+ async function status(target, opts) {
1858
+ const t = resolveTarget(resolve("."), target);
1859
+ const bearer = await getAccessToken(t, { tokenFlag: opts.token });
1860
+ const res = await fetch(`${t.url}/api/datasets/${t.dataset}/model/status`, {
1861
+ headers: { authorization: `Bearer ${bearer}` }
1862
+ });
1863
+ if (!res.ok) {
1864
+ throw new Error(`status failed: ${res.status} ${res.statusText}`);
1865
+ }
1866
+ const s = await res.json();
1867
+ const git = s.git;
1868
+ console.log(`${t.name}: ${t.url} dataset=${t.dataset}`);
1869
+ console.log(` version ${s.version ?? "?"}` + (git?.sha ? ` ${git.branch}@${shortSha(git.sha)}` : ""));
1870
+ console.log(` ${s.compileError ? `\u2717 ${s.compileError}` : `\u2713 compiled ${s.compiledAt ?? ""}`}`);
1871
+ }
1872
+ async function loginCmd(target) {
1873
+ const inst = resolveInstance(resolve("."), target);
1874
+ await login(inst.url);
1875
+ console.log(`\u2713 logged in to ${inst.name} (${inst.url})`);
1876
+ }
1877
+ async function logoutCmd(target) {
1878
+ const inst = resolveInstance(resolve("."), target);
1879
+ console.log(clearCreds(inst.url) ? `\u2713 logged out of ${inst.url}` : `not logged in to ${inst.url}`);
1880
+ }
1881
+ var program = new Command();
1882
+ program.name("malloyyo").description("Publish Malloy models to a Malloyyo instance").version(VERSION);
1883
+ program.command("login").argument("[target]", "target name or instance URL (optional if the config has one target)").description("sign in to an instance in your browser (stores a token)").action(loginCmd);
1884
+ 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);
1885
+ program.command("publish").argument("<target>", "named target from the `malloyyo` config block").argument("[dir]", "directory to publish", ".").option("--token <token>", "bearer token (overrides login/env)").option("--dry-run", "gather and report what would be sent, but don't POST").description('push the Malloy model in <dir> (default ".") to <target>').action(publish);
1886
+ program.command("status").argument("<target>", "named target from the `malloyyo` config block").option("--token <token>", "bearer token (overrides login/env)").description("show what's live on <target>: version, commit, compile state").action(status);
1887
+ program.command("mcp").option("-C, --root <dir>", "project root (default: current directory)").description(
1888
+ "run a local stdio MCP server (the explore / test-window surface) over the Malloy model in the current directory"
1889
+ ).action(async (opts) => {
1890
+ await serveMcp({ root: opts.root, version: VERSION });
1891
+ });
1892
+ program.parseAsync().catch((err) => {
1893
+ console.error(err instanceof Error ? err.message : String(err));
1894
+ process.exit(1);
1895
+ });