dotcms-custom-mcp 0.0.0-stage → 1.3.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 +257 -2
- package/dotcms.js +322 -0
- package/hooks/confirm-write.mjs +41 -0
- package/index.js +954 -0
- package/package.json +39 -4
- package/plans.js +111 -0
- package/relations.js +171 -0
- package/seo.js +365 -0
package/index.js
ADDED
|
@@ -0,0 +1,954 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Local MCP server for dotCMS.
|
|
3
|
+
//
|
|
4
|
+
// Read-only tools (always available):
|
|
5
|
+
// list_content_types, get_content_type_fields, get_content_type_relations,
|
|
6
|
+
// analyze_seo, audit_seo_pages, list_vtl_files, read_vtl_file
|
|
7
|
+
// Write tools (only when DOTCMS_ALLOW_WRITE=true, limited to DOTCMS_WRITE_ROOTS):
|
|
8
|
+
// plan_vtl_change (plans only, writes nothing) -> apply_vtl_change (writes, human-confirmed)
|
|
9
|
+
//
|
|
10
|
+
// Config: see dotcms.js.
|
|
11
|
+
|
|
12
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
13
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
14
|
+
import crypto from "node:crypto";
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
import {
|
|
17
|
+
ALLOW_WRITE,
|
|
18
|
+
BASE_URL,
|
|
19
|
+
CONFIRM,
|
|
20
|
+
INSECURE_TRANSPORT,
|
|
21
|
+
READ_EXTENSIONS,
|
|
22
|
+
SITE_URL,
|
|
23
|
+
TOKEN,
|
|
24
|
+
WRITE_ROOTS,
|
|
25
|
+
api,
|
|
26
|
+
assertReadable,
|
|
27
|
+
assertSite,
|
|
28
|
+
downloadFile,
|
|
29
|
+
ensureFolder,
|
|
30
|
+
escapeLucene,
|
|
31
|
+
fetchSiteHtml,
|
|
32
|
+
findFiles,
|
|
33
|
+
parseWritePath,
|
|
34
|
+
pickVersion,
|
|
35
|
+
resolveSite,
|
|
36
|
+
saveFile,
|
|
37
|
+
searchFiles,
|
|
38
|
+
} from "./dotcms.js";
|
|
39
|
+
import { deletePlan, diffLines, loadPlan, renderPlan, savePlan } from "./plans.js";
|
|
40
|
+
import { buildRelationTree, renderRelationTree } from "./relations.js";
|
|
41
|
+
import {
|
|
42
|
+
analyzeFields,
|
|
43
|
+
analyzeHtml,
|
|
44
|
+
auditRow,
|
|
45
|
+
checkUrl,
|
|
46
|
+
commonIssues,
|
|
47
|
+
crossCheck,
|
|
48
|
+
normalizePagePath,
|
|
49
|
+
renderAuditReport,
|
|
50
|
+
renderSeoReport,
|
|
51
|
+
sortRows,
|
|
52
|
+
summarize,
|
|
53
|
+
} from "./seo.js";
|
|
54
|
+
|
|
55
|
+
const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true };
|
|
56
|
+
const MAX_FILE_CHARS = 200_000;
|
|
57
|
+
|
|
58
|
+
// Field classes that only describe the edit-form layout, not real data.
|
|
59
|
+
const LAYOUT_FIELDS = new Set([
|
|
60
|
+
"RowField",
|
|
61
|
+
"ColumnField",
|
|
62
|
+
"TabDividerField",
|
|
63
|
+
"LineDividerField",
|
|
64
|
+
"ColumnBreakField",
|
|
65
|
+
]);
|
|
66
|
+
|
|
67
|
+
const shortClass = (clazz = "") => clazz.split(".").pop().replace(/^Immutable/, "");
|
|
68
|
+
|
|
69
|
+
function mapField(field) {
|
|
70
|
+
const out = {
|
|
71
|
+
name: field.name,
|
|
72
|
+
variable: field.variable,
|
|
73
|
+
type: field.fieldType || shortClass(field.clazz).replace(/Field$/, ""),
|
|
74
|
+
class: shortClass(field.clazz),
|
|
75
|
+
dataType: field.dataType,
|
|
76
|
+
required: !!field.required,
|
|
77
|
+
unique: !!field.unique,
|
|
78
|
+
indexed: !!field.indexed,
|
|
79
|
+
searchable: !!field.searchable,
|
|
80
|
+
listed: !!field.listed,
|
|
81
|
+
system: !!field.fixed,
|
|
82
|
+
};
|
|
83
|
+
if (field.hint) out.hint = field.hint;
|
|
84
|
+
if (field.defaultValue) out.defaultValue = field.defaultValue;
|
|
85
|
+
if (field.values) out.values = field.values;
|
|
86
|
+
if (field.regexCheck) out.regexCheck = field.regexCheck;
|
|
87
|
+
if (field.relationships) out.relationships = field.relationships;
|
|
88
|
+
if (field.categories) out.categories = field.categories;
|
|
89
|
+
if (field.fieldVariables?.length) {
|
|
90
|
+
out.fieldVariables = Object.fromEntries(field.fieldVariables.map((v) => [v.key, v.value]));
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const mapFile = (f) => ({
|
|
96
|
+
path: f.path,
|
|
97
|
+
name: f.fileName || f.name,
|
|
98
|
+
site: f.hostName,
|
|
99
|
+
identifier: f.identifier,
|
|
100
|
+
inode: f.inode,
|
|
101
|
+
languageId: f.languageId,
|
|
102
|
+
size: f.size,
|
|
103
|
+
modDate: f.modDate,
|
|
104
|
+
live: f.live,
|
|
105
|
+
description: f.description || undefined,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
const ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
|
|
109
|
+
const fail = (err) => ({ isError: true, content: [{ type: "text", text: err.message }] });
|
|
110
|
+
|
|
111
|
+
const server = new McpServer({ name: "dotcms", version: "1.3.0" });
|
|
112
|
+
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// Read-only tools
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
server.registerTool(
|
|
118
|
+
"list_content_types",
|
|
119
|
+
{
|
|
120
|
+
title: "List dotCMS content types",
|
|
121
|
+
description:
|
|
122
|
+
"Read-only. List content types in dotCMS (name, variable, base type, number of content entries). " +
|
|
123
|
+
"Use it to find the variable name of a content type before reading its fields.",
|
|
124
|
+
inputSchema: {
|
|
125
|
+
filter: z.string().optional().describe("Filter by name or variable (substring)"),
|
|
126
|
+
type: z
|
|
127
|
+
.enum(["CONTENT", "WIDGET", "FORM", "FILEASSET", "HTMLPAGE", "PERSONA", "VANITY_URL", "KEY_VALUE", "DOTASSET"])
|
|
128
|
+
.optional()
|
|
129
|
+
.describe("Only content types of this base type"),
|
|
130
|
+
page: z.number().int().min(1).default(1).describe("Page number"),
|
|
131
|
+
perPage: z.number().int().min(1).max(100).default(50).describe("Items per page"),
|
|
132
|
+
},
|
|
133
|
+
annotations: READ_ONLY,
|
|
134
|
+
},
|
|
135
|
+
async ({ filter, type, page, perPage }) => {
|
|
136
|
+
try {
|
|
137
|
+
const data = await api("/api/v1/contenttype", {
|
|
138
|
+
params: { filter, type, page, per_page: perPage, orderby: "name", direction: "ASC" },
|
|
139
|
+
});
|
|
140
|
+
const types = (data.entity || []).map((ct) => ({
|
|
141
|
+
name: ct.name,
|
|
142
|
+
variable: ct.variable,
|
|
143
|
+
id: ct.id,
|
|
144
|
+
baseType: ct.baseType,
|
|
145
|
+
description: ct.description || undefined,
|
|
146
|
+
entries: ct.nEntries,
|
|
147
|
+
system: !!ct.system,
|
|
148
|
+
}));
|
|
149
|
+
return ok({
|
|
150
|
+
page,
|
|
151
|
+
perPage,
|
|
152
|
+
total: data.pagination?.totalEntries,
|
|
153
|
+
count: types.length,
|
|
154
|
+
contentTypes: types,
|
|
155
|
+
});
|
|
156
|
+
} catch (err) {
|
|
157
|
+
return fail(err);
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
server.registerTool(
|
|
163
|
+
"get_content_type_fields",
|
|
164
|
+
{
|
|
165
|
+
title: "Get fields of a dotCMS content type",
|
|
166
|
+
description:
|
|
167
|
+
"Read-only. Return the fields of a dotCMS content type: name, variable, field type, data type, " +
|
|
168
|
+
"required/unique/indexed/searchable/listed flags, hint, default value, allowed values, " +
|
|
169
|
+
"relationships and field variables.",
|
|
170
|
+
inputSchema: {
|
|
171
|
+
contentType: z.string().min(1).describe("Content type variable name (e.g. 'Blog') or its id"),
|
|
172
|
+
includeLayout: z
|
|
173
|
+
.boolean()
|
|
174
|
+
.default(false)
|
|
175
|
+
.describe("Also include layout-only fields (rows, columns, tab dividers)"),
|
|
176
|
+
},
|
|
177
|
+
annotations: READ_ONLY,
|
|
178
|
+
},
|
|
179
|
+
async ({ contentType, includeLayout }) => {
|
|
180
|
+
try {
|
|
181
|
+
const data = await api(`/api/v1/contenttype/id/${encodeURIComponent(contentType)}`);
|
|
182
|
+
const ct = data.entity || {};
|
|
183
|
+
const fields = (ct.fields || [])
|
|
184
|
+
.filter((f) => includeLayout || !LAYOUT_FIELDS.has(shortClass(f.clazz)))
|
|
185
|
+
.map(mapField);
|
|
186
|
+
return ok({
|
|
187
|
+
name: ct.name,
|
|
188
|
+
variable: ct.variable,
|
|
189
|
+
id: ct.id,
|
|
190
|
+
baseType: ct.baseType,
|
|
191
|
+
description: ct.description || undefined,
|
|
192
|
+
urlMapPattern: ct.urlMapPattern || undefined,
|
|
193
|
+
detailPage: ct.detailPage || undefined,
|
|
194
|
+
fieldCount: fields.length,
|
|
195
|
+
fields,
|
|
196
|
+
});
|
|
197
|
+
} catch (err) {
|
|
198
|
+
return fail(err);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
const MAX_TYPES_SCANNED = 500;
|
|
204
|
+
|
|
205
|
+
/** Every content type with its fields, for finding relationships declared on other types. */
|
|
206
|
+
async function getAllContentTypes() {
|
|
207
|
+
const all = [];
|
|
208
|
+
for (let page = 1; ; page++) {
|
|
209
|
+
const data = await api("/api/v1/contenttype", { params: { page, per_page: 100, orderby: "name", direction: "ASC" } });
|
|
210
|
+
const batch = data.entity || [];
|
|
211
|
+
all.push(...batch);
|
|
212
|
+
const total = data.pagination?.totalEntries ?? all.length;
|
|
213
|
+
if (!batch.length || all.length >= total) break;
|
|
214
|
+
if (all.length >= MAX_TYPES_SCANNED) {
|
|
215
|
+
throw new Error(`more than ${MAX_TYPES_SCANNED} content types`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// Older dotCMS versions list content types without their fields: fetch those one by one.
|
|
219
|
+
const missing = all.filter((ct) => !Array.isArray(ct.fields));
|
|
220
|
+
for (let i = 0; i < missing.length; i += 8) {
|
|
221
|
+
await Promise.all(
|
|
222
|
+
missing.slice(i, i + 8).map(async (ct) => {
|
|
223
|
+
try {
|
|
224
|
+
ct.fields = (await api(`/api/v1/contenttype/id/${encodeURIComponent(ct.variable)}`)).entity?.fields || [];
|
|
225
|
+
} catch {
|
|
226
|
+
ct.fields = [];
|
|
227
|
+
}
|
|
228
|
+
}),
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
return all;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
server.registerTool(
|
|
235
|
+
"get_content_type_relations",
|
|
236
|
+
{
|
|
237
|
+
title: "Get the relationship tree of a dotCMS content type",
|
|
238
|
+
description:
|
|
239
|
+
"Read-only. Show everything a content type is connected to: its relationship fields, the related " +
|
|
240
|
+
"content types, and their relationships in turn, as a tree (text drawing plus JSON). For each " +
|
|
241
|
+
"connection it gives the field, the related type, the cardinality (ONE_TO_MANY, MANY_TO_MANY, " +
|
|
242
|
+
"ONE_TO_ONE, MANY_TO_ONE), which side this type is on, and the field on the other side. " +
|
|
243
|
+
"Also lists category fields, and relationships that only the other content type declares.",
|
|
244
|
+
inputSchema: {
|
|
245
|
+
contentType: z.string().min(1).describe("Content type variable name (e.g. 'Blog') or its id"),
|
|
246
|
+
depth: z
|
|
247
|
+
.number()
|
|
248
|
+
.int()
|
|
249
|
+
.min(1)
|
|
250
|
+
.max(5)
|
|
251
|
+
.default(2)
|
|
252
|
+
.describe("How many levels of related content types to follow (1 = direct relations only)"),
|
|
253
|
+
includeIncoming: z
|
|
254
|
+
.boolean()
|
|
255
|
+
.default(true)
|
|
256
|
+
.describe("Also find relationships declared only on other content types that point at this one (scans all content types)"),
|
|
257
|
+
includeFields: z
|
|
258
|
+
.boolean()
|
|
259
|
+
.default(false)
|
|
260
|
+
.describe("Also list the non-relationship fields (variable, type, required) of every content type in the tree"),
|
|
261
|
+
},
|
|
262
|
+
annotations: READ_ONLY,
|
|
263
|
+
},
|
|
264
|
+
async ({ contentType, depth, includeIncoming, includeFields }) => {
|
|
265
|
+
try {
|
|
266
|
+
const { tree, warnings, contentTypes } = await buildRelationTree({
|
|
267
|
+
root: contentType,
|
|
268
|
+
depth,
|
|
269
|
+
includeIncoming,
|
|
270
|
+
includeFields,
|
|
271
|
+
getType: async (variable) => {
|
|
272
|
+
const ct = (await api(`/api/v1/contenttype/id/${encodeURIComponent(variable)}`)).entity;
|
|
273
|
+
if (!ct?.variable) throw new Error(`Content type '${variable}' not found.`);
|
|
274
|
+
return ct;
|
|
275
|
+
},
|
|
276
|
+
getAllTypes: getAllContentTypes,
|
|
277
|
+
describeField: (f) => {
|
|
278
|
+
if (LAYOUT_FIELDS.has(shortClass(f.clazz))) return null;
|
|
279
|
+
const m = mapField(f);
|
|
280
|
+
return { variable: m.variable, name: m.name, type: m.type, required: m.required };
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
return {
|
|
284
|
+
content: [
|
|
285
|
+
{ type: "text", text: renderRelationTree(tree) + (warnings.length ? `\n\n${warnings.map((w) => `Note: ${w}`).join("\n")}` : "") },
|
|
286
|
+
{ type: "text", text: JSON.stringify({ root: tree.variable, depth, contentTypes, warnings, tree }, null, 2) },
|
|
287
|
+
],
|
|
288
|
+
};
|
|
289
|
+
} catch (err) {
|
|
290
|
+
return fail(err);
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
/** A warning when DOTCMS_SITE_URL does not look like it serves this site (several sites share one instance). */
|
|
296
|
+
async function siteUrlNote(siteHostname) {
|
|
297
|
+
if (!SITE_URL || !siteHostname) return null;
|
|
298
|
+
try {
|
|
299
|
+
const publicHost = new URL(SITE_URL).hostname.toLowerCase();
|
|
300
|
+
const site = await resolveSite(siteHostname);
|
|
301
|
+
const known = [site.hostname, ...site.aliases].map((s) => s.toLowerCase());
|
|
302
|
+
return known.includes(publicHost)
|
|
303
|
+
? null
|
|
304
|
+
: `Check: DOTCMS_SITE_URL (${publicHost}) is not a host name or alias of site ${site.hostname}; make sure it serves that site`;
|
|
305
|
+
} catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Fill a URL map pattern such as /blog/post/{urlTitle} from a content item; null if a value is missing. */
|
|
311
|
+
function urlFromPattern(pattern, content) {
|
|
312
|
+
let missing = false;
|
|
313
|
+
const url = pattern.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
314
|
+
const v = content?.[name];
|
|
315
|
+
if (typeof v !== "string" || !v) missing = true;
|
|
316
|
+
return v || "";
|
|
317
|
+
});
|
|
318
|
+
return missing ? null : url;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
server.registerTool(
|
|
322
|
+
"analyze_seo",
|
|
323
|
+
{
|
|
324
|
+
title: "Analyze the SEO of a dotCMS page or content item",
|
|
325
|
+
description:
|
|
326
|
+
"Read-only. Check the SEO of one page and report errors, warnings and notes. Pass a page 'path' " +
|
|
327
|
+
"(e.g. '/about-us' or '/blog/post/my-post'), or a 'contentType' with an 'identifier'. " +
|
|
328
|
+
"A regular page is checked from its own fields. A detail page (URL-mapped content) or a content item is " +
|
|
329
|
+
"checked from the content's fields, and its content type is loaded to see whether it has title, " +
|
|
330
|
+
"description and image fields and a sensible URL map pattern. Checks title and description length, " +
|
|
331
|
+
"duplicates, URL shape and images. When the server has DOTCMS_SITE_URL, the rendered HTML is checked too: " +
|
|
332
|
+
"title tag, meta description, canonical, robots, h1, Open Graph tags, image alt text, lang and viewport.",
|
|
333
|
+
inputSchema: {
|
|
334
|
+
path: z
|
|
335
|
+
.string()
|
|
336
|
+
.optional()
|
|
337
|
+
.describe("Page path on the site, e.g. '/about-us' or '/blog/post/my-post' (a full URL is reduced to its path)"),
|
|
338
|
+
contentType: z.string().optional().describe("Content type variable (e.g. 'Blog'); use with 'identifier' instead of 'path'"),
|
|
339
|
+
identifier: z.string().optional().describe("Identifier of the content item; use with 'contentType'"),
|
|
340
|
+
site: z
|
|
341
|
+
.string()
|
|
342
|
+
.optional()
|
|
343
|
+
.describe("Site host name, for a 'path' on a site other than the instance's default one, e.g. 'us.rebuild.development'"),
|
|
344
|
+
languageId: z.number().int().optional().describe("Language id (default: the site's default language)"),
|
|
345
|
+
},
|
|
346
|
+
annotations: READ_ONLY,
|
|
347
|
+
},
|
|
348
|
+
async ({ path, contentType, identifier, site, languageId }) => {
|
|
349
|
+
try {
|
|
350
|
+
if (path && (contentType || identifier)) throw new Error("Pass either 'path', or 'contentType' with 'identifier' — not both.");
|
|
351
|
+
if (!path && !(contentType && identifier)) {
|
|
352
|
+
throw new Error("Pass a page 'path' (e.g. '/about-us'), or 'contentType' together with 'identifier'.");
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const sources = [];
|
|
356
|
+
const extra = []; // findings that come from the process itself
|
|
357
|
+
let kind;
|
|
358
|
+
let heading;
|
|
359
|
+
let page = null;
|
|
360
|
+
let content = null;
|
|
361
|
+
let ct = null;
|
|
362
|
+
let urlPath = null;
|
|
363
|
+
let siteHostname = null;
|
|
364
|
+
|
|
365
|
+
if (path) {
|
|
366
|
+
urlPath = normalizePagePath(path);
|
|
367
|
+
const segments = urlPath === "/" ? "index" : urlPath.slice(1);
|
|
368
|
+
// Segments arrive percent-encoded from the path; decode first so they are not encoded twice.
|
|
369
|
+
const siteInfo = site ? await resolveSite(site) : null;
|
|
370
|
+
let data;
|
|
371
|
+
try {
|
|
372
|
+
data = await api(`/api/v1/page/render/${segments.split("/").map((s) => encodeURIComponent(decodeURIComponent(s))).join("/")}`, {
|
|
373
|
+
params: { mode: "LIVE", language_id: languageId, host_id: siteInfo?.identifier },
|
|
374
|
+
});
|
|
375
|
+
} catch (err) {
|
|
376
|
+
if (!site && /responded 404/.test(err.message)) {
|
|
377
|
+
err.message += " If the page belongs to another site than the instance's default one, pass 'site' (the site's host name).";
|
|
378
|
+
}
|
|
379
|
+
throw err;
|
|
380
|
+
}
|
|
381
|
+
const entity = data.entity || {};
|
|
382
|
+
page = entity.page || {};
|
|
383
|
+
content = entity.urlContentMap || null;
|
|
384
|
+
siteHostname = entity.site?.hostname || siteInfo?.hostname || null;
|
|
385
|
+
kind = content ? "detail-page" : "page";
|
|
386
|
+
sources.push(
|
|
387
|
+
`Page loaded from the dotCMS page API (live version${page.title ? `, "${page.title}"` : ""}${entity.site?.hostname ? `, site ${entity.site.hostname}` : ""})`,
|
|
388
|
+
);
|
|
389
|
+
if (content) {
|
|
390
|
+
const typeVar = content.contentType || content.contentTypeName;
|
|
391
|
+
if (typeVar) {
|
|
392
|
+
try {
|
|
393
|
+
ct = (await api(`/api/v1/contenttype/id/${encodeURIComponent(typeVar)}`)).entity || null;
|
|
394
|
+
sources.push(`Detail page: SEO values read from the ${ct?.variable || typeVar} content, definition from its content type`);
|
|
395
|
+
} catch (err) {
|
|
396
|
+
sources.push(`Detail page: SEO values read from the content; its content type could not be loaded (${err.message})`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
} else {
|
|
400
|
+
sources.push("Regular page: SEO values read from the page's own fields");
|
|
401
|
+
}
|
|
402
|
+
heading = `SEO analysis: ${urlPath} (${kind === "detail-page" ? `detail page${ct ? ` · ${ct.variable}` : ""}` : "page"})`;
|
|
403
|
+
} else {
|
|
404
|
+
kind = "content";
|
|
405
|
+
ct = (await api(`/api/v1/contenttype/id/${encodeURIComponent(contentType)}`)).entity;
|
|
406
|
+
if (!ct?.variable) throw new Error(`Content type '${contentType}' not found.`);
|
|
407
|
+
const base = `+contentType:${escapeLucene(ct.variable)} +identifier:${escapeLucene(identifier)}${languageId ? ` +languageId:${languageId}` : ""}`;
|
|
408
|
+
let state = "live";
|
|
409
|
+
let found = (await api("/api/content/_search", { method: "POST", body: { query: `${base} +live:true`, limit: 5 } })).entity?.jsonObjectView?.contentlets || [];
|
|
410
|
+
if (!found.length) {
|
|
411
|
+
state = "working";
|
|
412
|
+
found = (await api("/api/content/_search", { method: "POST", body: { query: `${base} +working:true`, limit: 5 } })).entity?.jsonObjectView?.contentlets || [];
|
|
413
|
+
}
|
|
414
|
+
if (!found.length) throw new Error(`No ${ct.variable} content with identifier '${identifier}'${languageId ? ` in language ${languageId}` : ""} was found.`);
|
|
415
|
+
content = found[0];
|
|
416
|
+
siteHostname = content.hostName || null;
|
|
417
|
+
sources.push(`Content loaded from dotCMS (${state} version), definition from content type ${ct.variable}`);
|
|
418
|
+
if (state === "working") extra.push({ severity: "warning", id: "not-live", message: "The content has no live version, so it is not visible to search engines yet.", where: "content" });
|
|
419
|
+
if (ct.urlMapPattern) urlPath = urlFromPattern(ct.urlMapPattern, content);
|
|
420
|
+
heading = `SEO analysis: ${ct.variable} content ${identifier}${urlPath ? ` (${urlPath})` : ""}`;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// The rendered page, when the public site is known.
|
|
424
|
+
let htmlResult = null;
|
|
425
|
+
if (urlPath && SITE_URL) {
|
|
426
|
+
try {
|
|
427
|
+
const { html, finalUrl } = await fetchSiteHtml(urlPath);
|
|
428
|
+
htmlResult = analyzeHtml(html);
|
|
429
|
+
sources.push(`Rendered HTML checked at ${finalUrl}`);
|
|
430
|
+
const urlNote = await siteUrlNote(siteHostname);
|
|
431
|
+
if (urlNote) sources.push(urlNote);
|
|
432
|
+
} catch (err) {
|
|
433
|
+
sources.push(`Rendered HTML not checked: ${err.message}`);
|
|
434
|
+
}
|
|
435
|
+
} else if (!SITE_URL) {
|
|
436
|
+
sources.push("Rendered HTML not checked (set DOTCMS_SITE_URL to the public site URL to include it)");
|
|
437
|
+
} else {
|
|
438
|
+
sources.push("Rendered HTML not checked (this content has no URL of its own)");
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const fields = analyzeFields({
|
|
442
|
+
kind,
|
|
443
|
+
page,
|
|
444
|
+
content,
|
|
445
|
+
contentType: ct,
|
|
446
|
+
// The rendered page is the truth for a regular page. For content, a field finding is the cause
|
|
447
|
+
// behind a rendered-page finding, so it is only dropped when the page has the value anyway.
|
|
448
|
+
htmlSeen: {
|
|
449
|
+
title: !!htmlResult && (kind === "page" || !!htmlResult.data.title),
|
|
450
|
+
description: !!htmlResult && (kind === "page" || !!htmlResult.data.description),
|
|
451
|
+
},
|
|
452
|
+
});
|
|
453
|
+
const findings = [
|
|
454
|
+
...extra,
|
|
455
|
+
...fields.findings,
|
|
456
|
+
...(htmlResult?.findings || []),
|
|
457
|
+
...crossCheck(fields.data, htmlResult?.data),
|
|
458
|
+
...(urlPath ? checkUrl(urlPath) : []),
|
|
459
|
+
];
|
|
460
|
+
if (kind === "detail-page" && !htmlResult) {
|
|
461
|
+
findings.push({
|
|
462
|
+
severity: "info",
|
|
463
|
+
id: "detail-title-from-template",
|
|
464
|
+
message: "The browser title of a detail page comes from the template, not from these fields; check the rendered page to confirm it uses the content's title.",
|
|
465
|
+
where: "template",
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
return {
|
|
470
|
+
content: [
|
|
471
|
+
{ type: "text", text: renderSeoReport({ heading, sources, findings }) },
|
|
472
|
+
{
|
|
473
|
+
type: "text",
|
|
474
|
+
text: JSON.stringify(
|
|
475
|
+
{
|
|
476
|
+
kind,
|
|
477
|
+
path: urlPath || undefined,
|
|
478
|
+
contentType: ct?.variable,
|
|
479
|
+
summary: summarize(findings),
|
|
480
|
+
sources,
|
|
481
|
+
values: fields.data,
|
|
482
|
+
rendered: htmlResult?.data,
|
|
483
|
+
findings,
|
|
484
|
+
},
|
|
485
|
+
null,
|
|
486
|
+
2,
|
|
487
|
+
),
|
|
488
|
+
},
|
|
489
|
+
],
|
|
490
|
+
};
|
|
491
|
+
} catch (err) {
|
|
492
|
+
return fail(err);
|
|
493
|
+
}
|
|
494
|
+
},
|
|
495
|
+
);
|
|
496
|
+
|
|
497
|
+
const AUDIT_HTML_BUDGET_MS = 45_000; // stop fetching rendered pages after this; the rest use page fields only
|
|
498
|
+
const AUDIT_HTML_CONCURRENCY = 4;
|
|
499
|
+
|
|
500
|
+
/** Run fn over items with at most `size` running at once; results keep the order of items. */
|
|
501
|
+
async function mapPool(items, size, fn) {
|
|
502
|
+
const out = new Array(items.length);
|
|
503
|
+
let next = 0;
|
|
504
|
+
await Promise.all(
|
|
505
|
+
Array.from({ length: Math.min(size, items.length) }, async () => {
|
|
506
|
+
while (next < items.length) {
|
|
507
|
+
const i = next++;
|
|
508
|
+
out[i] = await fn(items[i], i);
|
|
509
|
+
}
|
|
510
|
+
}),
|
|
511
|
+
);
|
|
512
|
+
return out;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
server.registerTool(
|
|
516
|
+
"audit_seo_pages",
|
|
517
|
+
{
|
|
518
|
+
title: "Audit the SEO of all pages in a folder",
|
|
519
|
+
description:
|
|
520
|
+
"Read-only. Check the SEO of every live page under a folder (default: the whole site) and report one line per " +
|
|
521
|
+
"page — errors, warnings and the top problems — most serious first, plus the problems that occur most often. " +
|
|
522
|
+
"Each page gets the same checks as analyze_seo for a regular page: title and description from the page's fields, " +
|
|
523
|
+
"URL shape, and, when the server has DOTCMS_SITE_URL, the rendered HTML. Pages are listed 'limit' at a time; " +
|
|
524
|
+
"ask for the next 'page' to continue. Detail pages (URL-mapped content) are not pages in dotCMS: check one with analyze_seo.",
|
|
525
|
+
inputSchema: {
|
|
526
|
+
folder: z.string().default("/").describe("Folder to audit, including its subfolders, e.g. '/blog' (default: '/', the whole site)"),
|
|
527
|
+
site: z.string().optional().describe("Site host name. Required when pages under the folder exist on several sites"),
|
|
528
|
+
languageId: z.number().int().optional().describe("Language id (default: the lowest language id each page has, usually the default language)"),
|
|
529
|
+
limit: z.number().int().min(1).max(100).default(25).describe("Pages to check per call"),
|
|
530
|
+
page: z.number().int().min(1).default(1).describe("Which batch of pages to check"),
|
|
531
|
+
onlyIssues: z.boolean().default(false).describe("List only pages that have errors or warnings"),
|
|
532
|
+
},
|
|
533
|
+
annotations: READ_ONLY,
|
|
534
|
+
},
|
|
535
|
+
async ({ folder, site, languageId, limit, page, onlyIssues }) => {
|
|
536
|
+
try {
|
|
537
|
+
const folderPath = normalizePagePath(folder);
|
|
538
|
+
const clauses = ["+baseType:5", "+live:true"];
|
|
539
|
+
if (folderPath !== "/") clauses.push(`+path:*${escapeLucene(folderPath.toLowerCase())}/*`);
|
|
540
|
+
// Filter by site inside the search, so totals and batches count only that site's pages.
|
|
541
|
+
const siteInfo = site ? await resolveSite(site) : null;
|
|
542
|
+
if (siteInfo) clauses.push(`+conhost:${siteInfo.identifier}`);
|
|
543
|
+
const offset = (page - 1) * limit;
|
|
544
|
+
const data = await api("/api/content/_search", {
|
|
545
|
+
method: "POST",
|
|
546
|
+
body: { query: clauses.join(" "), sort: "path asc", limit, offset },
|
|
547
|
+
});
|
|
548
|
+
const entity = data.entity || {};
|
|
549
|
+
const total = entity.resultsSize ?? 0;
|
|
550
|
+
let pages = (entity.jsonObjectView?.contentlets || []).filter(
|
|
551
|
+
(p) => typeof p.path === "string" && (folderPath === "/" || p.path.toLowerCase().startsWith(`${folderPath.toLowerCase()}/`)),
|
|
552
|
+
);
|
|
553
|
+
|
|
554
|
+
const sites = [...new Set(pages.map((p) => p.hostName).filter(Boolean))];
|
|
555
|
+
if (siteInfo) pages = pages.filter((p) => p.hostName?.toLowerCase() === siteInfo.hostname.toLowerCase());
|
|
556
|
+
else if (sites.length > 1) throw new Error(`Pages under ${folderPath} exist on several sites (${sites.join(", ")}). Pass 'site'.`);
|
|
557
|
+
const siteName = siteInfo?.hostname || sites[0];
|
|
558
|
+
|
|
559
|
+
if (languageId !== undefined) pages = pages.filter((p) => p.languageId === languageId);
|
|
560
|
+
else {
|
|
561
|
+
const lowest = new Map();
|
|
562
|
+
for (const p of pages) if (!lowest.has(p.identifier) || p.languageId < lowest.get(p.identifier).languageId) lowest.set(p.identifier, p);
|
|
563
|
+
pages = [...lowest.values()];
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const deadline = Date.now() + AUDIT_HTML_BUDGET_MS;
|
|
567
|
+
let htmlFailures = 0;
|
|
568
|
+
let htmlSkipped = 0;
|
|
569
|
+
const rows = await mapPool(pages, AUDIT_HTML_CONCURRENCY, async (p) => {
|
|
570
|
+
const urlPath = p.path.replace(/\/index$/i, "") || "/";
|
|
571
|
+
let htmlResult = null;
|
|
572
|
+
if (SITE_URL) {
|
|
573
|
+
const segments = urlPath.split("/");
|
|
574
|
+
if (Date.now() >= deadline || segments.some((s) => s === "." || s === "..")) htmlSkipped++;
|
|
575
|
+
else {
|
|
576
|
+
try {
|
|
577
|
+
htmlResult = analyzeHtml((await fetchSiteHtml(segments.map(encodeURIComponent).join("/"))).html);
|
|
578
|
+
} catch {
|
|
579
|
+
htmlFailures++;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
const fields = analyzeFields({ kind: "page", page: p, htmlSeen: { title: !!htmlResult, description: !!htmlResult } });
|
|
584
|
+
const findings = [...fields.findings, ...(htmlResult?.findings || []), ...crossCheck(fields.data, htmlResult?.data), ...checkUrl(urlPath)];
|
|
585
|
+
return auditRow({ path: urlPath, title: fields.data.title || htmlResult?.data.title, findings, htmlChecked: !!htmlResult });
|
|
586
|
+
});
|
|
587
|
+
|
|
588
|
+
const checked = rows.filter((r) => r.htmlChecked).length;
|
|
589
|
+
const sources = [
|
|
590
|
+
`Pages listed from the dotCMS content search (live versions${siteName ? `, site ${siteName}` : ""}); each page's own fields are checked`,
|
|
591
|
+
!SITE_URL
|
|
592
|
+
? "Rendered HTML not checked (set DOTCMS_SITE_URL to the public site URL to include it)"
|
|
593
|
+
: `Rendered HTML checked for ${checked} of ${rows.length} pages at ${SITE_URL}` +
|
|
594
|
+
(htmlFailures ? `; ${htmlFailures} could not be fetched` : "") +
|
|
595
|
+
(htmlSkipped ? `; ${htmlSkipped} skipped (time limit or unusual path)` : ""),
|
|
596
|
+
];
|
|
597
|
+
const urlNote = checked ? await siteUrlNote(siteName) : null;
|
|
598
|
+
if (urlNote) sources.push(urlNote);
|
|
599
|
+
const nextPage = offset + limit < total ? page + 1 : null;
|
|
600
|
+
const heading = `SEO audit: ${folderPath}${siteName ? ` on ${siteName}` : ""} (batch ${page})`;
|
|
601
|
+
|
|
602
|
+
return {
|
|
603
|
+
content: [
|
|
604
|
+
{ type: "text", text: renderAuditReport({ heading, sources, rows, total, nextPage, onlyIssues }) },
|
|
605
|
+
{
|
|
606
|
+
type: "text",
|
|
607
|
+
text: JSON.stringify(
|
|
608
|
+
{
|
|
609
|
+
folder: folderPath,
|
|
610
|
+
site: siteName,
|
|
611
|
+
batch: page,
|
|
612
|
+
limit,
|
|
613
|
+
matched: total,
|
|
614
|
+
checked: rows.length,
|
|
615
|
+
nextPage,
|
|
616
|
+
sources,
|
|
617
|
+
commonIssues: commonIssues(rows),
|
|
618
|
+
pages: sortRows(onlyIssues ? rows.filter((r) => r.errors || r.warnings) : rows),
|
|
619
|
+
},
|
|
620
|
+
null,
|
|
621
|
+
2,
|
|
622
|
+
),
|
|
623
|
+
},
|
|
624
|
+
],
|
|
625
|
+
};
|
|
626
|
+
} catch (err) {
|
|
627
|
+
return fail(err);
|
|
628
|
+
}
|
|
629
|
+
},
|
|
630
|
+
);
|
|
631
|
+
|
|
632
|
+
server.registerTool(
|
|
633
|
+
"list_vtl_files",
|
|
634
|
+
{
|
|
635
|
+
title: "List VTL files in dotCMS",
|
|
636
|
+
description:
|
|
637
|
+
"Read-only. Find Velocity (.vtl) files stored in dotCMS as file assets: container, template, " +
|
|
638
|
+
"theme, custom-field and scripting-API VTL files. Returns path, site, identifier, language, size and modification date.",
|
|
639
|
+
inputSchema: {
|
|
640
|
+
folder: z
|
|
641
|
+
.string()
|
|
642
|
+
.optional()
|
|
643
|
+
.describe("Only files whose path contains this folder, e.g. '/application/vtl' or 'containers/banner'"),
|
|
644
|
+
name: z.string().optional().describe("Only files whose file name contains this text, e.g. 'banner'"),
|
|
645
|
+
extension: z.string().default("vtl").describe(`File extension to look for (default 'vtl'; allowed: ${READ_EXTENSIONS.join(", ")})`),
|
|
646
|
+
page: z.number().int().min(1).default(1).describe("Page number"),
|
|
647
|
+
perPage: z.number().int().min(1).max(100).default(50).describe("Items per page"),
|
|
648
|
+
},
|
|
649
|
+
annotations: READ_ONLY,
|
|
650
|
+
},
|
|
651
|
+
async ({ folder, name, extension, page, perPage }) => {
|
|
652
|
+
try {
|
|
653
|
+
assertReadable(`x.${extension.replace(/^\./, "")}`);
|
|
654
|
+
const ext = escapeLucene(extension.replace(/^\./, "").toLowerCase());
|
|
655
|
+
const clauses = [`+path:*.${ext}`];
|
|
656
|
+
if (folder) {
|
|
657
|
+
const f = escapeLucene(folder.toLowerCase().replace(/^\/+|\/+$/g, ""));
|
|
658
|
+
clauses.push(`+path:*${f}/*`);
|
|
659
|
+
}
|
|
660
|
+
if (name) clauses.push(`+title:*${escapeLucene(name.toLowerCase())}*`);
|
|
661
|
+
|
|
662
|
+
const { total, files } = await searchFiles(clauses, {
|
|
663
|
+
limit: perPage,
|
|
664
|
+
offset: (page - 1) * perPage,
|
|
665
|
+
});
|
|
666
|
+
return ok({ page, perPage, total, count: files.length, files: files.map(mapFile) });
|
|
667
|
+
} catch (err) {
|
|
668
|
+
return fail(err);
|
|
669
|
+
}
|
|
670
|
+
},
|
|
671
|
+
);
|
|
672
|
+
|
|
673
|
+
server.registerTool(
|
|
674
|
+
"read_vtl_file",
|
|
675
|
+
{
|
|
676
|
+
title: "Read a VTL file from dotCMS",
|
|
677
|
+
description:
|
|
678
|
+
"Read-only. Return the source of a Velocity (.vtl) file stored in dotCMS. Pass either the full " +
|
|
679
|
+
"path (e.g. '/application/containers/banner/banner.vtl') or the file identifier from list_vtl_files.",
|
|
680
|
+
inputSchema: {
|
|
681
|
+
path: z.string().optional().describe("Full path of the file inside the site"),
|
|
682
|
+
identifier: z.string().optional().describe("File identifier (alternative to path)"),
|
|
683
|
+
site: z.string().optional().describe("Site host name, if the same path exists on several sites"),
|
|
684
|
+
languageId: z
|
|
685
|
+
.number()
|
|
686
|
+
.int()
|
|
687
|
+
.optional()
|
|
688
|
+
.describe("Language id, if the file has several language versions (default: the lowest id, usually the default language)"),
|
|
689
|
+
},
|
|
690
|
+
annotations: READ_ONLY,
|
|
691
|
+
},
|
|
692
|
+
async ({ path, identifier, site, languageId }) => {
|
|
693
|
+
try {
|
|
694
|
+
if (!path && !identifier) throw new Error("Pass either 'path' or 'identifier'.");
|
|
695
|
+
const files = await findFiles({ path, identifier, site });
|
|
696
|
+
const { file, languages } = pickVersion(files, { what: identifier || path, site, languageId });
|
|
697
|
+
assertReadable(file.fileName || file.name || file.path);
|
|
698
|
+
|
|
699
|
+
const content = await downloadFile(file);
|
|
700
|
+
const truncated = content.length > MAX_FILE_CHARS;
|
|
701
|
+
return ok({
|
|
702
|
+
...mapFile(file),
|
|
703
|
+
availableLanguageIds: languages,
|
|
704
|
+
truncated,
|
|
705
|
+
content: truncated ? content.slice(0, MAX_FILE_CHARS) : content,
|
|
706
|
+
});
|
|
707
|
+
} catch (err) {
|
|
708
|
+
return fail(err);
|
|
709
|
+
}
|
|
710
|
+
},
|
|
711
|
+
);
|
|
712
|
+
|
|
713
|
+
// ---------------------------------------------------------------------------
|
|
714
|
+
// Write tools — opt-in, limited to WRITE_ROOTS. Plan first, then the
|
|
715
|
+
// human check (hooks/confirm-write.mjs), then the write.
|
|
716
|
+
// ---------------------------------------------------------------------------
|
|
717
|
+
|
|
718
|
+
if (ALLOW_WRITE) {
|
|
719
|
+
const roots = WRITE_ROOTS.join(" and ");
|
|
720
|
+
|
|
721
|
+
// Fingerprints of the plans this process created. apply_vtl_change refuses a plan whose
|
|
722
|
+
// file on disk no longer matches, so editing a plan file cannot change what gets written.
|
|
723
|
+
const planFingerprints = new Map();
|
|
724
|
+
const fingerprint = (plan) => crypto.createHash("sha256").update(JSON.stringify(plan)).digest("hex");
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Ask the user through the client (MCP elicitation) when it can. Returns "confirmed",
|
|
728
|
+
* "declined", or "unsupported" when the client cannot ask — its own tool approval is then
|
|
729
|
+
* the only check.
|
|
730
|
+
*/
|
|
731
|
+
async function confirmWithUser(plan) {
|
|
732
|
+
if (!CONFIRM || !server.server.getClientCapabilities()?.elicitation) return "unsupported";
|
|
733
|
+
let answer;
|
|
734
|
+
try {
|
|
735
|
+
answer = await server.server.elicitInput({
|
|
736
|
+
message: `Apply this change to dotCMS?\n\n${renderPlan(plan)}`,
|
|
737
|
+
requestedSchema: {
|
|
738
|
+
type: "object",
|
|
739
|
+
properties: {
|
|
740
|
+
apply: { type: "boolean", title: "Apply this change", description: `${plan.action} ${plan.path} on ${plan.site}` },
|
|
741
|
+
},
|
|
742
|
+
required: ["apply"],
|
|
743
|
+
},
|
|
744
|
+
}, { timeout: 10 * 60 * 1000 }); // give the user time to read the diff
|
|
745
|
+
} catch (err) {
|
|
746
|
+
if (/does not support/i.test(err.message)) return "unsupported";
|
|
747
|
+
throw err;
|
|
748
|
+
}
|
|
749
|
+
return answer.action === "accept" && answer.content?.apply === true ? "confirmed" : "declined";
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
server.registerTool(
|
|
753
|
+
"plan_vtl_change",
|
|
754
|
+
{
|
|
755
|
+
title: "Plan a VTL file change in dotCMS",
|
|
756
|
+
description:
|
|
757
|
+
"Step 1 of 2 for every write. Does NOT change dotCMS: it validates the target, compares the new " +
|
|
758
|
+
"source with the current file and returns a plan (action, target, diff, warnings) with a planId. " +
|
|
759
|
+
`Writable locations: ${roots} — scripting-API files (e.g. /application/apivtl/my-endpoint/get.vtl, ` +
|
|
760
|
+
"file name = HTTP method) and custom fields (e.g. /application/vtl/custom-fields/my-field/code.vtl). " +
|
|
761
|
+
"Whether it is a create or an update is detected from whether the file exists. " +
|
|
762
|
+
"Show the returned plan to the user, then call apply_vtl_change with the planId.",
|
|
763
|
+
inputSchema: {
|
|
764
|
+
path: z.string().min(1).describe(`Full path of the file, inside ${roots}`),
|
|
765
|
+
site: z
|
|
766
|
+
.string()
|
|
767
|
+
.optional()
|
|
768
|
+
.describe("Site host name. Required for a new file, or when the path exists on several sites"),
|
|
769
|
+
content: z
|
|
770
|
+
.string()
|
|
771
|
+
.min(1)
|
|
772
|
+
.max(MAX_FILE_CHARS)
|
|
773
|
+
.describe("Full Velocity source of the file (the whole file, not a patch)"),
|
|
774
|
+
languageId: z.number().int().optional().describe("Language id (default: the default language)"),
|
|
775
|
+
publish: z
|
|
776
|
+
.boolean()
|
|
777
|
+
.default(false)
|
|
778
|
+
.describe("Publish immediately. Default false: save a working version only, the live file stays as it is"),
|
|
779
|
+
},
|
|
780
|
+
annotations: READ_ONLY,
|
|
781
|
+
},
|
|
782
|
+
async ({ path, site, content, languageId, publish }) => {
|
|
783
|
+
try {
|
|
784
|
+
const target = parseWritePath(path);
|
|
785
|
+
if (site !== undefined) assertSite(site);
|
|
786
|
+
const files = await findFiles({ path: target.full, site });
|
|
787
|
+
|
|
788
|
+
let action = "CREATE";
|
|
789
|
+
let base = null;
|
|
790
|
+
let current = "";
|
|
791
|
+
if (files.length) {
|
|
792
|
+
const { file } = pickVersion(files, { what: target.full, site, languageId });
|
|
793
|
+
action = "UPDATE";
|
|
794
|
+
base = { identifier: file.identifier, inode: file.inode, live: !!file.live };
|
|
795
|
+
site = file.hostName;
|
|
796
|
+
languageId = file.languageId;
|
|
797
|
+
current = await downloadFile(file);
|
|
798
|
+
} else if (!site) {
|
|
799
|
+
throw new Error(`${target.full} does not exist yet. Pass 'site' to plan creating it.`);
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const changes = diffLines(current, content);
|
|
803
|
+
if (action === "UPDATE" && !changes.length) {
|
|
804
|
+
throw new Error("Nothing to do: the new content is identical to the current file.");
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const warnings = [];
|
|
808
|
+
if (publish) warnings.push("publish is on — the change goes live as soon as it is applied.");
|
|
809
|
+
if (/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\./.test(content)) {
|
|
810
|
+
warnings.push("the content contains what looks like an API token (JWT).");
|
|
811
|
+
}
|
|
812
|
+
const hints = [];
|
|
813
|
+
if (action === "UPDATE" && !publish && base.live) {
|
|
814
|
+
hints.push("The file has a live version: it keeps serving the old content until this change is published.");
|
|
815
|
+
}
|
|
816
|
+
if (target.kind === "custom-field" && action === "CREATE") {
|
|
817
|
+
hints.push(`To use it, set the Custom-Field value to: #dotParse("//${site}${target.full}")`);
|
|
818
|
+
}
|
|
819
|
+
if (target.kind === "api" && action === "CREATE") {
|
|
820
|
+
const endpoint = target.folder.slice(target.root.length).replace(/\/$/, "");
|
|
821
|
+
hints.push(
|
|
822
|
+
`Once published it answers ${target.fileName.replace(/\.vtl$/i, "").toUpperCase()} ${BASE_URL}/api/vtl/${endpoint}`,
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const plan = savePlan({
|
|
827
|
+
action,
|
|
828
|
+
kind: target.kind,
|
|
829
|
+
instance: BASE_URL,
|
|
830
|
+
site,
|
|
831
|
+
path: target.full,
|
|
832
|
+
folder: target.folder,
|
|
833
|
+
fileName: target.fileName,
|
|
834
|
+
languageId,
|
|
835
|
+
publish,
|
|
836
|
+
content,
|
|
837
|
+
base,
|
|
838
|
+
changes,
|
|
839
|
+
warnings,
|
|
840
|
+
hints,
|
|
841
|
+
});
|
|
842
|
+
planFingerprints.set(plan.id, fingerprint(plan));
|
|
843
|
+
|
|
844
|
+
return {
|
|
845
|
+
content: [
|
|
846
|
+
{
|
|
847
|
+
type: "text",
|
|
848
|
+
text:
|
|
849
|
+
renderPlan(plan) +
|
|
850
|
+
`\n\nplanId: ${plan.id}\nNothing has been written. Show this plan to the user; to carry it out call ` +
|
|
851
|
+
"apply_vtl_change with this planId.",
|
|
852
|
+
},
|
|
853
|
+
],
|
|
854
|
+
};
|
|
855
|
+
} catch (err) {
|
|
856
|
+
return fail(err);
|
|
857
|
+
}
|
|
858
|
+
},
|
|
859
|
+
);
|
|
860
|
+
|
|
861
|
+
server.registerTool(
|
|
862
|
+
"apply_vtl_change",
|
|
863
|
+
{
|
|
864
|
+
title: "Apply a planned VTL file change to dotCMS",
|
|
865
|
+
description:
|
|
866
|
+
"Step 2 of 2. WRITES to dotCMS: creates or updates the VTL file exactly as described by a plan from " +
|
|
867
|
+
"plan_vtl_change. Takes only the planId, so nothing but the planned content can be written. " +
|
|
868
|
+
"Only call it after the user has seen the plan and agreed to it. When the client supports it, the server " +
|
|
869
|
+
"also asks the user to confirm. A plan works once, only in the server session that made it, and expires after 30 minutes; " +
|
|
870
|
+
"it is rejected if the file changed in dotCMS after the plan was made.",
|
|
871
|
+
inputSchema: {
|
|
872
|
+
planId: z.string().min(1).describe("planId returned by plan_vtl_change"),
|
|
873
|
+
},
|
|
874
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
|
|
875
|
+
},
|
|
876
|
+
async ({ planId }) => {
|
|
877
|
+
try {
|
|
878
|
+
const plan = loadPlan(planId);
|
|
879
|
+
if (planFingerprints.get(plan.id) !== fingerprint(plan)) {
|
|
880
|
+
throw new Error(
|
|
881
|
+
`Plan ${plan.id} was not made by this server session, or its file was changed afterwards. Make a new plan with plan_vtl_change.`,
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
if (plan.instance !== BASE_URL) {
|
|
885
|
+
throw new Error(`Plan ${plan.id} was made for ${plan.instance}, but this server is connected to ${BASE_URL}.`);
|
|
886
|
+
}
|
|
887
|
+
// Never trust the stored plan for where it may write: check it again.
|
|
888
|
+
const target = parseWritePath(plan.path);
|
|
889
|
+
if (target.folder !== plan.folder || target.fileName !== plan.fileName) {
|
|
890
|
+
throw new Error(`Plan ${plan.id} is inconsistent. Make a new plan with plan_vtl_change.`);
|
|
891
|
+
}
|
|
892
|
+
assertSite(plan.site);
|
|
893
|
+
|
|
894
|
+
if ((await confirmWithUser(plan)) === "declined") {
|
|
895
|
+
throw new Error(`The user declined plan ${plan.id}. Nothing was written.`);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// The plan must still describe reality.
|
|
899
|
+
const files = (await findFiles({ path: plan.path, site: plan.site })).filter(
|
|
900
|
+
(f) => plan.action === "CREATE" || f.languageId === plan.languageId,
|
|
901
|
+
);
|
|
902
|
+
if (plan.action === "CREATE" && files.length) {
|
|
903
|
+
throw new Error(`${plan.path} was created on ${plan.site} after the plan was made. Make a new plan.`);
|
|
904
|
+
}
|
|
905
|
+
if (plan.action === "UPDATE" && files[0]?.inode !== plan.base.inode) {
|
|
906
|
+
throw new Error(`${plan.path} changed in dotCMS after the plan was made. Make a new plan.`);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
const folderError = plan.action === "CREATE" ? await ensureFolder(plan.site, plan.folder) : null;
|
|
910
|
+
let saved;
|
|
911
|
+
try {
|
|
912
|
+
saved = await saveFile({
|
|
913
|
+
site: plan.site,
|
|
914
|
+
folder: plan.folder,
|
|
915
|
+
fileName: plan.fileName,
|
|
916
|
+
content: plan.content,
|
|
917
|
+
identifier: plan.base?.identifier,
|
|
918
|
+
languageId: plan.languageId,
|
|
919
|
+
publish: plan.publish,
|
|
920
|
+
});
|
|
921
|
+
} catch (err) {
|
|
922
|
+
if (folderError) err.message += ` (creating folder ${plan.folder} also failed: ${folderError})`;
|
|
923
|
+
throw err;
|
|
924
|
+
}
|
|
925
|
+
deletePlan(plan.id);
|
|
926
|
+
planFingerprints.delete(plan.id);
|
|
927
|
+
|
|
928
|
+
return ok({
|
|
929
|
+
result: `${plan.action === "CREATE" ? "Created" : "Updated"} ${plan.path} on ${plan.site}`,
|
|
930
|
+
planId: plan.id,
|
|
931
|
+
workflowAction: saved.action,
|
|
932
|
+
published: !!plan.publish,
|
|
933
|
+
note: plan.publish
|
|
934
|
+
? "The file is live."
|
|
935
|
+
: "Saved as a working (unpublished) version. The live file is unchanged until it is published.",
|
|
936
|
+
identifier: saved.entity.identifier,
|
|
937
|
+
inode: saved.entity.inode,
|
|
938
|
+
languageId: saved.entity.languageId,
|
|
939
|
+
});
|
|
940
|
+
} catch (err) {
|
|
941
|
+
return fail(err);
|
|
942
|
+
}
|
|
943
|
+
},
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
await server.connect(new StdioServerTransport());
|
|
948
|
+
console.error(
|
|
949
|
+
`dotcms-mcp running (${BASE_URL}${TOKEN ? "" : ", no DOTCMS_TOKEN set"}, ` +
|
|
950
|
+
`${ALLOW_WRITE ? `writes enabled under ${WRITE_ROOTS.join(", ")}` : "read-only"})`,
|
|
951
|
+
);
|
|
952
|
+
if (INSECURE_TRANSPORT) {
|
|
953
|
+
console.error("WARNING: DOTCMS_URL is plain http on a remote host — the API token is sent unencrypted. Use https.");
|
|
954
|
+
}
|