@malloy-publisher/server 0.0.232 → 0.0.233

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 (48) hide show
  1. package/dist/app/api-doc.yaml +61 -10
  2. package/dist/app/assets/{EnvironmentPage-DXEaZIPx.js → EnvironmentPage-DutP7T8h.js} +1 -1
  3. package/dist/app/assets/{HomePage-kofsqpZt.js → HomePage-BcxDrBfl.js} +1 -1
  4. package/dist/app/assets/{LightMode-CNhIlIlJ.js → LightMode-BJukGxgz.js} +1 -1
  5. package/dist/app/assets/{MainPage-Bgqo8jCy.js → MainPage-DXbwlMeF.js} +2 -2
  6. package/dist/app/assets/{MaterializationsPage-CgBlgGz2.js → MaterializationsPage-BBQksmTU.js} +1 -1
  7. package/dist/app/assets/{ModelPage-B0TjoDtf.js → ModelPage-C6tK51uU.js} +1 -1
  8. package/dist/app/assets/{PackagePage-BL8vnFj1.js → PackagePage-Bo3cwwZE.js} +1 -1
  9. package/dist/app/assets/{RouteError-BzPby0X2.js → RouteError-BufkcAKE.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-CTEP_9r3.js → ThemeEditorPage-DICvvKpa.js} +1 -1
  11. package/dist/app/assets/{WorkbookPage-BwM3BmKw.js → WorkbookPage-Dkwt75Nj.js} +1 -1
  12. package/dist/app/assets/{core-CK68iv6w.es-CpRxXBt7.js → core-C0nunIQT.es-DlMLKZBK.js} +1 -1
  13. package/dist/app/assets/{index-CmkW1MiE.js → index-BusxL5Pt.js} +1 -1
  14. package/dist/app/assets/{index-B33zGctF.js → index-CmEVVe-8.js} +4 -4
  15. package/dist/app/assets/{index-tXJXwdyj.js → index-Cs4WVm2z.js} +1 -1
  16. package/dist/app/assets/{index-BkiWKaAF.js → index-qnhU9CGo.js} +1 -1
  17. package/dist/app/index.html +1 -1
  18. package/dist/server.mjs +19456 -842
  19. package/package.json +1 -1
  20. package/src/controller/query.controller.ts +26 -21
  21. package/src/json_utils.spec.ts +51 -0
  22. package/src/json_utils.ts +33 -0
  23. package/src/mcp/query_envelope.spec.ts +229 -0
  24. package/src/mcp/query_envelope.ts +230 -0
  25. package/src/mcp/server.protocol.spec.ts +128 -16
  26. package/src/mcp/skills/build_skills_bundle.ts +94 -4
  27. package/src/mcp/skills/skills_bundle.json +1 -1
  28. package/src/mcp/skills/skills_bundle.spec.ts +113 -4
  29. package/src/mcp/tool_response.spec.ts +108 -0
  30. package/src/mcp/tool_response.ts +138 -0
  31. package/src/mcp/tools/compile_tool.spec.ts +112 -4
  32. package/src/mcp/tools/compile_tool.ts +61 -30
  33. package/src/mcp/tools/docs_search_tool.ts +6 -16
  34. package/src/mcp/tools/execute_query_tool.spec.ts +23 -3
  35. package/src/mcp/tools/execute_query_tool.ts +90 -151
  36. package/src/mcp/tools/get_context_tool.spec.ts +63 -3
  37. package/src/mcp/tools/get_context_tool.ts +43 -46
  38. package/src/mcp/tools/reload_package_tool.ts +3 -29
  39. package/src/service/compile_fragment_techniques.spec.ts +156 -0
  40. package/src/service/connection.spec.ts +371 -1
  41. package/src/service/connection.ts +77 -14
  42. package/src/service/connection_config.spec.ts +60 -0
  43. package/src/service/connection_config.ts +26 -0
  44. package/src/service/duckdb_instance_isolation.spec.ts +137 -0
  45. package/src/service/model.ts +41 -19
  46. package/src/service/model_limits.spec.ts +28 -0
  47. package/src/service/model_limits.ts +21 -0
  48. package/tests/integration/mcp/mcp_execute_query_tool.integration.spec.ts +37 -12
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  import lunr from "lunr";
4
4
  import { EnvironmentStore } from "../../service/environment_store";
