@centrali-io/centrali-mcp 5.5.0 → 6.0.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 +104 -10
- package/dist/index.js +2 -2
- package/dist/tools/describe.js +116 -40
- package/dist/tools/records.d.ts +19 -0
- package/dist/tools/records.js +91 -5
- package/dist/tools/saved-queries.d.ts +14 -0
- package/dist/tools/saved-queries.js +457 -0
- package/package.json +2 -2
- package/src/index.ts +2 -2
- package/src/tools/describe.ts +130 -41
- package/src/tools/records.ts +90 -5
- package/src/tools/saved-queries.ts +497 -0
- package/tests/savedQueriesRouting.test.cjs +148 -0
- package/tests/typedVariables.test.cjs +113 -0
- package/dist/tools/smart-queries.d.ts +0 -3
- package/dist/tools/smart-queries.js +0 -249
- package/src/tools/smart-queries.ts +0 -284
package/src/tools/describe.ts
CHANGED
|
@@ -91,16 +91,16 @@ export function registerDescribeTools(server: McpServer) {
|
|
|
91
91
|
},
|
|
92
92
|
smart_queries: {
|
|
93
93
|
summary:
|
|
94
|
-
"Reusable, parameterized queries defined in the console. Support {
|
|
95
|
-
describeWith: "
|
|
94
|
+
"Reusable, parameterized queries defined in the console. Support typed '${variable}' substitution and multi-collection joins (up to 4 joined collections per query).",
|
|
95
|
+
describeWith: "describe_saved_queries",
|
|
96
96
|
tools: [
|
|
97
|
-
"
|
|
98
|
-
"
|
|
99
|
-
"
|
|
100
|
-
"
|
|
101
|
-
"
|
|
102
|
-
"
|
|
103
|
-
"
|
|
97
|
+
"list_saved_queries",
|
|
98
|
+
"get_saved_query",
|
|
99
|
+
"create_saved_query",
|
|
100
|
+
"update_saved_query",
|
|
101
|
+
"delete_saved_query",
|
|
102
|
+
"execute_saved_query",
|
|
103
|
+
"test_saved_query",
|
|
104
104
|
],
|
|
105
105
|
},
|
|
106
106
|
orchestrations: {
|
|
@@ -1061,11 +1061,11 @@ export function registerDescribeTools(server: McpServer) {
|
|
|
1061
1061
|
})
|
|
1062
1062
|
);
|
|
1063
1063
|
|
|
1064
|
-
// ──
|
|
1064
|
+
// ── Saved Queries ──────────────────────────────────────────────────
|
|
1065
1065
|
|
|
1066
1066
|
registerTool<any>(server,
|
|
1067
|
-
"
|
|
1068
|
-
"Get the schema reference for Centrali saved
|
|
1067
|
+
"describe_saved_queries",
|
|
1068
|
+
"Get the schema reference for Centrali saved queries. Explains the canonical QueryDefinition body, variable substitution, and execution.",
|
|
1069
1069
|
{},
|
|
1070
1070
|
async () => ({
|
|
1071
1071
|
content: [
|
|
@@ -1073,27 +1073,91 @@ export function registerDescribeTools(server: McpServer) {
|
|
|
1073
1073
|
type: "text",
|
|
1074
1074
|
text: JSON.stringify(
|
|
1075
1075
|
{
|
|
1076
|
-
domain: "Saved Queries
|
|
1076
|
+
domain: "Saved Queries",
|
|
1077
1077
|
description:
|
|
1078
|
-
"Saved queries are reusable, parameterized queries defined in the Centrali console. They store a canonical QueryDefinition plus optional variable declarations and
|
|
1078
|
+
"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.",
|
|
1079
1079
|
saved_query_shape: {
|
|
1080
1080
|
id: "UUID",
|
|
1081
1081
|
name: "string — display name",
|
|
1082
1082
|
recordSlug: "string — the collection this query targets",
|
|
1083
1083
|
description: "string | null",
|
|
1084
1084
|
queryDefinition:
|
|
1085
|
-
"object — canonical QueryDefinition (without 'resource' — filled in from recordSlug). Variables are referenced as '{
|
|
1085
|
+
"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.",
|
|
1086
|
+
variables:
|
|
1087
|
+
"Record<string, QueryVariableDefinition> | null — typed parameter declarations. Present on Phase 4 saved queries; null/absent on legacy untyped rows. See 'variable_declarations' below.",
|
|
1086
1088
|
},
|
|
1087
1089
|
query_definition_reference:
|
|
1088
|
-
"Use describe_records for the full QueryDefinition shape, operator vocabulary, and examples.",
|
|
1090
|
+
"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'.",
|
|
1091
|
+
joins: {
|
|
1092
|
+
description:
|
|
1093
|
+
"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'.",
|
|
1094
|
+
cap: 4,
|
|
1095
|
+
join_clause_shape: {
|
|
1096
|
+
foreignSlug:
|
|
1097
|
+
"string — the joined collection's record slug. LITERAL ONLY: '${var}' placeholders rejected (identifiers must be literal under SECURITY DEFINER auth).",
|
|
1098
|
+
localField:
|
|
1099
|
+
"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.",
|
|
1100
|
+
foreignField:
|
|
1101
|
+
"string — field on the joined collection (same dotted-vs-bare rules as localField). LITERAL ONLY: no '${var}' placeholders.",
|
|
1102
|
+
joinType:
|
|
1103
|
+
"'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.",
|
|
1104
|
+
select:
|
|
1105
|
+
"string[] (optional) — projection on the joined row; defaults to all readable fields",
|
|
1106
|
+
alias:
|
|
1107
|
+
"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.",
|
|
1108
|
+
},
|
|
1109
|
+
authorization:
|
|
1110
|
+
"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.",
|
|
1111
|
+
error_codes: [
|
|
1112
|
+
"joins_length_exceeded — more than 4 join entries",
|
|
1113
|
+
"duplicate_join_alias — same alias appears twice, OR alias equals primary 'resource', OR alias equals reserved '_joined'",
|
|
1114
|
+
"unsupported_combination — 'text' + 'joins', or 'include' + 'joins'",
|
|
1115
|
+
"unsupported_clause — joinType is 'right' or 'full' and 'DATA_QUERY_OUTER_JOINS_ENABLED' is off",
|
|
1116
|
+
"invalid_query — '${var}' placeholder in any identifier slot (foreignSlug / localField / foreignField / alias / joinType)",
|
|
1117
|
+
],
|
|
1118
|
+
response_shape:
|
|
1119
|
+
"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'.",
|
|
1120
|
+
example: {
|
|
1121
|
+
resource: "orders",
|
|
1122
|
+
where: { "data.status": { eq: "open" } },
|
|
1123
|
+
joins: [
|
|
1124
|
+
{
|
|
1125
|
+
foreignSlug: "customers",
|
|
1126
|
+
localField: "data.customerId",
|
|
1127
|
+
foreignField: "id",
|
|
1128
|
+
joinType: "left",
|
|
1129
|
+
select: ["id", "data.name", "data.email"],
|
|
1130
|
+
alias: "customer",
|
|
1131
|
+
},
|
|
1132
|
+
{
|
|
1133
|
+
foreignSlug: "regions",
|
|
1134
|
+
localField: "customer.data.regionId",
|
|
1135
|
+
foreignField: "id",
|
|
1136
|
+
joinType: "inner",
|
|
1137
|
+
alias: "region",
|
|
1138
|
+
},
|
|
1139
|
+
],
|
|
1140
|
+
sort: [{ field: "createdAt", direction: "desc" }],
|
|
1141
|
+
page: { limit: 50 },
|
|
1142
|
+
},
|
|
1143
|
+
example_response_row: {
|
|
1144
|
+
id: "order-123",
|
|
1145
|
+
data: { status: "open", amount: 99.99 },
|
|
1146
|
+
createdAt: "2026-04-01T00:00:00Z",
|
|
1147
|
+
_joined: {
|
|
1148
|
+
customer: { id: "cust-1", data: { name: "Acme", email: "a@b.co" } },
|
|
1149
|
+
region: { id: "reg-1", data: { code: "us-east" } },
|
|
1150
|
+
},
|
|
1151
|
+
},
|
|
1152
|
+
},
|
|
1089
1153
|
variable_syntax: {
|
|
1090
1154
|
description:
|
|
1091
|
-
"
|
|
1155
|
+
"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}'.",
|
|
1092
1156
|
example_query_definition: {
|
|
1093
1157
|
where: {
|
|
1094
1158
|
and: [
|
|
1095
|
-
{ "data.status": { eq: "{
|
|
1096
|
-
{ "data.amount": { gte: "{
|
|
1159
|
+
{ "data.status": { eq: "${statusFilter}" } },
|
|
1160
|
+
{ "data.amount": { gte: "${minAmount}" } },
|
|
1097
1161
|
],
|
|
1098
1162
|
},
|
|
1099
1163
|
sort: [{ field: "createdAt", direction: "desc" }],
|
|
@@ -1103,45 +1167,70 @@ export function registerDescribeTools(server: McpServer) {
|
|
|
1103
1167
|
statusFilter: "active",
|
|
1104
1168
|
minAmount: 1000,
|
|
1105
1169
|
},
|
|
1106
|
-
note: "Pass values via the 'variables' arg on
|
|
1170
|
+
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.",
|
|
1171
|
+
},
|
|
1172
|
+
variable_declarations: {
|
|
1173
|
+
description:
|
|
1174
|
+
"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).",
|
|
1175
|
+
shape: {
|
|
1176
|
+
type:
|
|
1177
|
+
"VariableType — 'string' | 'number' | 'boolean' | 'datetime' | 'id' | { array: VariableType } | { reference: '<collectionSlug>' }",
|
|
1178
|
+
required: "boolean (optional) — when true, the value must be supplied at execute time (or a 'default' must be set)",
|
|
1179
|
+
default: "scalar (optional) — used when the caller omits the value",
|
|
1180
|
+
description: "string (optional) — surfaced in tool descriptions and AI prompts",
|
|
1181
|
+
},
|
|
1182
|
+
example: {
|
|
1183
|
+
statusFilter: { type: "string", required: true, description: "Order status to filter by" },
|
|
1184
|
+
minAmount: { type: "number", default: 0 },
|
|
1185
|
+
since: { type: "datetime", required: true },
|
|
1186
|
+
customerIds: { type: { array: "id" } },
|
|
1187
|
+
ownerRef: { type: { reference: "users" } },
|
|
1188
|
+
},
|
|
1189
|
+
clearing_declarations:
|
|
1190
|
+
"Pass 'variables: null' on update_saved_query to clear declarations and revert the query to untyped string substitution.",
|
|
1107
1191
|
},
|
|
1108
1192
|
crud_tools: {
|
|
1109
|
-
|
|
1110
|
-
description: "Get a saved query by ID, including its full canonical definition",
|
|
1193
|
+
get_saved_query: {
|
|
1194
|
+
description: "Get a saved query by ID, including its full canonical definition and typed 'variables' declarations.",
|
|
1111
1195
|
required_params: ["recordSlug", "queryId"],
|
|
1112
1196
|
},
|
|
1113
|
-
|
|
1114
|
-
description: "Create a new saved query for a collection",
|
|
1197
|
+
create_saved_query: {
|
|
1198
|
+
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.",
|
|
1115
1199
|
required_params: ["recordSlug", "name", "queryDefinition"],
|
|
1116
|
-
optional_params: ["description"],
|
|
1200
|
+
optional_params: ["description", "variables"],
|
|
1117
1201
|
queryDefinition_example: {
|
|
1118
|
-
where: { "data.status": { eq: "
|
|
1202
|
+
where: { "data.status": { eq: "${statusFilter}" } },
|
|
1119
1203
|
sort: [{ field: "createdAt", direction: "desc" }],
|
|
1120
1204
|
page: { limit: 100 },
|
|
1121
1205
|
},
|
|
1206
|
+
variables_example: {
|
|
1207
|
+
statusFilter: { type: "string", required: true },
|
|
1208
|
+
},
|
|
1122
1209
|
},
|
|
1123
|
-
|
|
1124
|
-
description: "Update an existing saved query. Partial updates supported.",
|
|
1210
|
+
update_saved_query: {
|
|
1211
|
+
description: "Update an existing saved query. Partial updates supported. Pass 'variables: null' to clear typed declarations.",
|
|
1125
1212
|
required_params: ["recordSlug", "queryId"],
|
|
1126
|
-
optional_params: ["name", "description", "queryDefinition"],
|
|
1213
|
+
optional_params: ["name", "description", "queryDefinition", "variables"],
|
|
1127
1214
|
},
|
|
1128
|
-
|
|
1215
|
+
delete_saved_query: {
|
|
1129
1216
|
description: "Delete a saved query by ID",
|
|
1130
1217
|
required_params: ["recordSlug", "queryId"],
|
|
1131
1218
|
},
|
|
1132
|
-
|
|
1133
|
-
description: "Test execute a canonical query definition without saving it.
|
|
1219
|
+
test_saved_query: {
|
|
1220
|
+
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.",
|
|
1134
1221
|
required_params: ["recordSlug", "queryDefinition"],
|
|
1135
1222
|
optional_params: ["variables"],
|
|
1136
1223
|
},
|
|
1137
1224
|
},
|
|
1138
1225
|
tips: [
|
|
1139
|
-
"Use
|
|
1140
|
-
"
|
|
1141
|
-
"
|
|
1226
|
+
"Use list_saved_queries to discover available queries (optionally filter by collection slug); each row's 'variables' field tells you what to pass",
|
|
1227
|
+
"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",
|
|
1228
|
+
"Read the saved query's 'variables' map for type, required-ness, default, and description before calling execute_saved_query",
|
|
1142
1229
|
"Prefer saved queries over ad-hoc query_records filters for reusable logic",
|
|
1143
|
-
"
|
|
1144
|
-
"DO NOT author new saved queries with legacy '$'-prefixed operators ('$eq', '$gte', …)
|
|
1230
|
+
"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",
|
|
1231
|
+
"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.",
|
|
1232
|
+
"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.",
|
|
1233
|
+
"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.",
|
|
1145
1234
|
],
|
|
1146
1235
|
},
|
|
1147
1236
|
null,
|
|
@@ -1714,12 +1803,12 @@ export function registerDescribeTools(server: McpServer) {
|
|
|
1714
1803
|
"Set access policy with set_page_access_policy before publishing if you need auth",
|
|
1715
1804
|
"Use variable bindings on data sources to scope data dynamically — bind to URL params, auth context, record context, or static defaults",
|
|
1716
1805
|
"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' })",
|
|
1717
|
-
"For user-scoped views (e.g., My Approvals): bind a variable to { source: 'auth', field: 'userId' } and use a smart query with {
|
|
1806
|
+
"For user-scoped views (e.g., My Approvals): bind a variable to { source: 'auth', field: 'userId' } and use a smart query with '${assigneeId}'",
|
|
1718
1807
|
],
|
|
1719
1808
|
multi_page_pattern: {
|
|
1720
1809
|
description: "How to build a list→detail app with scoped related data",
|
|
1721
1810
|
steps: [
|
|
1722
|
-
"1. Create a smart query with {
|
|
1811
|
+
"1. Create a smart query with '${variables}' for the detail page's related data (e.g., filter by '${requestId}')",
|
|
1723
1812
|
"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'] }",
|
|
1724
1813
|
"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' } }",
|
|
1725
1814
|
"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.",
|
|
@@ -1816,7 +1905,7 @@ export function registerDescribeTools(server: McpServer) {
|
|
|
1816
1905
|
"string[] | null — which columns users can filter on (for data-table blocks)",
|
|
1817
1906
|
},
|
|
1818
1907
|
data_source_shape: {
|
|
1819
|
-
type: "'structure' | 'query' — 'structure' fetches collection records directly, 'query' executes a smart query with {
|
|
1908
|
+
type: "'structure' | 'query' — 'structure' fetches collection records directly, 'query' executes a smart query with '${variable}' substitution",
|
|
1820
1909
|
ref: "string — the collection ID (for structure) or smart query ID (for query) — UUID",
|
|
1821
1910
|
mode: "'list' | 'single' | 'aggregate' — optional. 'single' fetches one record (detail pages), 'list' fetches paginated records, 'aggregate' computes metrics",
|
|
1822
1911
|
recordSlug: "string | undefined — the collection's record slug for direct resolution (avoids an extra lookup). Recommended for structure type.",
|
|
@@ -1837,7 +1926,7 @@ export function registerDescribeTools(server: McpServer) {
|
|
|
1837
1926
|
static: "{ source: 'static', value: 'literalValue' } — a hardcoded default",
|
|
1838
1927
|
},
|
|
1839
1928
|
behavior: {
|
|
1840
|
-
query_type: "For type:'query' — resolved variables substitute into smart query {
|
|
1929
|
+
query_type: "For type:'query' — resolved variables substitute into smart query '${placeholders}' before execution",
|
|
1841
1930
|
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.",
|
|
1842
1931
|
unresolved: "If any variable cannot be resolved, the block returns an empty result with a variableError message — NEVER unfiltered data",
|
|
1843
1932
|
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.",
|
package/src/tools/records.ts
CHANGED
|
@@ -182,8 +182,66 @@ function translateQueryRecordsArgs(args: QueryRecordsArgs): {
|
|
|
182
182
|
return { resource, definition };
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Client-side `${var}` substitution for ad-hoc `query_records`. MCP agents
|
|
187
|
+
* often template queries (e.g. `${userId}` from prior tool output) — this
|
|
188
|
+
* helper resolves those placeholders before sending the body to the
|
|
189
|
+
* canonical `/records/query` endpoint, which has no native variable
|
|
190
|
+
* substitution.
|
|
191
|
+
*
|
|
192
|
+
* Behavior:
|
|
193
|
+
* - Replaces every `${name}` occurrence inside string values.
|
|
194
|
+
* - When the entire string is a single placeholder (e.g. `"${ids}"`), the
|
|
195
|
+
* value is replaced with the typed value as-is so arrays / numbers /
|
|
196
|
+
* booleans round-trip without being stringified.
|
|
197
|
+
* - Throws `Error("missing_required_variable: <name>")` when a placeholder
|
|
198
|
+
* references a variable that wasn't supplied — the caller surfaces the
|
|
199
|
+
* same code the executor uses for typed saved queries (contract §10).
|
|
200
|
+
* - Walks objects + arrays recursively; leaves non-strings untouched.
|
|
201
|
+
*/
|
|
202
|
+
function substituteCanonicalVariables(
|
|
203
|
+
node: unknown,
|
|
204
|
+
values: Record<string, unknown>
|
|
205
|
+
): unknown {
|
|
206
|
+
if (node == null) return node;
|
|
207
|
+
if (typeof node === "string") {
|
|
208
|
+
const wholeRe = /^\s*\$\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\s*$/;
|
|
209
|
+
const wholeMatch = node.match(wholeRe);
|
|
210
|
+
if (wholeMatch) {
|
|
211
|
+
const name = wholeMatch[1];
|
|
212
|
+
if (!(name in values)) {
|
|
213
|
+
throw new Error(`missing_required_variable: ${name}`);
|
|
214
|
+
}
|
|
215
|
+
return values[name];
|
|
216
|
+
}
|
|
217
|
+
return node.replace(/\$\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g, (_match, name: string) => {
|
|
218
|
+
if (!(name in values)) {
|
|
219
|
+
throw new Error(`missing_required_variable: ${name}`);
|
|
220
|
+
}
|
|
221
|
+
const v = values[name];
|
|
222
|
+
return v == null ? "" : String(v);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
if (Array.isArray(node)) {
|
|
226
|
+
return node.map((item) => substituteCanonicalVariables(item, values));
|
|
227
|
+
}
|
|
228
|
+
if (typeof node === "object") {
|
|
229
|
+
const out: Record<string, unknown> = {};
|
|
230
|
+
for (const [k, v] of Object.entries(node as Record<string, unknown>)) {
|
|
231
|
+
out[k] = substituteCanonicalVariables(v, values);
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
return node;
|
|
236
|
+
}
|
|
237
|
+
|
|
185
238
|
// Exposed for tests
|
|
186
|
-
export const _internal = {
|
|
239
|
+
export const _internal = {
|
|
240
|
+
translateQueryRecordsArgs,
|
|
241
|
+
parseLegacyFilters,
|
|
242
|
+
parseLegacySort,
|
|
243
|
+
substituteCanonicalVariables,
|
|
244
|
+
};
|
|
187
245
|
/**
|
|
188
246
|
* Ensures the SDK has a valid token.
|
|
189
247
|
*/
|
|
@@ -261,6 +319,8 @@ Example body:
|
|
|
261
319
|
"select": { "fields": ["id", "data.status", "data.amount"] }
|
|
262
320
|
}
|
|
263
321
|
|
|
322
|
+
Templating: any string operator value may reference '\${variableName}' placeholders; pass concrete values via the 'variables' arg and the placeholders are substituted before the query hits the engine. When a string is exactly one placeholder ('\${ids}'), the value passes through untyped (so arrays / numbers / booleans round-trip without stringification).
|
|
323
|
+
|
|
264
324
|
Returns the canonical { data, meta } envelope. 'select', 'text', and 'include' are all accepted by the engine.`,
|
|
265
325
|
{
|
|
266
326
|
// Canonical fields (Phase 1)
|
|
@@ -301,9 +361,22 @@ Returns the canonical { data, meta } envelope. 'select', 'text', and 'include' a
|
|
|
301
361
|
.optional()
|
|
302
362
|
.describe("Field projection. Example: { fields: ['id', 'data.status'] }."),
|
|
303
363
|
include: z
|
|
304
|
-
.array(
|
|
364
|
+
.array(
|
|
365
|
+
z
|
|
366
|
+
.object({
|
|
367
|
+
relation: z.string(),
|
|
368
|
+
where: z.any().optional(),
|
|
369
|
+
select: z
|
|
370
|
+
.object({ fields: z.array(z.string()) })
|
|
371
|
+
.optional(),
|
|
372
|
+
include: z.any().optional(),
|
|
373
|
+
})
|
|
374
|
+
.passthrough(),
|
|
375
|
+
)
|
|
305
376
|
.optional()
|
|
306
|
-
.describe(
|
|
377
|
+
.describe(
|
|
378
|
+
"Relation expansion. Each entry names a relation declared on the collection and may carry an optional `where` (filter on the included rows in the target's namespace), `select` (projection on the attached row), and recursive `include` children."
|
|
379
|
+
),
|
|
307
380
|
|
|
308
381
|
// Legacy 5.4.0 fields — accepted, translated to canonical, removed after 2026-10-28
|
|
309
382
|
recordSlug: z
|
|
@@ -342,13 +415,25 @@ Returns the canonical { data, meta } envelope. 'select', 'text', and 'include' a
|
|
|
342
415
|
.boolean()
|
|
343
416
|
.optional()
|
|
344
417
|
.describe("[Deprecated 2026-10-28] Ignored — `meta.total` is always returned for offset pagination."),
|
|
418
|
+
|
|
419
|
+
// Templating
|
|
420
|
+
variables: z
|
|
421
|
+
.record(z.string(), z.any())
|
|
422
|
+
.optional()
|
|
423
|
+
.describe(
|
|
424
|
+
"Values bound to '\${varName}' placeholders inside string operator values. Substituted client-side before the query hits the engine. Whole-string placeholders ('\${ids}') round-trip the typed value without stringification."
|
|
425
|
+
),
|
|
345
426
|
},
|
|
346
427
|
async (args) => {
|
|
347
428
|
let resource = "<unknown>";
|
|
348
429
|
try {
|
|
349
|
-
const
|
|
430
|
+
const { variables, ...rest } = args as QueryRecordsArgs & { variables?: Record<string, unknown> };
|
|
431
|
+
const translated = translateQueryRecordsArgs(rest as QueryRecordsArgs);
|
|
350
432
|
resource = translated.resource;
|
|
351
|
-
const
|
|
433
|
+
const finalDefinition = variables
|
|
434
|
+
? (substituteCanonicalVariables(translated.definition, variables) as Record<string, unknown>)
|
|
435
|
+
: translated.definition;
|
|
436
|
+
const result = await sdk.records.query(resource, finalDefinition as any);
|
|
352
437
|
return {
|
|
353
438
|
content: [
|
|
354
439
|
{ type: "text", text: JSON.stringify(result, null, 2) },
|