@centrali-io/centrali-mcp 6.17.0 → 8.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.
@@ -1,615 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { CentraliSDK } from "@centrali-io/centrali-sdk";
3
- import { z } from "zod";
4
- import { registerTool, formatError } from "./_register.js";
5
- import axios, { AxiosInstance } from "axios";
6
-
7
- /**
8
- * Derives the pages API base URL from the CENTRALI_URL.
9
- * Pattern: https://centrali.io -> https://api.centrali.io/pages
10
- * Or uses CENTRALI_PAGES_URL env var if explicitly set.
11
- */
12
- function getPagesBaseUrl(centraliUrl: string): string {
13
- const override = process.env.CENTRALI_PAGES_URL;
14
- if (override) return override.replace(/\/$/, "");
15
-
16
- const url = new URL(centraliUrl);
17
- const hostname = url.hostname.startsWith("api.")
18
- ? url.hostname
19
- : `api.${url.hostname}`;
20
- return `${url.protocol}//${hostname}/pages`;
21
- }
22
-
23
- /**
24
- * Ensures the SDK has a valid token by making a lightweight SDK call.
25
- * The SDK's internal axios interceptor handles client-credentials token
26
- * fetch and 401 refresh automatically — we just need to trigger it.
27
- */
28
- async function ensureToken(sdk: CentraliSDK): Promise<string | null> {
29
- let token = sdk.getToken();
30
- if (token) return token;
31
-
32
- // Token not yet fetched — trigger the SDK's internal auth flow
33
- // by making a lightweight call. The SDK will fetch and cache the token.
34
- try {
35
- await sdk.functions.list({ limit: 1 });
36
- } catch {
37
- // Ignore errors — we only need the token refresh side effect
38
- }
39
- return sdk.getToken();
40
- }
41
-
42
- /**
43
- * Creates an axios instance for the pages API that uses the SDK's token.
44
- * Auth is handled through the SDK's public getToken() API — no internal casting.
45
- */
46
- function createPagesClient(sdk: CentraliSDK, centraliUrl: string, workspaceId: string): {
47
- client: AxiosInstance;
48
- workspaceId: string;
49
- } {
50
- const baseURL = getPagesBaseUrl(centraliUrl);
51
- const client = axios.create({ baseURL, proxy: false });
52
-
53
- // Attach the SDK's bearer token to every request
54
- client.interceptors.request.use(async (config) => {
55
- const token = await ensureToken(sdk);
56
- if (token) {
57
- config.headers.Authorization = `Bearer ${token}`;
58
- }
59
- return config;
60
- });
61
-
62
- // Retry on 401/403 after refreshing the token via the SDK
63
- client.interceptors.response.use(
64
- (response) => response,
65
- async (error) => {
66
- const originalRequest = error.config;
67
- const isAuthError = error.response?.status === 401 || error.response?.status === 403;
68
-
69
- if (isAuthError && !originalRequest._hasRetried) {
70
- originalRequest._hasRetried = true;
71
-
72
- // Force a fresh token by making an SDK call (triggers internal 401 refresh)
73
- try {
74
- await sdk.functions.list({ limit: 1 });
75
- } catch {
76
- // Ignore — we only need the token refresh side effect
77
- }
78
-
79
- const token = sdk.getToken();
80
- if (token) {
81
- originalRequest.headers.Authorization = `Bearer ${token}`;
82
- return client.request(originalRequest);
83
- }
84
- }
85
-
86
- return Promise.reject(error);
87
- }
88
- );
89
-
90
- return { client, workspaceId };
91
- }
92
-
93
- export function registerPageTools(
94
- server: McpServer,
95
- sdk: CentraliSDK,
96
- centraliUrl: string,
97
- workspaceId: string
98
- ) {
99
- const { client } = createPagesClient(sdk, centraliUrl, workspaceId);
100
- const basePath = `/ws/${workspaceId}/api/v1/pages`;
101
-
102
- // ── Page CRUD ──────────────────────────────────────────────────────
103
-
104
- registerTool<any>(server,
105
- "list_pages",
106
- "List all pages in the workspace. Pages are pre-built UI views (lists, detail views, forms, dashboards) that surface data from collections.",
107
- {
108
- page: z.number().optional().describe("Page number (1-indexed, default: 1)"),
109
- pageSize: z.number().optional().describe("Items per page (default: 20)"),
110
- pageType: z
111
- .enum(["list", "detail", "form", "dashboard"])
112
- .optional()
113
- .describe("Filter by page type"),
114
- },
115
- async ({ page, pageSize, pageType }) => {
116
- try {
117
- const params: Record<string, any> = {};
118
- if (page !== undefined) params.page = page;
119
- if (pageSize !== undefined) params.pageSize = pageSize;
120
- if (pageType) params.pageType = pageType;
121
-
122
- const resp = await client.get(basePath, { params });
123
- return {
124
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
125
- };
126
- } catch (error) {
127
- return {
128
- content: [{ type: "text", text: formatError(error, "listing pages") }],
129
- isError: true,
130
- };
131
- }
132
- }
133
- );
134
-
135
- registerTool<any>(server,
136
- "get_page",
137
- "Get a page by its ID. Returns the page metadata including name, slug, type, and description.",
138
- {
139
- pageId: z.string().describe("The page ID (UUID)"),
140
- },
141
- async ({ pageId }) => {
142
- try {
143
- const resp = await client.get(`${basePath}/${pageId}`);
144
- return {
145
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
146
- };
147
- } catch (error) {
148
- return {
149
- content: [{ type: "text", text: formatError(error, `getting page '${pageId}'`) }],
150
- isError: true,
151
- };
152
- }
153
- }
154
- );
155
-
156
- registerTool<any>(server,
157
- "create_page",
158
- `Create a new page in the workspace. A page is a UI view backed by data from collections. Specify the page type: 'list' for data tables, 'detail' for single-record views, 'form' for data entry, 'dashboard' for metrics and charts.
159
-
160
- Navigate-to-page actions can use config.useQueryParams: true to pass selected row fields as URL query params to the target page. Pair with paramConfig: { source: 'row', mode: 'selected', selectedFields: ['id'] } to control which fields are passed. Use config.paramMapping: { sourceField: 'targetParam' } to rename fields in the URL (e.g., { requestId: 'id' } passes ?id=<value> instead of ?requestId=<value>). The target detail page can then use variable bindings with { source: 'url', param: 'id' } to read those params.`,
161
- {
162
- name: z.string().describe("Display name for the page (e.g., 'Customer List')"),
163
- slug: z.string().describe("URL-safe slug (e.g., 'customer-list')"),
164
- pageType: z
165
- .enum(["list", "detail", "form", "dashboard"])
166
- .describe("The type of page to create"),
167
- description: z.string().optional().describe("Optional description of the page's purpose"),
168
- },
169
- async ({ name, slug, pageType, description }) => {
170
- try {
171
- const resp = await client.post(basePath, { name, slug, pageType, description });
172
- return {
173
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
174
- };
175
- } catch (error) {
176
- return {
177
- content: [{ type: "text", text: formatError(error, "creating page") }],
178
- isError: true,
179
- };
180
- }
181
- }
182
- );
183
-
184
- registerTool<any>(server,
185
- "update_page",
186
- "Update a page's metadata (name, slug, description). Does not modify the page definition — use save_page_draft for that.",
187
- {
188
- pageId: z.string().describe("The page ID (UUID) to update"),
189
- name: z.string().optional().describe("New display name"),
190
- slug: z.string().optional().describe("New URL slug"),
191
- description: z.string().optional().describe("New description"),
192
- showInNavShell: z.boolean().optional().describe("Whether to show this page in the navigation shell"),
193
- },
194
- async ({ pageId, name, slug, description, showInNavShell }) => {
195
- try {
196
- const body: Record<string, any> = {};
197
- if (name !== undefined) body.name = name;
198
- if (slug !== undefined) body.slug = slug;
199
- if (description !== undefined) body.description = description;
200
- if (showInNavShell !== undefined) body.showInNavShell = showInNavShell;
201
-
202
- const resp = await client.patch(`${basePath}/${pageId}`, body);
203
- return {
204
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
205
- };
206
- } catch (error) {
207
- return {
208
- content: [{ type: "text", text: formatError(error, `updating page '${pageId}'`) }],
209
- isError: true,
210
- };
211
- }
212
- }
213
- );
214
-
215
- registerTool<any>(server,
216
- "delete_page",
217
- "Soft-delete a page by its ID. The page will no longer be accessible but can potentially be restored.",
218
- {
219
- pageId: z.string().describe("The page ID (UUID) to delete"),
220
- },
221
- async ({ pageId }) => {
222
- try {
223
- await client.delete(`${basePath}/${pageId}`);
224
- return {
225
- content: [{ type: "text", text: `Page '${pageId}' deleted successfully.` }],
226
- };
227
- } catch (error) {
228
- return {
229
- content: [{ type: "text", text: formatError(error, `deleting page '${pageId}'`) }],
230
- isError: true,
231
- };
232
- }
233
- }
234
- );
235
-
236
- // ── Drafts & Versions ─────────────────────────────────────────────
237
-
238
- registerTool<any>(server,
239
- "save_page_draft",
240
- `Save or update the draft definition for a page. The definition describes the page's layout: sections, blocks, data sources, actions, and presentation. This does NOT publish the page — use publish_page after saving.
241
-
242
- Each block's dataSource can include an optional 'variables' map for runtime variable binding:
243
- variables: { [varName]: { source, param?, field?, value? } }
244
-
245
- Variable binding sources:
246
- - { source: 'url', param: 'id' } — read from URL query param
247
- - { source: 'auth', field: 'userId' | 'email' | 'name' } — from authenticated user
248
- - { source: 'record', field: 'fieldName' } — from page's primary record (detail pages)
249
- - { source: 'static', value: 'active' } — literal default value
250
-
251
- For query data sources: variables substitute into smart query {{placeholders}}.
252
- For structure data sources: variables become equality filters. IMPORTANT: variable name 'id' is special — it fetches the record BY its system UUID. All other variable names filter against data.<fieldName> in the JSONB column (e.g., variable 'requestId' → filters on data.requestId). Reference fields between collections store system UUIDs.
253
-
254
- Common patterns:
255
- - Detail page primary record: { id: { source: 'url', param: 'id' } } — fetches single record by system ID
256
- - Detail page related list: { requestId: { source: 'url', param: 'id' } } — filters where data.requestId = URL param
257
- - User-scoped view: { assigneeId: { source: 'auth', field: 'userId' } }
258
- - Navigate with params: action config { useQueryParams: true } + paramConfig { source: 'row', mode: 'selected', selectedFields: ['id'] }
259
- - Rename params: action config { useQueryParams: true, paramMapping: { requestId: 'id' } } — passes ?id=<value> instead of ?requestId=<value>`,
260
- {
261
- pageId: z.string().describe("The page ID (UUID)"),
262
- definition: z
263
- .record(z.string(), z.any())
264
- .describe(
265
- "The page definition object containing sections with blocks. Each section has: id, kind (content|metrics|exceptions|actions|hero|supporting), title, layout (single-column|two-column|metric-strip|stack), and blocks array."
266
- ),
267
- changeSummary: z.string().optional().describe("Summary of changes in this draft"),
268
- },
269
- async ({ pageId, definition, changeSummary }) => {
270
- try {
271
- const body: Record<string, any> = { definition };
272
- if (changeSummary) body.changeSummary = changeSummary;
273
-
274
- const resp = await client.put(`${basePath}/${pageId}/draft`, body);
275
- return {
276
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
277
- };
278
- } catch (error) {
279
- return {
280
- content: [{ type: "text", text: formatError(error, `saving draft for page '${pageId}'`) }],
281
- isError: true,
282
- };
283
- }
284
- }
285
- );
286
-
287
- registerTool<any>(server,
288
- "get_page_draft",
289
- "Get the current draft version of a page, including its full definition (sections, blocks, data sources).",
290
- {
291
- pageId: z.string().describe("The page ID (UUID)"),
292
- },
293
- async ({ pageId }) => {
294
- try {
295
- const resp = await client.get(`${basePath}/${pageId}/draft`);
296
- return {
297
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
298
- };
299
- } catch (error) {
300
- return {
301
- content: [{ type: "text", text: formatError(error, `getting draft for page '${pageId}'`) }],
302
- isError: true,
303
- };
304
- }
305
- }
306
- );
307
-
308
- registerTool<any>(server,
309
- "list_page_versions",
310
- "List all versions of a page. Each version captures a snapshot of the page definition at a point in time.",
311
- {
312
- pageId: z.string().describe("The page ID (UUID)"),
313
- page: z.number().optional().describe("Page number (1-indexed, default: 1)"),
314
- pageSize: z.number().optional().describe("Items per page (default: 20)"),
315
- },
316
- async ({ pageId, page, pageSize }) => {
317
- try {
318
- const params: Record<string, any> = {};
319
- if (page !== undefined) params.page = page;
320
- if (pageSize !== undefined) params.pageSize = pageSize;
321
-
322
- const resp = await client.get(`${basePath}/${pageId}/versions`, { params });
323
- return {
324
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
325
- };
326
- } catch (error) {
327
- return {
328
- content: [{ type: "text", text: formatError(error, `listing versions for page '${pageId}'`) }],
329
- isError: true,
330
- };
331
- }
332
- }
333
- );
334
-
335
- // ── Publishing ────────────────────────────────────────────────────
336
-
337
- registerTool<any>(server,
338
- "validate_page",
339
- "Run validation checks on a page's current draft to determine if it is ready to publish. Returns a list of issues (errors and warnings) that must be resolved before publishing.",
340
- {
341
- pageId: z.string().describe("The page ID (UUID) to validate"),
342
- },
343
- async ({ pageId }) => {
344
- try {
345
- const resp = await client.post(`${basePath}/${pageId}/validate`);
346
- return {
347
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
348
- };
349
- } catch (error) {
350
- return {
351
- content: [{ type: "text", text: formatError(error, `validating page '${pageId}'`) }],
352
- isError: true,
353
- };
354
- }
355
- }
356
- );
357
-
358
- registerTool<any>(server,
359
- "publish_page",
360
- "Publish the current draft of a page, making it accessible at its runtime URL. Validates the draft first — if there are errors, publishing is rejected with details. Returns the publication record and the public runtime URL.",
361
- {
362
- pageId: z.string().describe("The page ID (UUID) to publish"),
363
- },
364
- async ({ pageId }) => {
365
- try {
366
- const resp = await client.post(`${basePath}/${pageId}/publish`);
367
- return {
368
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
369
- };
370
- } catch (error) {
371
- return {
372
- content: [{ type: "text", text: formatError(error, `publishing page '${pageId}'`) }],
373
- isError: true,
374
- };
375
- }
376
- }
377
- );
378
-
379
- registerTool<any>(server,
380
- "unpublish_page",
381
- "Unpublish a page, making it no longer accessible at its runtime URL. The page definition is preserved and can be re-published later.",
382
- {
383
- pageId: z.string().describe("The page ID (UUID) to unpublish"),
384
- },
385
- async ({ pageId }) => {
386
- try {
387
- const resp = await client.post(`${basePath}/${pageId}/unpublish`);
388
- return {
389
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
390
- };
391
- } catch (error) {
392
- return {
393
- content: [{ type: "text", text: formatError(error, `unpublishing page '${pageId}'`) }],
394
- isError: true,
395
- };
396
- }
397
- }
398
- );
399
-
400
- // ── Access Policy ─────────────────────────────────────────────────
401
-
402
- registerTool<any>(server,
403
- "set_page_access_policy",
404
- "Set the access policy for a page. Controls who can view the published page: 'public' (anyone), 'authenticated' (logged-in users), or 'role-gated' (users with specific roles).",
405
- {
406
- pageId: z.string().describe("The page ID (UUID)"),
407
- accessMode: z
408
- .enum(["public", "authenticated", "role-gated"])
409
- .describe("Access control mode"),
410
- requiredRoles: z
411
- .array(z.string())
412
- .optional()
413
- .describe("Required roles (only used when accessMode is 'role-gated')"),
414
- },
415
- async ({ pageId, accessMode, requiredRoles }) => {
416
- try {
417
- const body: Record<string, any> = { accessMode };
418
- if (requiredRoles) body.requiredRoles = requiredRoles;
419
-
420
- const resp = await client.put(`${basePath}/${pageId}/access-policy`, body);
421
- return {
422
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
423
- };
424
- } catch (error) {
425
- return {
426
- content: [{ type: "text", text: formatError(error, `setting access policy for page '${pageId}'`) }],
427
- isError: true,
428
- };
429
- }
430
- }
431
- );
432
-
433
- // ── Theme ─────────────────────────────────────────────────────────
434
-
435
- registerTool<any>(server,
436
- "get_page_theme",
437
- "Get the workspace theme configuration used by published pages. Includes primary color, accent color, optional logo URL, and font family.",
438
- {},
439
- async () => {
440
- try {
441
- const resp = await client.get(`${basePath}/theme`);
442
- return {
443
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
444
- };
445
- } catch (error) {
446
- return {
447
- content: [{ type: "text", text: formatError(error, "getting page theme") }],
448
- isError: true,
449
- };
450
- }
451
- }
452
- );
453
-
454
- registerTool<any>(server,
455
- "set_page_theme",
456
- "Set the workspace theme for published pages. Controls the visual branding of all published pages.",
457
- {
458
- primaryColor: z.string().describe("Primary brand color (hex, e.g., '#1a73e8')"),
459
- accentColor: z.string().describe("Accent color (hex, e.g., '#ff6d00')"),
460
- logoUrl: z.string().optional().describe("URL to the workspace logo"),
461
- fontFamily: z.string().optional().describe("Font family name (e.g., 'Inter', 'Roboto')"),
462
- },
463
- async ({ primaryColor, accentColor, logoUrl, fontFamily }) => {
464
- try {
465
- const config: Record<string, any> = { primaryColor, accentColor };
466
- if (logoUrl !== undefined) config.logoUrl = logoUrl;
467
- if (fontFamily !== undefined) config.fontFamily = fontFamily;
468
-
469
- const resp = await client.put(`${basePath}/theme`, { config });
470
- return {
471
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
472
- };
473
- } catch (error) {
474
- return {
475
- content: [{ type: "text", text: formatError(error, "setting page theme") }],
476
- isError: true,
477
- };
478
- }
479
- }
480
- );
481
-
482
- // ── Navigation ────────────────────────────────────────────────────
483
-
484
- registerTool<any>(server,
485
- "get_navigation",
486
- "Get the workspace navigation configuration. Controls the sidebar/nav shell that wraps published pages.",
487
- {},
488
- async () => {
489
- try {
490
- const resp = await client.get(`${basePath}/navigation`);
491
- return {
492
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
493
- };
494
- } catch (error) {
495
- return {
496
- content: [{ type: "text", text: formatError(error, "getting navigation config") }],
497
- isError: true,
498
- };
499
- }
500
- }
501
- );
502
-
503
- registerTool<any>(server,
504
- "set_navigation",
505
- "Set the workspace navigation configuration. Defines the sidebar items, branding, and grouping for the page navigation shell.",
506
- {
507
- config: z
508
- .record(z.string(), z.any())
509
- .describe(
510
- "Navigation config object with: enabled (boolean), branding ({ logoUrl, displayName }), items (array of nav items with pageId, label, icon, group)"
511
- ),
512
- },
513
- async ({ config }) => {
514
- try {
515
- const resp = await client.put(`${basePath}/navigation`, { config });
516
- return {
517
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
518
- };
519
- } catch (error) {
520
- return {
521
- content: [{ type: "text", text: formatError(error, "setting navigation config") }],
522
- isError: true,
523
- };
524
- }
525
- }
526
- );
527
-
528
- registerTool<any>(server,
529
- "delete_navigation",
530
- "Delete the workspace navigation configuration. Pages revert to standalone rendering without a sidebar/nav shell.",
531
- {},
532
- async () => {
533
- try {
534
- await client.delete(`${basePath}/navigation`);
535
- return {
536
- content: [{ type: "text", text: "Navigation config deleted. Pages will render standalone." }],
537
- };
538
- } catch (error) {
539
- return {
540
- content: [{ type: "text", text: formatError(error, "deleting navigation config") }],
541
- isError: true,
542
- };
543
- }
544
- }
545
- );
546
-
547
- // ── Assembly (AI-assisted page generation) ────────────────────────
548
-
549
- registerTool<any>(server,
550
- "generate_starter_pages",
551
- "Generate page proposals from collection IDs. Uses guided assembly to create page definitions (list, detail, form, dashboard) tailored to the data schema. Returns proposals that can be reviewed and accepted.",
552
- {
553
- collectionIds: z
554
- .array(z.string())
555
- .describe("Array of collection IDs (UUIDs) to generate pages for. Get these from list_collections → id field."),
556
- goals: z
557
- .array(z.string())
558
- .optional()
559
- .describe("Optional goals to guide page generation (e.g., 'customer management dashboard', 'order tracking')"),
560
- },
561
- async ({ collectionIds, goals }) => {
562
- try {
563
- const body: Record<string, any> = { structureIds: collectionIds };
564
- if (goals) body.goals = goals;
565
-
566
- const resp = await client.post(`${basePath}/generate-starter-pages`, body);
567
- return {
568
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
569
- };
570
- } catch (error) {
571
- return {
572
- content: [{ type: "text", text: formatError(error, "generating starter pages") }],
573
- isError: true,
574
- };
575
- }
576
- }
577
- );
578
-
579
- registerTool<any>(server,
580
- "accept_page_proposal",
581
- "Accept a generated page proposal and create the page with its initial draft definition. Use after reviewing proposals from generate_starter_pages.",
582
- {
583
- name: z.string().describe("Display name for the page"),
584
- slug: z.string().describe("URL-safe slug for the page"),
585
- pageType: z
586
- .enum(["list", "detail", "form", "dashboard"])
587
- .describe("Page type"),
588
- definition: z
589
- .record(z.string(), z.any())
590
- .describe("The page definition from the proposal"),
591
- generationSource: z
592
- .string()
593
- .describe("The source that generated this proposal (from the proposal object)"),
594
- },
595
- async ({ name, slug, pageType, definition, generationSource }) => {
596
- try {
597
- const resp = await client.post(`${basePath}/accept-proposal`, {
598
- name,
599
- slug,
600
- pageType,
601
- definition,
602
- generationSource,
603
- });
604
- return {
605
- content: [{ type: "text", text: JSON.stringify(resp.data, null, 2) }],
606
- };
607
- } catch (error) {
608
- return {
609
- content: [{ type: "text", text: formatError(error, "accepting page proposal") }],
610
- isError: true,
611
- };
612
- }
613
- }
614
- );
615
- }