5
5
  import { buildMalloyUri } from "../handler_utils";
6
+ import { jsonResource } from "../tool_response";
6
7
  import { logger } from "../../logger";
7
8
  import rawIndex from "./docs_search/malloy_docs_index.json";
8
9
 
@@ -88,6 +89,10 @@ const SEARCH_DOCS_DESCRIPTION = `Search the Malloy documentation by keyword and
88
89
  - Before writing unfamiliar Malloy syntax (window functions, autobin, dialect-specific functions, rendering tags) or when a query fails with a syntax error you do not recognize.
89
90
  - Do NOT use it to look up field or source names in a model; use malloy_getContext for that.
90
91
 
92
+ ## Contract rules
93
+ - These are documentation pages, not model entities. Do not treat a doc title as a field or source name.
94
+ - The excerpt is only a hint; open the url for the full detail.
95
+
91
96
  ## Parameters
92
97
  - query (required): keywords describing what you need.
93
98
  - limit (optional): maximum results to return; default 8.
@@ -95,10 +100,6 @@ const SEARCH_DOCS_DESCRIPTION = `Search the Malloy documentation by keyword and
95
100
  ## Response
96
101
  A JSON array of matches, each with title, url (a docs.malloydata.dev link), and a short excerpt, ordered by relevance. Empty array if nothing matches; broaden the keywords and retry.
97
102
 
98
- ## Contract rules
99
- - These are documentation pages, not model entities. Do not treat a doc title as a field or source name.
100
- - The excerpt is only a hint; open the url for the full detail.
101
-
102
103
  ## Worked example
