@centrali-io/centrali-mcp 5.5.1 → 6.1.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.
package/README.md CHANGED
@@ -90,7 +90,7 @@ After connecting, call `describe_centrali` first — it returns the full capabil
90
90
  | `describe_records` | Schema reference for record operations (filters, sorting, pagination, expand) |
91
91
  | `describe_search` | Schema reference for full-text search |
92
92
  | `describe_compute` | Compute function reference (input contract, secrets, async execution, api object) |
93
- | `describe_smart_queries` | Smart query reference (parameterized queries, variables) |
93
+ | `describe_saved_queries` | Saved-query schema reference (parameterized queries, variables) |
94
94
  | `describe_orchestrations` | Orchestration reference (multi-step workflows, encrypted params) |
95
95
  | `describe_insights` | Anomaly insights reference |
96
96
  | `describe_validation` | Data validation reference |
@@ -154,19 +154,113 @@ After connecting, call `describe_centrali` first — it returns the full capabil
154
154
  | `invoke_endpoint` | Call a sync compute endpoint by path (returns response inline) |
155
155
  | `remove_allowed_domain` | Remove a domain from the allowlist |
156
156
 
157
- ### Saved Queries (a.k.a. Smart Queries)
157
+ ### Saved Queries
158
158
 
159
- Saved queries store a canonical `QueryDefinition` plus optional variables. Tool names keep the `_smart_query` suffix for backwards compatibility, but inputs and outputs are the canonical shape.
159
+ Saved queries store a canonical `QueryDefinition` plus optional variables and an optional multi-collection `joins[]` clause.
160
160
 
161
161
  | Tool | Description |
162
162
  |------|-------------|