103
104
  { "query": "window functions lag" }`;
104
105
 
@@ -121,18 +122,7 @@ export function registerDocsSearchTool(
121
122
 
122
123
  const results = searchDocsIndex(query, max);
123
124
 
124
- return {
125
- content: [
126
- {
127
- type: "resource" as const,
128
- resource: {
129
- type: "application/json",
130
- uri: buildMalloyUri({}, "docs-search"),
131
- text: JSON.stringify(results),
132
- },
133
- },
134
- ],
135
- };
125
+ return jsonResource(buildMalloyUri({}, "docs-search"), results);
136
126
  },
137
127
  );
138
128
  }
@@ -13,7 +13,11 @@ import {
13
13
  // compile_tool.spec.ts and reload_package_tool.spec.ts.
14
14
  type Handler = (params: Record<string, unknown>) => Promise<{
15
15
  isError?: boolean;
16
- content: Array<{ resource: { text: string } }>;
16
+ content: Array<{
17
+ type?: string;
18
+ text?: string;
19
+ resource?: { text: string };
20
+ }>;
17
21
  }>;
18
22
 
19
23
  function captureHandler(store: Partial<EnvironmentStore>): Handler {
@@ -28,8 +32,8 @@ function captureHandler(store: Partial<EnvironmentStore>): Handler {
28
32
  return handler;
29
33
  }
30
34
 
31
- function parse(result: { content: Array<{ resource: { text: string } }> }) {
32
- return JSON.parse(result.content[0].resource.text);
35
+ function parse(result: { content: Array<{ resource?: { text: string } }> }) {
36
+ return JSON.parse(result.content[0].resource!.text);
33
37
  }
34
38
 
35
39
  /**
@@ -140,4 +144,20 @@ describe("malloy_executeQuery error classification", () => {
140
144
  // one; echoing the name back would undo that.
141
145
  expect(parsed.error).not.toContain("salaries");
142
146
  });
147
+
148
+ it("also states the error in a text block", async () => {
149
+ // The structured payload rides in an embedded resource block. A client
150
+ // that renders only text blocks on an isError result shows nothing at
151
+ // all for it, which is how a real diagnostic surfaces to the agent as a
152
+ // bare "Unknown error". Every error must say it in plain text too.
153
+ const handler = captureHandler(
154
+ storeWhoseQueryThrows(new MalloyError("unexpected '@'", [])),
155
+ );
156
+ const result = await handler(args);
157
+ const parsed = parse(result);
158
+
159
+ const textBlock = result.content.find((b) => b.type === "text");
160
+ expect(textBlock).toBeDefined();
161
+ expect(textBlock!.text).toContain(parsed.error);
162
+ });
143
163
  });
@@ -16,6 +16,9 @@ import {
16
16
  classifyToolError,
17
17
  getModelForQuery,
18
18
  } from "../handler_utils";
19
+ import { jsonResource, jsonToolError } from "../tool_response";
20
+ import { buildQueryEnvelope } from "../query_envelope";
21
+ import { bigIntReplacer } from "../../json_utils";
19
22
  import { MCP_ERROR_MESSAGES } from "../mcp_constants";
20
23
 
21
24
  /**
@@ -61,6 +64,26 @@ const executeQueryShape = {
61
64
  ),
62
65
  };
63
66
 
67
+ const EXECUTE_QUERY_DESCRIPTION = `Run a Malloy query against a model and return the rows. Takes either ad-hoc Malloy in query, or a named view/query via queryName (with sourceName for a view).
68
+
69
+ ## Contract rules
70
+ - Check _limit_hit before reporting any total, count, or "top N". True means the server's default row cap cut the result off and more rows exist, so the numbers in front of you are a partial set, not the answer. A query that set its own limit: or top: does not set it, and returning exactly that many rows is a complete answer to what was asked.
71
+ - Never sum or count the returned rows to state a total when _limit_hit or _rows_truncated is set. Aggregate in the query instead.
72
+ - _returned_rows: 0 with _rows_truncated set means one row was too large to send, NOT that nothing matched. Do not report it as an empty result.
73
+ - Use source, view, and field names exactly as malloy_getContext returned them.
74
+
75
+ ## Response
76
+ A JSON object, the same shape Credible's execute_query returns, so a data app behaves the same authored locally and served in production:
77
+ - rows: flat objects keyed by column name, the shape an in-package data app receives.
78
+ - _meta: the Malloy metadata flat rows drop (schema with field types and render tags, annotations, connection_name, query_timezone).
79
+ - _query_row_limit: the cap pushed into the SQL, from the query's own limit: or the server default.
80
+ - _limit_source: "query" when the cap came from the query's own limit:/top:, "server_default" otherwise.
81
+ - _limit_hit: the row count equals that cap AND the cap was the server default.
82
+ - _rows_truncated / _total_rows / _returned_rows: present only when the payload cap dropped rows.
83
+ - warning, renderLogErrors: present only when they apply.
84
+
85
+ A query with no limit: of its own gets the server default, so a result landing exactly on _query_row_limit is almost never the whole table. Values above 2^53 are returned as JSON strings so their digits survive.`;
86
+
64
87
  // Type inference is handled automatically by the MCP server based on the executeQueryShape
65
88
 
66
89
  /**
@@ -72,7 +95,7 @@ export function registerExecuteQueryTool(
72
95
  ): void {
73
96
  mcpServer.tool(
74
97
  "malloy_executeQuery",
75
- "Executes a Malloy query (either ad-hoc or a named query/view defined in a model) against the specified model and returns the results as JSON.",
98
+ EXECUTE_QUERY_DESCRIPTION,
76
99
  executeQueryShape,
77
100
  /** Handles requests for the malloy_executeQuery tool */
78
101
  async (params) => {
@@ -120,29 +143,10 @@ export function registerExecuteQueryTool(
120
143
 
121
144
  // Handle errors during package/model access (e.g., not found, initial compilation)
122
145
  if ("error" in modelResult) {
123
- // Format error details as structured JSON
124
- const errorJson = JSON.stringify(
125
- {
126
- error: modelResult.error.message,
127
- suggestions: modelResult.error.suggestions,
128
- },
129
- null,
130
- 2,
146
+ return jsonToolError(
147
+ "error://executeQuery/modelAccess",
148
+ modelResult.error,
131
149
  );
132
- return {
133
- isError: true,
134
- // Return as application/json nested inside a 'resource' type
135
- content: [
136
- {
137
- type: "resource", // Use 'resource' type
138
- resource: {
139
- type: "application/json", // Actual content type
140
- uri: "error://executeQuery/modelAccess", // Placeholder URI
141
- text: errorJson,
142
- },
143
- },
144
- ],
145
- };
146
150
  }
147
151
 
148
152
  // --- Execute Query ---
@@ -160,123 +164,77 @@ export function registerExecuteQueryTool(
160
164
  let querySlot: QuerySlotHandle | null = null;
161
165
  try {
162
166
  querySlot = tryAcquireQuerySlot("mcp:executeQuery");
163
- // If ad-hoc query is provided, use it directly in the 3rd arg
164
- if (query) {
165
- const { result } = await runWithQueryTimeout(
167
+ // The two call modes differ only in which arguments carry the
168
+ // query; everything after the run is identical, so they share one
169
+ // path rather than two copies that can drift.
170
+ const { result, compactResult, rowLimit, rowLimitSource } =
171
+ await runWithQueryTimeout(
166
172
  (abortSignal) =>
167
- model.getQueryResults(
168
- undefined,
169
- undefined,
170
- query,
171
- filterParams,
172
- undefined,
173
- givens as Record<string, GivenValue> | undefined,
174
- abortSignal,
175
- ),
173
+ query
174
+ ? model.getQueryResults(
175
+ undefined,
176
+ undefined,
177
+ query,
178
+ filterParams,
179
+ undefined,
180
+ givens as Record<string, GivenValue> | undefined,
181
+ abortSignal,
182
+ )
183
+ : model.getQueryResults(
184
+ sourceName,
185
+ queryName,
186
+ undefined,
187
+ filterParams,
188
+ undefined,
189
+ givens as Record<string, GivenValue> | undefined,
190
+ abortSignal,
191
+ ),
176
192
  getQueryTimeoutMs(),
177
193
  );
178
- const { validateRenderTags } = await import(
179
- "@malloydata/render-validator"
180
- );
181
- const renderLogs = validateRenderTags(result);
182
194
 
183
- const baseUriComponents = {
184
- environment: environmentName,
185
- package: packageName,
186
- resourceType: "models" as const,
187
- resourceName: modelPath,
188
- };
189
- const resultUri = buildMalloyUri(baseUriComponents, "result");
190
- const resultString = JSON.stringify(result, null, 2);
191
-
192
- const content = [
193
- {
194
- type: "resource" as const,
195
- resource: {
196
- type: "application/json",
197
- uri: resultUri,
198
- text: resultString,
199
- },
200
- },
201
- ];
202
-
203
- if (renderLogs.length > 0) {
204
- return {
205
- isError: false,
206
- content: [
207
- ...content,
208
- {
209
- type: "text" as const,
210
- text: `Render tag warnings:\n${JSON.stringify(renderLogs, null, 2)}`,
211
- },
212
- ],
213
- };
214
- }
215
-
216
- return { isError: false, content };
217
- } else if (queryName) {
218
- const { result } = await runWithQueryTimeout(
219
- (abortSignal) =>
220
- model.getQueryResults(
221
- sourceName,
222
- queryName,
223
- undefined,
224
- filterParams,
225
- undefined,
226
- givens as Record<string, GivenValue> | undefined,
227
- abortSignal,
228
- ),
229
- getQueryTimeoutMs(),
230
- );
231
- const { validateRenderTags } = await import(
232
- "@malloydata/render-validator"
233
- );
234
- const renderLogs = validateRenderTags(result);
195
+ // Render-tag validation reads the FULL Malloy result: the tags live
196
+ // in its schema annotations, which the flat rows do not carry. It
197
+ // runs regardless of which shape is returned.
198
+ const { validateRenderTags } = await import(
199
+ "@malloydata/render-validator"
200
+ );
201
+ const renderLogs = validateRenderTags(result);
235
202
 
236
- const baseUriComponents = {
203
+ const resultUri = buildMalloyUri(
204
+ {
237
205
  environment: environmentName,
238
206
  package: packageName,
239
207
  resourceType: "models" as const,
240
208
  resourceName: modelPath,
241
- };
242
- const resultUri = buildMalloyUri(baseUriComponents, "result");
243
- const resultString = JSON.stringify(result, null, 2);
244
-
245
- const content = [
246
- {
247
- type: "resource" as const,
248
- resource: {
249
- type: "application/json",
250
- uri: resultUri,
251
- text: resultString,
252
- },
253
- },
254
- ];
209
+ },
210
+ "result",
211
+ );
255
212
 
256
- if (renderLogs.length > 0) {
257
- return {
258
- isError: false,
259
- content: [
260
- ...content,
261
- {
262
- type: "text" as const,
263
- text: `Render tag warnings:\n${JSON.stringify(renderLogs, null, 2)}`,
264
- },
265
- ],
266
- };
267
- }
213
+ const envelope = buildQueryEnvelope(
214
+ compactResult,
215
+ rowLimit,
216
+ result,
217
+ renderLogs.map((log) => log.message),
218
+ undefined,
219
+ rowLimitSource,
220
+ );
268
221
 
269
- return { isError: false, content };
270
- }
222
+ // A capped or truncated result, and a broken render tag, are the
223
+ // things an agent most needs to notice, so they are stated in text
224
+ // rather than left for a client that parses the payload.
225
+ const notes = [
226
+ envelope.warning,
227
+ envelope.renderLogErrors &&
228
+ `Render tag problems: ${envelope.renderLogErrors.join("; ")}`,
229
+ ].filter(Boolean);
271
230
 
272
- // If execution reaches this point, something has gone wrong with
273
- // the earlier parameter validation logic. Throw an explicit error
274
- // so the return type is never 'undefined' from the compiler's
275
- // perspective.
276
- throw new McpError(
277
- ErrorCode.InternalError,
278
- "Unreachable executeQuery code path – parameters were not validated correctly.",
279
- );
231
+ return jsonResource(resultUri, envelope, {
232
+ space: 2,
233
+ // BigInt reaches here: compactResult is raw driver output and
234
+ // DuckDB returns count() as one.
235
+ replacer: bigIntReplacer,
236
+ text: notes.length > 0 ? notes.join("\n\n") : undefined,
237
+ });
280
238
  } catch (queryError) {
281
239
  // Handle query execution errors (syntax errors, invalid queries, etc.)
282
240
  logger.error(
@@ -306,29 +264,10 @@ export function registerExecuteQueryTool(
306
264
  );
307
265
  }
308
266
 
309
- // Format error details as structured JSON
310
- const errorJson = JSON.stringify(
311
- {
312
- error: errorDetails.message,
313
- suggestions,
314
- },
315
- null,
316
- 2,
317
- );
318
- return {
319
- isError: true,
320
- // Return as application/json nested inside a 'resource' type
321
- content: [
322
- {
323
- type: "resource", // Use 'resource' type
324
- resource: {
325
- type: "application/json", // Actual content type
326
- uri: "error://executeQuery/queryExecution", // Placeholder URI
327
- text: errorJson,
328
- },
329
- },
330
- ],
331
- };
267
+ return jsonToolError("error://executeQuery/queryExecution", {
268
+ message: errorDetails.message,
269
+ suggestions,
270
+ });
332
271
  } finally {
333
272
  // Release on every exit path — success, error, or
334
273
  // unreachable code-path throw. `release()` is idempotent
@@ -18,6 +18,7 @@ import {
18
18
  } from "./get_context_tool";
19
19
  import { embeddingText } from "./embedding_index";
20
20
  import type { EnvironmentStore } from "../../service/environment_store";
21
+ import { PackageNotFoundError } from "../../errors";
21
22
  import { DuckDBConnection } from "../../storage/duckdb/DuckDBConnection";
22
23
  import { createEntityEmbeddingsTable } from "../../storage/duckdb/schema";
23
24
  import {
@@ -132,9 +133,15 @@ describe("get_context sanitize", () => {
132
133
 
133
134
  // Capture the tool handler that registerGetContextTool passes to McpServer.tool,
134
135
  // so each discovery tier can be exercised against a mocked EnvironmentStore.
136
+ type Content = Array<{
137
+ type?: string;
138
+ text?: string;
139
+ resource?: { text: string };
140
+ }>;
141
+
135
142
  type Handler = (params: Record<string, unknown>) => Promise<{
136
143
  isError?: boolean;
137
- content: Array<{ resource: { text: string } }>;
144
+ content: Content;
138
145
  }>;
139
146
 
140
147
  function captureHandler(store: Partial<EnvironmentStore>): Handler {
@@ -149,8 +156,12 @@ function captureHandler(store: Partial<EnvironmentStore>): Handler {
149
156
  return handler;
150
157
  }
151
158
 
152
- function parse(result: { content: Array<{ resource: { text: string } }> }) {
153
- return JSON.parse(result.content[0].resource.text);
159
+ function parse(result: { content: Content }) {
160
+ return JSON.parse(result.content[0].resource!.text);
161
+ }
162
+
163
+ function textBlock(result: { content: Content }) {
164
+ return result.content.find((b) => b.type === "text")?.text;
154
165
  }
155
166
 
156
167
  // A model with one source (order_items) carrying one dimension (state).
@@ -242,6 +253,53 @@ describe("get_context discovery tiers", () => {
242
253
  const parsed = parse(result);
243
254
  expect(parsed.results).toEqual([]);
244
255
  expect(parsed.error).toContain("could not be resolved");
256
+ // Suggestions and a text block, same as this tool's three siblings. Both
257
+ // were absent before: the payload carried a bare message, and a
258
+ // text-only client saw nothing at all.
259
+ expect(parsed.suggestions.length).toBeGreaterThan(0);
260
+ expect(textBlock(result)).toContain("could not be resolved");
261
+ });
262
+
263
+ it("reports an unknown package as not-found, not as an internal fault", async () => {
264
+ // Pins the classification, not just that an error came back. Before this
265
+ // routed through classifyToolError every failure arrived as the raw
266
+ // message with no remediation, so a typo'd package name gave the agent
267
+ // nothing to act on.
268
+ const handler = captureHandler({
269
+ getEnvironment: async () =>
270
+ ({
271
+ getPackage: async () => {
272
+ throw new PackageNotFoundError("Package 'nope' not found");
273
+ },
274
+ }) as never,
275
+ });
276
+ const result = await handler({
277
+ environmentName: "malloy-samples",
278
+ packageName: "nope",
279
+ query: "state",
280
+ });
281
+ expect(result.isError).toBe(true);
282
+ const parsed = parse(result);
283
+ expect(parsed.results).toEqual([]);
284
+ expect(parsed.error).toContain("Resource not found");
285
+ expect(parsed.error).toContain("nope");
286
+ expect(textBlock(result)).toContain("Resource not found");
287
+ });
288
+
289
+ it("reports a non-Error throwable without inventing 'Unknown error'", async () => {
290
+ // The old per-site `error instanceof Error ? error.message : "Unknown
291
+ // error"` turned a thrown string into exactly the unhelpful text this
292
+ // tool's callers reported. classifyToolError stringifies it instead.
293
+ const handler = captureHandler({
294
+ listEnvironments: async () => {
295
+ throw "the store exploded";
296
+ },
297
+ });
298
+ const result = await handler({});
299
+ const parsed = parse(result);
300
+ expect(parsed.error).toContain("the store exploded");
301
+ expect(parsed.error).not.toContain("Unknown error");
302
+ expect(textBlock(result)).toContain("the store exploded");
245
303
  });
246
304
 
247
305
  it("tier 3: package without a query lists only its sources", async () => {
@@ -299,6 +357,8 @@ describe("get_context discovery tiers", () => {
299
357
  const parsed = parse(result);
300
358
  expect(parsed.results).toEqual([]);
301
359
  expect(parsed.error).toContain("not initialized");
360
+ expect(parsed.suggestions.length).toBeGreaterThan(0);
361
+ expect(textBlock(result)).toContain("not initialized");
302
362
  });
303
363
 
304
364
  it("tier 3: lists every source, not just the first 10", async () => {
@@ -8,7 +8,8 @@ import {
8
8
  embeddingConfigured,
9
9
  getEmbeddingProvider,
10
10
  } from "../../service/embedding_provider";
11
- import { buildMalloyUri } from "../handler_utils";
11
+ import { buildMalloyUri, classifyToolError } from "../handler_utils";
12
+ import { jsonResource, jsonToolError } from "../tool_response";
12
13
  import { logger } from "../../logger";
13
14
  import { entityRowKey, trySemanticSearch } from "./embedding_index";
14
15
 
@@ -261,46 +262,45 @@ async function getPackageIndex(
261
262
 
262
263
  const GET_CONTEXT_DESCRIPTION = `Discover what a Publisher deployment exposes and retrieve the model entities most relevant to a plain-English question, so you can ground a query in what the model actually defines instead of guessing. This is the starting point when you do not yet know the environment, package, or model names.
263
264
 
264
- ## Progressive discovery
265
- Call it with as much as you know and omit the rest; it answers at the appropriate level:
266
- - No arguments: lists the available environments, each with its package names.
267
- - environmentName only: lists the packages in that environment, with descriptions.
268
- - environmentName + packageName: lists that package's sources.
269
- - environmentName + packageName + query: returns the sources, views, named queries, and dimension/measure fields most relevant to the question.
265
+ ## Contract rules
266
+ - Use the names it returns verbatim; never invent an environment, package, or entity that is not in the results.
267
+ - Start broad and narrow down: environments, then packages, then sources, then a query.
270
268
 
271
269
  ## Parameters
272
- - environmentName (optional): omit to list environments.
273
- - packageName (optional): omit, with environmentName set, to list packages.
274
- - query (optional): a plain-English description of what you need; omit, with environmentName and packageName set, to list the package's sources.
275
- - sourceName (optional): narrow retrieval to entities within one source (the drill-down phase).
276
- - limit (optional): cap the number of results (max 50). Retrieval defaults to 10; the listing tiers return all unless set.
270
+ All optional. Supply what you know and omit the rest; each combination answers at its own level.
271
+ - none: lists the environments, each with its package names.
272
+ - environmentName: lists that environment's packages, with descriptions.
273
+ - + packageName: lists that package's sources.
274
+ - + query: a plain-English description of what you need, returning the sources, views, named queries, and dimension/measure fields most relevant to it.
275
+ - sourceName: narrows retrieval to one source (the drill-down phase).
276
+ - limit: caps results (max 50). Retrieval defaults to 10; the listing levels return all unless set.
277
277
 
278
278
  ## Response
279
279
  A JSON object with a results array whose items carry a kind field. For retrieval, each entity has kind (source / view / query / dimension / measure), name, source, modelPath, and doc; environmentName, packageName, modelPath, and source map directly onto malloy_executeQuery parameters, and for a view or named query you pass its name as queryName with sourceName. When the server is configured with an embedding provider, retrieval is ranked by semantic similarity: the payload then carries a retrieval field ("semantic", or "lexical" when the provider is unavailable) and each semantic entity a score.
280
280
 
281
- ## Contract rules
282
- - Use the names verbatim; do not invent environments, packages, or entities not in the results.
283
- - Start broad and narrow down: list environments, then packages, then sources, then query.
284
-
285
281
  ## Worked example
286
282
  { "environmentName": "examples", "packageName": "storefront", "query": "revenue by product category" }`;
287
283
 
288
284
  /**
289
- * Wrap a JSON payload in the MCP resource-content shape every tier of this tool
290
- * returns. isError marks a tool-level error (e.g. an unknown environment/package).
285
+ * Every tier of this tool answers with `results`, so an error keeps that key
286
+ * (empty) alongside `error`. Callers can read `results` unconditionally without
287
+ * branching on success first.
288
+ *
289
+ * Routed through classifyToolError for the same reason its three sibling tools
290
+ * are: it homes each error class to real remediation, so an unknown package
291
+ * says so instead of arriving as a bare message with no suggestions. It also
292
+ * replaces a per-site `error instanceof Error ? error.message : "Unknown
293
+ * error"`, which was the one path in this file that could produce exactly the
294
+ * unhelpful string this tool's callers reported.
291
295
  */
292
- function jsonResource(uri: string, payload: unknown, isError = false) {
293
- const content = [
296
+ function contextError(uri: string, identifier: string, error: unknown) {
297
+ return jsonToolError(
298
+ uri,
299
+ classifyToolError("getContext", identifier, error),
294
300
  {
295
- type: "resource" as const,
296
- resource: {
297
- type: "application/json",
298
- uri,
299
- text: JSON.stringify(payload),
300
- },
301
+ results: [],
301
302
  },
302
- ];
303
- return isError ? { isError: true, content } : { content };
303
+ );
304
304
  }
305
305
 
306
306
  /**
@@ -348,16 +348,17 @@ export function registerGetContextTool(
348
348
  results,
349
349
  });
350
350
  } catch (error) {
351
- const message =
352
- error instanceof Error ? error.message : "Unknown error";
353
351
  logger.warn(
354
352
  "[MCP Tool getContext] listing environments failed",
355
- { error: message },
353
+ {
354
+ error:
355
+ error instanceof Error ? error.message : String(error),
356
+ },
356
357
  );
357
- return jsonResource(
358
+ return contextError(
358
359
  buildMalloyUri({}, "get-context"),
359
- { error: message, results: [] },
360
- true,
360
+ "environments",
361
+ error,
361
362
  );
362
363
  }
363
364
  }
@@ -384,19 +385,17 @@ export function registerGetContextTool(
384
385
  { results },
385
386
  );
386
387
  } catch (error) {
387
- const message =
388
- error instanceof Error ? error.message : "Unknown error";
389
388
  logger.warn("[MCP Tool getContext] listing packages failed", {
390
389
  environmentName,
391
- error: message,
390
+ error: error instanceof Error ? error.message : String(error),
392
391
  });
393
- return jsonResource(
392
+ return contextError(
394
393
  buildMalloyUri(
395
394
  { environment: environmentName },
396
395
  "get-context",
397
396
  ),
398
- { error: message, results: [] },
399
- true,
397
+ environmentName,
398
+ error,
400
399
  );
401
400
  }
402
401
  }
@@ -410,21 +409,19 @@ export function registerGetContextTool(
410
409
  packageName,
411
410
  );
412
411
  } catch (error) {
413
- const message =
414
- error instanceof Error ? error.message : "Unknown error";
415
412
  logger.warn("[MCP Tool getContext] index build failed", {
416
413
  environmentName,
417
414
  packageName,
418
415
  sourceName,
419
- error: message,
416
+ error: error instanceof Error ? error.message : String(error),
420
417
  });
421
- return jsonResource(
418
+ return contextError(
422
419
  buildMalloyUri(
423
420
  { environment: environmentName, package: packageName },
424
421
  "get-context",
425
422
  ),
426
- { error: message, results: [] },
427
- true,
423
+ `${environmentName}/${packageName}`,
424
+ error,
428
425
  );
429
426
  }
430
427