163
- | `list_smart_queries` | List saved queries, optionally by collection |
164
- | `get_smart_query` | Get a saved query by ID |
165
- | `create_smart_query` | Create a reusable parameterized query (canonical body) |
166
- | `update_smart_query` | Update a saved query (canonical body) |
167
- | `delete_smart_query` | Delete a saved query |
168
- | `execute_smart_query` | Execute a saved query with optional variables |
169
- | `test_smart_query` | Test a canonical query definition without saving |
163
+ | `list_saved_queries` | List saved queries, optionally by collection |
164
+ | `get_saved_query` | Get a saved query by ID |
165
+ | `create_saved_query` | Create a reusable parameterized query (canonical body) |
166
+ | `update_saved_query` | Update a saved query (canonical body) |
167
+ | `delete_saved_query` | Delete a saved query |
168
+ | `execute_saved_query` | Execute a saved query with optional variables |
169
+ | `test_saved_query` | Test a canonical query definition without saving |
170
+
171
+ **Typed parameter discovery → execute.** Saved queries authored with typed parameters expose their parameter shape through `describe_saved_queries` (schema reference) and `get_saved_query` / `list_saved_queries` (per-row `variables` declarations). The expected discover-then-execute flow:
172
+
173
+ 1. **Discover schema** (one-shot) — `describe_saved_queries` returns the `QueryVariableDefinition` shape (`type`, `required?`, `default?`, `description?`) and the supported `VariableType` union (`string` | `number` | `boolean` | `datetime` | `id` | `{ array: T }` | `{ reference: collectionSlug }`).
174
+ 2. **Discover the query** — `get_saved_query` returns the row including `variables`. Read each entry to learn what to bind. The canonical response includes `queryDefinition.resource` (always equal to the row's `recordSlug`):
175
+ ```json
176
+ {
177
+ "id": "…",
178
+ "name": "Monthly revenue",
179
+ "recordSlug": "orders",
180
+ "queryDefinition": {
181
+ "resource": "orders",
182
+ "where": { "and": [
183
+ { "data.month": { "eq": "${month}" } },
184
+ { "data.region": { "eq": "${region}" } }
185
+ ]},
186
+ "sort": [{ "field": "data.amount", "direction": "desc" }],
187
+ "page": { "limit": 100 }
188
+ },
189
+ "variables": {
190
+ "month": { "type": "datetime", "required": true, "description": "Month bucket (UTC)" },
191
+ "region": { "type": "string", "required": true }
192
+ }
193
+ }
194
+ ```
195
+ 3. **Execute typed** — pass concrete values via `execute_saved_query`'s `variables` arg. The server validates each value against its declared type (no coercion — `"123"` will not be accepted for a `number` declaration) and then substitutes. `datetime` accepts an ISO-8601 string:
196
+ ```json
197
+ {
198
+ "recordSlug": "orders",
199
+ "queryId": "…",
200
+ "variables": { "month": "2026-04-01T00:00:00Z", "region": "us-east" }
201
+ }
202
+ ```
203
+ Typed errors surface as `variable_type_mismatch`, `missing_required_variable`, or `extra_variable`. Untyped (legacy) rows have `variables: null` and accept any keys; values are stringified before substitution. The untyped fallback is also taken by post-backfill rows (canonical body, no declarations yet) until an author promotes them.
204
+
205
+ The MCP `test_saved_query` tool intentionally does **not** expose `variableDeclarations` — its dry-run path falls back to legacy string substitution and does not enforce typed declarations. Round-trip via `create_saved_query` + `execute_saved_query` to validate typed parameters end-to-end.
206
+
207
+ **Multi-collection joins.** Saved queries support an optional `joins[]` clause inside `queryDefinition` (max 4 entries). Each entry joins another collection to the primary record set:
208
+
209
+ ```json
210
+ {
211
+ "resource": "orders",
212
+ "where": { "data.status": { "eq": "open" } },
213
+ "joins": [
214
+ {
215
+ "foreignSlug": "customers",
216
+ "localField": "data.customerId",
217
+ "foreignField": "id",
218
+ "joinType": "left",
219
+ "select": ["id", "data.name", "data.email"],
220
+ "alias": "customer"
221
+ }
222
+ ],
223
+ "sort": [{ "field": "createdAt", "direction": "desc" }],
224
+ "page": { "limit": 50 }
225
+ }
226
+ ```
227
+
228
+ Constraints (validated by `@centrali/query`):
229
+
230
+ - `joinType` must be `'inner'` or `'left'` — `'right'` and `'full'` are rejected by the executor with `unsupported_clause`.
231
+ - `text` and `joins` cannot appear in the same query (`unsupported_combination`).
232
+ - Aliases (or implicit `foreignSlug`) must be unique within `joins[]` (`duplicate_join_alias`).
233
+ - Cap of 4 entries (`joins_length_exceeded`).
234
+ - `localField` may use `<priorAlias>.<field>` to chain a join through an earlier alias.
235
+
236
+ `execute_saved_query` returns `{ rows, meta, fields }`. Each entry in `rows` carries joined data under a top-level `_joined` key:
237
+
238
+ ```json
239
+ {
240
+ "rows": [
241
+ {
242
+ "id": "order-123",
243
+ "data": { "status": "open" },
244
+ "_joined": {
245
+ "customer": { "id": "cust-1", "data": { "name": "Acme" } }
246
+ }
247
+ }
248
+ ],
249
+ "meta": { "limit": 50, "offset": 0, "total": 1 },
250
+ "fields": [{ "name": "id" }, { "name": "data" }, { "name": "_joined" }]
251
+ }
252
+ ```
253
+
254
+ LEFT joins surface `null` for unmatched rows.
255
+
256
+ **Authorization (SECURITY DEFINER, locked 2026-05-04).** Saved queries are author-bound — the AUTHOR's permissions define what the query can read; the executor only needs an `execute` check on the saved-query resource at runtime.
257
+
258
+ - **Author time** (`create_saved_query` / `update_saved_query` / `test_saved_query`): the caller must hold `records:list` on the primary collection AND on every collection referenced in `joins[]`. The data service returns 403 if any access is missing.
259
+ - **Execute time** (`execute_saved_query`): only `execute` on the saved-query resource is checked; there is no per-collection re-check, and field-level redaction follows the author's permissions, not the executor's. Secret-masking still applies unconditionally.
260
+
261
+ AI assistants should not propose saved queries (or join chains) against collections the **author** can't read — execute will succeed for less-privileged callers, but authoring will fail.
262
+
263
+ **Reserved clauses.** Saved-query create/update/test surfaces reject `text` (full-text search) and `include` (relation expansion) with 422 `unsupported_clause`. Those clauses are available on the ad-hoc `POST /records/query` surface only — don't author saved queries that use them.
170
264
 
171
265
  ### Orchestrations
172
266
  | Tool | Description |
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ const structures_js_1 = require("./tools/structures.js");
17
17
  const records_js_1 = require("./tools/records.js");
18
18
  const search_js_1 = require("./tools/search.js");
19
19
  const compute_js_1 = require("./tools/compute.js");
20
- const smart_queries_js_1 = require("./tools/smart-queries.js");
20
+ const saved_queries_js_1 = require("./tools/saved-queries.js");
21
21
  const orchestrations_js_1 = require("./tools/orchestrations.js");
22
22
  const insights_js_1 = require("./tools/insights.js");
23
23
  const validation_js_1 = require("./tools/validation.js");
@@ -73,7 +73,7 @@ function main() {
73
73
  (0, records_js_1.registerRecordTools)(server, sdk, baseUrl, workspaceId);
74
74
  (0, search_js_1.registerSearchTools)(server, sdk);
75
75
  (0, compute_js_1.registerComputeTools)(server, sdk, baseUrl, workspaceId);
76
- (0, smart_queries_js_1.registerSmartQueryTools)(server, sdk);
76
+ (0, saved_queries_js_1.registerSavedQueryTools)(server, sdk);
77
77
  (0, orchestrations_js_1.registerOrchestrationTools)(server, sdk);
78
78
  (0, insights_js_1.registerInsightTools)(server, sdk);
79
79
  (0, validation_js_1.registerValidationTools)(server, sdk);
@@ -379,7 +379,7 @@ function registerComputeTools(server, sdk, centraliUrl, workspaceId) {
379
379
  triggerMetadata: zod_1.z
380
380
  .record(zod_1.z.string(), zod_1.z.any())
381
381
  .optional()
382
- .describe("Type-specific configuration. For event-driven: { eventType, recordSlug }. For scheduled: { scheduleType, cronExpression, timezone }. For http-trigger: auto-generated URL. For endpoint: { path, allowedMethods?, timeoutMs?, auth? } where path is URL-safe (e.g., 'create-order'), allowedMethods defaults to ['POST'], timeoutMs 1000-30000 (default 30000), auth is { mode: 'bearer'|'public'|'apiKey'|'hmac' }. All trigger types accept params: a dictionary of static values passed to the function as triggerParams. Mark any secret with { value: 'plaintext', encrypt: true } to store it AES-256-GCM-encrypted at rest; it arrives as plaintext in triggerParams at execution time."),
382
+ .describe("Type-specific configuration. For event-driven: { eventType, recordSlug }. For scheduled: { scheduleType, cronExpression, timezone }. For http-trigger: { path } where path is a URL-safe slug (e.g. 'stripe-webhook'); the trigger is reachable at `<api-host>/data/workspace/<workspaceSlug>/api/v1/http-trigger/<path>`. Optional native HMAC signature verification (no crypto in the function body): the **recommended path** is { validateSignature: true, provider: 'svix' | 'stripe' | 'slack' | 'github' | 'shopify', signingSecret } — the `provider` shortcut wires every wire-format detail (header names, signed-value format, digest encoding, secret encoding) from a built-in preset. Covers Svix (Clerk, Resend, Loops, OpenAI, Brex), Stripe, Slack, GitHub, Shopify out of the box. **Advanced**: any preset field can be overridden, or the preset can be skipped entirely by supplying the raw knobs directly — { validateSignature: true, signingSecret, signatureHeaderName, signatureIdHeaderName?, timestampHeaderName?, timestampExtractionPattern?, extractionPattern?, hmacAlgorithm?, hmacEncoding?, secretEncoding?, encoding?, payloadFormat? }. Defaults when no provider: hmacAlgorithm 'sha256', hmacEncoding 'base64', extractionPattern '^(?:v1,)?(.+)$', secretEncoding 'raw'; built-in 5-minute replay tolerance. Two-step setup recommended: (1) create the trigger with just { path } and optionally { provider } — the public URL is `<api-host>/data/workspace/<ws>/api/v1/http-trigger/<path>`; (2) register that URL with the webhook provider; (3) when the provider issues the signing secret, call update_trigger with validateSignature: true + signingSecret. Providers will not give a signing secret until they have the URL. For endpoint: { path, allowedMethods?, timeoutMs?, auth? } where path is URL-safe (e.g., 'create-order'), allowedMethods defaults to ['POST'], timeoutMs 1000-30000 (default 30000), auth is { mode: 'bearer'|'public'|'apiKey'|'hmac' | 'svix' | 'stripe' | 'slack' | 'github' | 'shopify', secret? } — provider-named modes are HMAC verification with the matching preset (auth.secret is the colocated signing secret; legacy `mode: 'hmac'` keeps its single-header body-only behaviour for back-compat). All trigger types accept params: a dictionary of static values passed to the function as triggerParams. Mark any secret with { value: 'plaintext', encrypt: true } to store it AES-256-GCM-encrypted at rest; it arrives as plaintext in triggerParams at execution time."),
383
383
  enabled: zod_1.z.boolean().optional().describe("Whether the trigger is enabled (default: true)"),
384
384
  }, (_a) => __awaiter(this, [_a], void 0, function* ({ name, functionId, executionType, description, triggerMetadata, enabled }) {
385
385
  try {
@@ -90,16 +90,16 @@ function registerDescribeTools(server) {
90
90
  ],
91
91
  },
92
92
  smart_queries: {
93
- summary: "Reusable, parameterized queries defined in the console. Support {{variable}} substitution.",
94
- describeWith: "describe_smart_queries",
93
+ summary: "Reusable, parameterized queries defined in the console. Support typed '${variable}' substitution and multi-collection joins (up to 4 joined collections per query).",
94
+ describeWith: "describe_saved_queries",
95
95
  tools: [
96
- "list_smart_queries",
97
- "get_smart_query",
98
- "create_smart_query",
99
- "update_smart_query",
100
- "delete_smart_query",
101
- "execute_smart_query",
102
- "test_smart_query",
96
+ "list_saved_queries",
97
+ "get_saved_query",
98
+ "create_saved_query",
99
+ "update_saved_query",
100
+ "delete_saved_query",
101
+ "execute_saved_query",
102
+ "test_saved_query",
103
103
  ],
104
104
  },
105
105
  orchestrations: {
@@ -845,6 +845,33 @@ function registerDescribeTools(server) {
845
845
  triggerMetadata_examples: {
846
846
  "event-driven": { eventType: "record_created", recordSlug: "orders" },
847
847
  scheduled: { scheduleType: "cron", cronExpression: "0 9 * * *", timezone: "America/New_York" },
848
+ "http-trigger_url_shape": "Public URL: <api-host>/data/workspace/<workspaceSlug>/api/v1/http-trigger/<path>. The path is supplied by the caller in triggerMetadata.path and must be URL-safe. The URL is NOT returned in the create_trigger / get_trigger response — derive it from the workspaceSlug + path.",
849
+ "http-trigger_setup_flow": "Webhook signing secrets are chicken-and-egg: providers issue the secret only AFTER you give them a URL. Recommended flow — (1) create_trigger with { path, provider, validateSignature: true } and NO signingSecret — the trigger is created in a pending state with a stable URL; (2) register that URL in the provider's dashboard; (3) once the provider returns the signing secret, call update_trigger with signingSecret set. Until step 3 lands, the trigger rejects every request with 'HMAC signing secret not configured for this endpoint' — that's the desired safe default during URL-registration.",
850
+ "http-trigger_provider_shortcut": {
851
+ _note: "Recommended — one preset wires every wire-format detail. Use this for Svix (Clerk, Resend, Loops, OpenAI, Brex), Stripe, Slack, GitHub, Shopify. Override individual fields only if a provider's scheme has drifted (e.g. custom hmacAlgorithm).",
852
+ path: "clerk-webhook",
853
+ validateSignature: true,
854
+ provider: "svix",
855
+ signingSecret: "whsec_…",
856
+ },
857
+ "http-trigger_advanced_raw": {
858
+ _note: "Skip the preset for full manual control — useful for non-standard schemes the built-in providers don't cover. Every field maps 1:1 to the runtime SignatureMetadata interface.",
859
+ path: "custom-webhook",
860
+ validateSignature: true,
861
+ signingSecret: "whsec_…",
862
+ signatureHeaderName: "x-custom-signature",
863
+ timestampHeaderName: "x-custom-timestamp",
864
+ extractionPattern: "^v1,(.+)$",
865
+ hmacAlgorithm: "sha256",
866
+ hmacEncoding: "base64",
867
+ secretEncoding: "prefixed-base64",
868
+ },
869
+ endpoint_provider_shortcut: {
870
+ _note: "Provider-named endpoint auth mode + colocated secret. Equivalent to mode: 'hmac' + triggerMetadata.provider — the service layer normalises auth.secret onto triggerMetadata.signingSecret at create/update time.",
871
+ path: "stripe-events",
872
+ allowedMethods: ["POST"],
873
+ auth: { mode: "stripe", secret: "whsec_…" },
874
+ },
848
875
  endpoint: { path: "create-order", allowedMethods: ["POST"], timeoutMs: 10000, auth: { mode: "bearer" } },
849
876
  },
850
877
  },
@@ -985,30 +1012,84 @@ function registerDescribeTools(server) {
985
1012
  ],
986
1013
  });
987
1014
  }));
988
- // ── Smart Queries ──────────────────────────────────────────────────
989
- (0, _register_js_1.registerTool)(server, "describe_smart_queries", "Get the schema reference for Centrali saved (a.k.a. smart) queries. Explains the canonical QueryDefinition body, variable substitution, and execution.", {}, () => __awaiter(this, void 0, void 0, function* () {
1015
+ // ── Saved Queries ──────────────────────────────────────────────────
1016
+ (0, _register_js_1.registerTool)(server, "describe_saved_queries", "Get the schema reference for Centrali saved queries. Explains the canonical QueryDefinition body, variable substitution, and execution.", {}, () => __awaiter(this, void 0, void 0, function* () {
990
1017
  return ({
991
1018
  content: [
992
1019
  {
993
1020
  type: "text",
994
1021
  text: JSON.stringify({
995
- domain: "Saved Queries (a.k.a. Smart Queries)",
996
- description: "Saved queries are reusable, parameterized queries defined in the Centrali console. They store a canonical QueryDefinition plus optional variable declarations and are executed under the caller's permissions. Tool names retain the `_smart_query` suffix for backwards compatibility.",
1022
+ domain: "Saved Queries",
1023
+ description: "Saved queries are reusable, parameterized queries defined in the Centrali console. They store a canonical QueryDefinition plus optional typed variable declarations and follow SECURITY DEFINER auth — the AUTHOR's permissions define what the query can read; the executor only needs an 'execute' check on the saved-query resource.",
997
1024
  saved_query_shape: {
998
1025
  id: "UUID",
999
1026
  name: "string — display name",
1000
1027
  recordSlug: "string — the collection this query targets",
1001
1028
  description: "string | null",
1002
- queryDefinition: "object — canonical QueryDefinition (without 'resource' — filled in from recordSlug). Variables are referenced as '{{varName}}' placeholders inside operator values; the engine infers them from the body.",
1029
+ queryDefinition: "object — canonical QueryDefinition (without 'resource' — filled in from recordSlug). Supports 'where', 'sort', 'page', 'select', and a multi-collection 'joins[]' clause (max 4). The 'text' (full-text search) and 'include' (relation expansion) clauses are reserved on saved-query create/update/test surfaces and currently fail with 422 unsupported_clause — they are available on the ad-hoc 'POST /records/query' surface only. Variables are referenced as '${varName}' placeholders inside operator values.",
1030
+ variables: "Record<string, QueryVariableDefinition> | null — typed parameter declarations. Present on Phase 4 saved queries; null/absent on legacy untyped rows. See 'variable_declarations' below.",
1031
+ },
1032
+ query_definition_reference: "Use describe_records for the full QueryDefinition shape, operator vocabulary, and examples. Saved queries support 'where', 'sort', 'page', 'select', and a multi-collection 'joins[]' clause (see 'joins' below). Saved queries do NOT support 'text' or 'include' on this surface — those land on ad-hoc 'POST /records/query'.",
1033
+ joins: {
1034
+ description: "Multi-collection joins. Saved queries may include up to 4 joined collections (JOINS_MAX_LENGTH = 4). Each side is sourced from a tenancy-filtered subquery before the join, so wrong-tenant rows can never participate. Combining 'text' and 'joins' is rejected with 'unsupported_combination'; combining 'include' and 'joins' is also rejected with 'unsupported_combination'.",
1035
+ cap: 4,
1036
+ join_clause_shape: {
1037
+ foreignSlug: "string — the joined collection's record slug. LITERAL ONLY: '${var}' placeholders rejected (identifiers must be literal under SECURITY DEFINER auth).",
1038
+ localField: "string — field on primary; bare names ('id') target top-level columns, dotted ('data.customerId') targets JSONB. Chained joins may use '<priorAlias>.<field>' to reference a prior join's row. LITERAL ONLY: no '${var}' placeholders.",
1039
+ foreignField: "string — field on the joined collection (same dotted-vs-bare rules as localField). LITERAL ONLY: no '${var}' placeholders.",
1040
+ joinType: "'inner' | 'left' | 'right' | 'full' — required, no default. INNER and LEFT are always available. RIGHT and FULL OUTER are gated server-side by the 'DATA_QUERY_OUTER_JOINS_ENABLED' env flag; when off the executor returns 'unsupported_clause'. LITERAL ONLY: no '${var}' placeholders.",
1041
+ select: "string[] (optional) — projection on the joined row; defaults to all readable fields",
1042
+ alias: "string (optional) — logical alias used in '_joined[alias]' on response rows and as the 'priorAlias' for chained joins. Defaults to foreignSlug. REQUIRED when joining the same foreignSlug more than once in the same query. Must NOT equal the primary 'resource' or '_joined' (validator rejects with 'duplicate_join_alias'). LITERAL ONLY: no '${var}' placeholders.",
1043
+ },
1044
+ authorization: "SECURITY DEFINER (author-bound). Saved queries follow the SQL-view pattern — the AUTHOR's permissions define what the query can read; the executor only needs an 'execute' check on the saved-query resource at runtime. At AUTHOR time (create / update / test) the caller needs 'records:list' on the primary collection AND every collection referenced in 'joins[]'; the data service returns 403 if any access is missing. At EXECUTE time there is no per-collection re-check, and field-level redaction follows the author's permissions, not the executor's. AI assistants should not propose joined queries against collections the user can't read.",
1045
+ error_codes: [
1046
+ "joins_length_exceeded — more than 4 join entries",
1047
+ "duplicate_join_alias — same alias appears twice, OR alias equals primary 'resource', OR alias equals reserved '_joined'",
1048
+ "unsupported_combination — 'text' + 'joins', or 'include' + 'joins'",
1049
+ "unsupported_clause — joinType is 'right' or 'full' and 'DATA_QUERY_OUTER_JOINS_ENABLED' is off",
1050
+ "invalid_query — '${var}' placeholder in any identifier slot (foreignSlug / localField / foreignField / alias / joinType)",
1051
+ ],
1052
+ response_shape: "execute_saved_query returns '{ rows, meta, fields }'. Each entry in 'rows' carries '_joined': { [alias]: <joinedRow> | null } at the top level. LEFT and FULL joins surface 'null' for the joined alias when there is no match (phantom-foreign). RIGHT and FULL joins additionally surface PHANTOM-PRIMARY rows where the primary side has no match — every primary column ('id', 'data', 'createdAt', ...) is null and the joined alias carries the unmatched-foreign data. Consumers detect phantom rows by 'rows[i].id === null'.",
1053
+ example: {
1054
+ resource: "orders",
1055
+ where: { "data.status": { eq: "open" } },
1056
+ joins: [
1057
+ {
1058
+ foreignSlug: "customers",
1059
+ localField: "data.customerId",
1060
+ foreignField: "id",
1061
+ joinType: "left",
1062
+ select: ["id", "data.name", "data.email"],
1063
+ alias: "customer",
1064
+ },
1065
+ {
1066
+ foreignSlug: "regions",
1067
+ localField: "customer.data.regionId",
1068
+ foreignField: "id",
1069
+ joinType: "inner",
1070
+ alias: "region",
1071
+ },
1072
+ ],
1073
+ sort: [{ field: "createdAt", direction: "desc" }],
1074
+ page: { limit: 50 },
1075
+ },
1076
+ example_response_row: {
1077
+ id: "order-123",
1078
+ data: { status: "open", amount: 99.99 },
1079
+ createdAt: "2026-04-01T00:00:00Z",
1080
+ _joined: {
1081
+ customer: { id: "cust-1", data: { name: "Acme", email: "a@b.co" } },
1082
+ region: { id: "reg-1", data: { code: "us-east" } },
1083
+ },
1084
+ },
1003
1085
  },
1004
- query_definition_reference: "Use describe_records for the full QueryDefinition shape, operator vocabulary, and examples.",
1005
1086
  variable_syntax: {
1006
- description: "Variables use double-brace syntax: '{{variableName}}'. They appear inside operator values; the engine infers the variable list from the body and resolves substitutions at execution time. There is no separate variable declaration placeholders in the QueryDefinition are the source of truth.",
1087
+ description: "Phase 4 canonical syntax: '${variableName}'. Placeholders appear inside operator values; the server resolves substitutions and (when the row carries 'variables' declarations) validates each value against its declared type by JS typeof — there is no server-side coercion, so '\"123\"' is rejected for a 'number' declaration. 'datetime' accepts an ISO-8601 string. Legacy '{{varName}}' placeholders still work on pre-Phase-4 untyped rows during the deprecation window — every value is stringified before substitution. New saved queries should declare typed 'variables' and use '${varName}'.",
1007
1088
  example_query_definition: {
1008
1089
  where: {
1009
1090
  and: [
1010
- { "data.status": { eq: "{{statusFilter}}" } },
1011
- { "data.amount": { gte: "{{minAmount}}" } },
1091
+ { "data.status": { eq: "${statusFilter}" } },
1092
+ { "data.amount": { gte: "${minAmount}" } },
1012
1093
  ],
1013
1094
  },
1014
1095
  sort: [{ field: "createdAt", direction: "desc" }],
@@ -1018,45 +1099,67 @@ function registerDescribeTools(server) {
1018
1099
  statusFilter: "active",
1019
1100
  minAmount: 1000,
1020
1101
  },
1021
- note: "Pass values via the 'variables' arg on execute_smart_query / test_smart_query. Values are substituted before the engine validates the query.",
1102
+ note: "Pass values via the 'variables' arg on execute_saved_query the server validates against the saved query's declarations by JS typeof (no coercion; typed errors: 'variable_type_mismatch', 'missing_required_variable', 'extra_variable'). test_saved_query is unwired for typed dry-run today: it falls back to legacy string substitution and does not enforce typed declarations. Round-trip via create_saved_query + execute_saved_query for typed validation.",
1103
+ },
1104
+ variable_declarations: {
1105
+ description: "Each entry in the saved query's 'variables' map declares a typed parameter slot. Authors set this on create_saved_query / update_saved_query; the executor uses it to validate runtime values by JS typeof (no coercion).",
1106
+ shape: {
1107
+ type: "VariableType — 'string' | 'number' | 'boolean' | 'datetime' | 'id' | { array: VariableType } | { reference: '<collectionSlug>' }",
1108
+ required: "boolean (optional) — when true, the value must be supplied at execute time (or a 'default' must be set)",
1109
+ default: "scalar (optional) — used when the caller omits the value",
1110
+ description: "string (optional) — surfaced in tool descriptions and AI prompts",
1111
+ },
1112
+ example: {
1113
+ statusFilter: { type: "string", required: true, description: "Order status to filter by" },
1114
+ minAmount: { type: "number", default: 0 },
1115
+ since: { type: "datetime", required: true },
1116
+ customerIds: { type: { array: "id" } },
1117
+ ownerRef: { type: { reference: "users" } },
1118
+ },
1119
+ clearing_declarations: "Pass 'variables: null' on update_saved_query to clear declarations and revert the query to untyped string substitution.",
1022
1120
  },
1023
1121
  crud_tools: {
1024
- get_smart_query: {
1025
- description: "Get a saved query by ID, including its full canonical definition",
1122
+ get_saved_query: {
1123
+ description: "Get a saved query by ID, including its full canonical definition and typed 'variables' declarations.",
1026
1124
  required_params: ["recordSlug", "queryId"],
1027
1125
  },
1028
- create_smart_query: {
1029
- description: "Create a new saved query for a collection",
1126
+ create_saved_query: {
1127
+ description: "Create a new saved query for a collection. When 'variables' is provided, the canonical create path is used and every '${var}' in queryDefinition must be declared.",
1030
1128
  required_params: ["recordSlug", "name", "queryDefinition"],
1031
- optional_params: ["description"],
1129
+ optional_params: ["description", "variables"],
1032
1130
  queryDefinition_example: {
1033
- where: { "data.status": { eq: "active" } },
1131
+ where: { "data.status": { eq: "${statusFilter}" } },
1034
1132
  sort: [{ field: "createdAt", direction: "desc" }],
1035
1133
  page: { limit: 100 },
1036
1134
  },
1135
+ variables_example: {
1136
+ statusFilter: { type: "string", required: true },
1137
+ },
1037
1138
  },
1038
- update_smart_query: {
1039
- description: "Update an existing saved query. Partial updates supported.",
1139
+ update_saved_query: {
1140
+ description: "Update an existing saved query. Partial updates supported. Pass 'variables: null' to clear typed declarations.",
1040
1141
  required_params: ["recordSlug", "queryId"],
1041
- optional_params: ["name", "description", "queryDefinition"],
1142
+ optional_params: ["name", "description", "queryDefinition", "variables"],
1042
1143
  },
1043
- delete_smart_query: {
1144
+ delete_saved_query: {
1044
1145
  description: "Delete a saved query by ID",
1045
1146
  required_params: ["recordSlug", "queryId"],
1046
1147
  },
1047
- test_smart_query: {
1048
- description: "Test execute a canonical query definition without saving it. Preview results before creating.",
1148
+ test_saved_query: {
1149
+ description: "Test execute a canonical query definition without saving it. Note: typed 'variableDeclarations' dry-run is not yet wired on the server — use create_saved_query + execute_saved_query to validate typed parameters end-to-end.",
1049
1150
  required_params: ["recordSlug", "queryDefinition"],
1050
1151
  optional_params: ["variables"],
1051
1152
  },
1052
1153
  },
1053
1154
  tips: [
1054
- "Use list_smart_queries to discover available queries (optionally filter by collection slug)",
1055
- "Saved queries return the same canonical { data, meta } envelope as query_records",
1056
- "Variables are declared when creating the query — read the query's 'variables' field to see what's expected",
1155
+ "Use list_saved_queries to discover available queries (optionally filter by collection slug); each row's 'variables' field tells you what to pass",
1156
+ "execute_saved_query returns a { rows, meta, fields } envelope; joined data lives under 'rows[i]._joined' (LEFT/FULL surface 'null' under unmatched aliases; RIGHT/FULL also surface phantom-primary rows where rows[i].id === null and the joined alias carries the foreign-side data). The ad-hoc query_records tool returns the canonical { data, meta } shape they are not interchangeable",
1157
+ "Read the saved query's 'variables' map for type, required-ness, default, and description before calling execute_saved_query",
1057
1158
  "Prefer saved queries over ad-hoc query_records filters for reusable logic",
1058
- "Use test_smart_query to validate canonical syntax and preview results before saving",
1059
- "DO NOT author new saved queries with legacy '$'-prefixed operators ('$eq', '$gte', …). The data service still translates them server-side during the deprecation window, but new saved queries must use canonical operators ('eq', 'gte', …)",
1159
+ "test_saved_query previews canonical syntax + result rows but does not yet enforce typed declarations server-side — round-trip via create + execute_saved_query for typed validation",
1160
+ "DO NOT author new saved queries with legacy '$'-prefixed operators ('$eq', '$gte', …) or '{{var}}' placeholders. Both still translate during the deprecation window, but new saved queries must use canonical operators ('eq', 'gte', …) and '${var}' placeholders.",
1161
+ "For multi-collection reporting, use 'joins[]' (see top-level 'joins' field) — up to 4 joined collections; joinType is 'inner' | 'left' | 'right' | 'full' (RIGHT/FULL gated server-side by 'DATA_QUERY_OUTER_JOINS_ENABLED' — coordinate with ops if you need them). Joined rows arrive under '_joined[alias]' on each primary row. Identifiers ('foreignSlug', 'localField', 'foreignField', 'alias', 'joinType') are literal-only — no '${var}' placeholders. 'text' and 'joins' cannot be combined; 'include' and 'joins' cannot be combined either.",
1162
+ "Before authoring a join, confirm the user has 'records:list' on every joined collection — saved queries run under SECURITY DEFINER and the data service enforces author-time auth on the primary + every join.",
1060
1163
  ],
1061
1164
  }, null, 2),
1062
1165
  },
@@ -1540,12 +1643,12 @@ function registerDescribeTools(server) {
1540
1643
  "Set access policy with set_page_access_policy before publishing if you need auth",
1541
1644
  "Use variable bindings on data sources to scope data dynamically — bind to URL params, auth context, record context, or static defaults",
1542
1645
  "For list→detail navigation: set useQueryParams:true on navigate-to-page actions, then bind the detail page's data source variables to { source: 'url', param: 'id' }. Use config.paramMapping to rename fields if source and target use different names (e.g., { requestId: 'id' })",
1543
- "For user-scoped views (e.g., My Approvals): bind a variable to { source: 'auth', field: 'userId' } and use a smart query with {{assigneeId}}",
1646
+ "For user-scoped views (e.g., My Approvals): bind a variable to { source: 'auth', field: 'userId' } and use a smart query with '${assigneeId}'",
1544
1647
  ],
1545
1648
  multi_page_pattern: {
1546
1649
  description: "How to build a list→detail app with scoped related data",
1547
1650
  steps: [
1548
- "1. Create a smart query with {{variables}} for the detail page's related data (e.g., filter by {{requestId}})",
1651
+ "1. Create a smart query with '${variables}' for the detail page's related data (e.g., filter by '${requestId}')",
1549
1652
  "2. Create a list page with a data-table block and a navigate-to-page action: set config.useQueryParams:true, paramConfig: { source:'row', mode:'selected', selectedFields:['id'] }",
1550
1653
  "3. Create a detail page with: (a) a record-card block with mode:'single' and variables: { id: { source:'url', param:'id' } }, (b) a related-list block with dataSource type:'query', ref:smartQueryId, variables: { requestId: { source:'url', param:'id' } }",
1551
1654
  "4. Publish both pages. Clicking a row on the list navigates to /ws/detail-slug?id=rowId, and the detail page scopes all blocks to that ID.",
@@ -1617,7 +1720,7 @@ function registerDescribeTools(server) {
1617
1720
  filterableColumns: "string[] | null — which columns users can filter on (for data-table blocks)",
1618
1721
  },
1619
1722
  data_source_shape: {
1620
- type: "'structure' | 'query' — 'structure' fetches collection records directly, 'query' executes a smart query with {{variable}} substitution",
1723
+ type: "'structure' | 'query' — 'structure' fetches collection records directly, 'query' executes a smart query with '${variable}' substitution",
1621
1724
  ref: "string — the collection ID (for structure) or smart query ID (for query) — UUID",
1622
1725
  mode: "'list' | 'single' | 'aggregate' — optional. 'single' fetches one record (detail pages), 'list' fetches paginated records, 'aggregate' computes metrics",
1623
1726
  recordSlug: "string | undefined — the collection's record slug for direct resolution (avoids an extra lookup). Recommended for structure type.",
@@ -1638,7 +1741,7 @@ function registerDescribeTools(server) {
1638
1741
  static: "{ source: 'static', value: 'literalValue' } — a hardcoded default",
1639
1742
  },
1640
1743
  behavior: {
1641
- query_type: "For type:'query' — resolved variables substitute into smart query {{placeholders}} before execution",
1744
+ query_type: "For type:'query' — resolved variables substitute into smart query '${placeholders}' before execution",
1642
1745
  structure_type: "For type:'structure' — resolved variables become equality filters on the collection. IMPORTANT: the variable name 'id' is special — it matches the system record UUID (used for single-record fetch by ID). ALL OTHER variable names filter against user data fields and are automatically prefixed with 'data.' (e.g., variable 'requestId' filters on data.requestId in the JSONB column). System columns like createdAt, updatedAt, status do NOT get the data. prefix.",
1643
1746
  unresolved: "If any variable cannot be resolved, the block returns an empty result with a variableError message — NEVER unfiltered data",
1644
1747
  detail_page_pattern: "For a detail page: use variables: { id: { source: 'url', param: 'id' } } on the primary record-card block to fetch by system ID. For related-list blocks, use the actual data field name (e.g., variables: { requestId: { source: 'url', param: 'id' } }) — this filters related records where data.requestId matches the URL param. The 'id' variable fetches a record BY its UUID; other variable names filter records WHERE a field equals the value.",
@@ -29,10 +29,29 @@ declare function translateQueryRecordsArgs(args: QueryRecordsArgs): {
29
29
  resource: string;
30
30
  definition: Record<string, unknown>;
31
31
  };
32
+ /**
33
+ * Client-side `${var}` substitution for ad-hoc `query_records`. MCP agents
34
+ * often template queries (e.g. `${userId}` from prior tool output) — this
35
+ * helper resolves those placeholders before sending the body to the
36
+ * canonical `/records/query` endpoint, which has no native variable
37
+ * substitution.
38
+ *
39
+ * Behavior:
40
+ * - Replaces every `${name}` occurrence inside string values.
41
+ * - When the entire string is a single placeholder (e.g. `"${ids}"`), the
42
+ * value is replaced with the typed value as-is so arrays / numbers /
43
+ * booleans round-trip without being stringified.
44
+ * - Throws `Error("missing_required_variable: <name>")` when a placeholder
45
+ * references a variable that wasn't supplied — the caller surfaces the
46
+ * same code the executor uses for typed saved queries (contract §10).
47
+ * - Walks objects + arrays recursively; leaves non-strings untouched.
48
+ */
49
+ declare function substituteCanonicalVariables(node: unknown, values: Record<string, unknown>): unknown;
32
50
  export declare const _internal: {
33
51
  translateQueryRecordsArgs: typeof translateQueryRecordsArgs;
34
52
  parseLegacyFilters: typeof parseLegacyFilters;
35
53
  parseLegacySort: typeof parseLegacySort;
54
+ substituteCanonicalVariables: typeof substituteCanonicalVariables;
36
55
  };
37
56
  export declare function registerRecordTools(server: McpServer, sdk: CentraliSDK, centraliUrl: string, workspaceId: string): void;
38
57
  export {};