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 CHANGED
@@ -1,3 +1,258 @@
1
- # Temporary Holding Version
1
+ # dotcms-custom-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Model Context Protocol](https://modelcontextprotocol.io) server for [dotCMS](https://www.dotcms.com). It lets an AI assistant (GitHub Copilot, Claude Code, Claude Desktop, Cursor, …) inspect content types and their fields, and read — and optionally write — Velocity (VTL) files in a dotCMS instance.
4
+
5
+ - **Read-only by default.** Write tools are only exposed when you opt in.
6
+ - **Writes are plan-first.** A change is planned and shown as a diff before anything is saved, and is limited to folders you allow.
7
+ - **No install step.** Runs over stdio through `npx`.
8
+
9
+ ## Requirements
10
+
11
+ - Node.js 20.18.1 or newer
12
+ - A dotCMS instance reachable from the machine that runs your AI client
13
+ - A dotCMS API token (dotCMS admin → your user → *API Access Tokens*)
14
+
15
+ ## Quick start
16
+
17
+ ```bash
18
+ DOTCMS_URL=https://your-dotcms.example.com DOTCMS_TOKEN=your-token npx -y dotcms-custom-mcp
19
+ ```
20
+
21
+ The server speaks MCP over stdio, so you normally don't run it by hand — your AI client starts it using one of the configurations below.
22
+
23
+ ## Configuration
24
+
25
+ All configuration is through environment variables.
26
+
27
+ | Variable | Default | Purpose |
28
+ | --- | --- | --- |
29
+ | `DOTCMS_URL` | `http://localhost:8080` | Base URL of the dotCMS instance |
30
+ | `DOTCMS_TOKEN` | *(none)* | API token, sent as a `Bearer` token |
31
+ | `DOTCMS_ALLOW_WRITE` | `false` | Set to `true` to expose the write tools |
32
+ | `DOTCMS_WRITE_ROOTS` | `/application/apivtl/,/application/vtl/custom-fields/` | Comma-separated folders the write tools are limited to |
33
+ | `DOTCMS_READ_EXTENSIONS` | `vtl` | Comma-separated file extensions the read tools may return |
34
+ | `DOTCMS_CONFIRM` | *(on)* | Set to `off` to skip the server's own confirmation prompt before a write |
35
+ | `DOTCMS_SITE_URL` | *(none)* | Public URL of the website, e.g. `https://www.example.com`. Lets the SEO tools also check the rendered HTML. The API token is never sent to it. With several sites, use a host name or alias of the site you check; the report warns when it is not one |
36
+ | `DOTCMS_PLANS_DIR` | `~/.dotcms-mcp/plans` | Where pending change plans are stored |
37
+
38
+ ### Behind a proxy
39
+
40
+ The server honours the standard `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables for every request to dotCMS. Add them to the `env` block of your client configuration:
41
+
42
+ ```json
43
+ "env": {
44
+ "DOTCMS_URL": "https://your-dotcms.example.com",
45
+ "DOTCMS_TOKEN": "your-token",
46
+ "HTTPS_PROXY": "http://proxy.example.com:8080",
47
+ "NO_PROXY": "localhost,127.0.0.1"
48
+ }
49
+ ```
50
+
51
+ Keep `localhost` in `NO_PROXY` when dotCMS runs on your own machine, otherwise the request is sent to the proxy, which cannot reach it.
52
+
53
+ ## Client setup
54
+
55
+ ### GitHub Copilot (VS Code)
56
+
57
+ Create `.vscode/mcp.json` in your workspace, then start the server from the editor and use Copilot Chat in Agent mode. VS Code prompts for the token once and stores it securely.
58
+
59
+ ```json
60
+ {
61
+ "inputs": [
62
+ {
63
+ "id": "dotcms-token",
64
+ "type": "promptString",
65
+ "description": "dotCMS API token",
66
+ "password": true
67
+ }
68
+ ],
69
+ "servers": {
70
+ "dotcms": {
71
+ "type": "stdio",
72
+ "command": "npx",
73
+ "args": ["-y", "dotcms-custom-mcp"],
74
+ "env": {
75
+ "DOTCMS_URL": "https://your-dotcms.example.com",
76
+ "DOTCMS_TOKEN": "${input:dotcms-token}"
77
+ }
78
+ }
79
+ }
80
+ }
81
+ ```
82
+
83
+ ### Claude Code
84
+
85
+ ```bash
86
+ claude mcp add dotcms --env DOTCMS_URL=https://your-dotcms.example.com --env DOTCMS_TOKEN=your-token -- npx -y dotcms-custom-mcp
87
+ ```
88
+
89
+ ### Claude Desktop, Cursor and other clients
90
+
91
+ Add the server to the client's MCP configuration:
92
+
93
+ ```json
94
+ {
95
+ "mcpServers": {
96
+ "dotcms": {
97
+ "command": "npx",
98
+ "args": ["-y", "dotcms-custom-mcp"],
99
+ "env": {
100
+ "DOTCMS_URL": "https://your-dotcms.example.com",
101
+ "DOTCMS_TOKEN": "your-token"
102
+ }
103
+ }
104
+ }
105
+ }
106
+ ```
107
+
108
+ ## Tools
109
+
110
+ ### Always available (read-only)
111
+
112
+ | Tool | What it does |
113
+ | --- | --- |
114
+ | `list_content_types` | Lists content types, with optional name filter, base-type filter and paging |
115
+ | `get_content_type_fields` | Returns the fields of a content type (variable, type, data type, required/unique/indexed flags, field variables, relationships). Layout-only fields are hidden unless requested |
116
+ | `get_content_type_relations` | Shows the relationship tree of a content type: its relationship fields, the related content types and their relationships in turn, with cardinality and sides. Also lists category fields and relationships declared only on other types |
117
+ | `analyze_seo` | Checks the SEO of a page or content item and reports errors, warnings and notes. Regular pages are checked from the page; detail pages (URL-mapped content) and content items are checked from the content and its content type |
118
+ | `audit_seo_pages` | Checks the SEO of every live page under a folder and reports one line per page, most serious first, plus the most common problems across the pages |
119
+ | `list_vtl_files` | Finds VTL files by folder and/or file name, with paging |
120
+ | `read_vtl_file` | Returns the source of a VTL file by path or identifier, optionally for a specific site or language |
121
+
122
+ The two file tools only return files whose extension is listed in `DOTCMS_READ_EXTENSIONS`.
123
+
124
+ #### Relationship tree
125
+
126
+ `get_content_type_relations` takes a content type and follows its relationships to the depth you ask for (1–5, default 2). It returns a text drawing and the same tree as JSON:
127
+
128
+ ```
129
+ Blog (Blog)
130
+ ├─ author ─► BlogAuthor [MANY_TO_MANY, child side, other field: blog]
131
+ │ └─ blog ─► Blog [MANY_TO_MANY, parent side] (already shown above)
132
+ └─ blogComment ─► BlogComment [ONE_TO_MANY, parent side]
133
+ ├─ blog ─► Blog [ONE_TO_MANY, child side, other field: blogComment] (already shown above)
134
+ └─ commentAuthor ─► BlogCommentor [ONE_TO_MANY, child side, other field: blogComment]
135
+ ```
136
+
137
+ | Option | Default | Purpose |
138
+ | --- | --- | --- |
139
+ | `depth` | `2` | Levels of related content types to follow |
140
+ | `includeIncoming` | `true` | Also find relationships that only another content type declares (marked `◄─`). This scans all content types, so the token needs permission to list them |
141
+ | `includeFields` | `false` | Also list the other fields of every content type in the tree |
142
+
143
+ A type that was already shown higher up is not expanded again, so circular relationships don't loop.
144
+
145
+ #### SEO analysis
146
+
147
+ `analyze_seo` checks one page and returns a text report plus the same findings as JSON. Give it either a page `path`, or a `contentType` with an `identifier`:
148
+
149
+ | You give | It checks |
150
+ | --- | --- |
151
+ | `path` of a regular (drag-and-drop) page | The page's own fields: title and description |
152
+ | `path` of a detail page (URL-mapped content) | The mapped content's fields, plus its **content type**: does it have title, description and image fields, and is the URL map pattern sensible |
153
+ | `contentType` + `identifier` | The content item and its content type; the URL is built from the URL map pattern |
154
+
155
+ What it looks for:
156
+
157
+ - title and description present, and within 30–60 and 70–160 characters
158
+ - title identical to the description
159
+ - URL shape: length, uppercase, underscores, spaces, file extensions, depth
160
+ - missing image for social previews
161
+ - content types with no description field, no URL map pattern, or a pattern built from an id
162
+
163
+ Set `DOTCMS_SITE_URL` to also check the **rendered HTML**, the way a crawler sees it: `<title>`, meta description, canonical link, robots `noindex`, number of `<h1>` headings, Open Graph tags, images without `alt`, `lang`, viewport and structured data. Without it, the report says the HTML was not checked. The public site is fetched anonymously; the dotCMS token is never sent there.
164
+
165
+ Options: `site` is the site's host name (or alias) and is needed when the page is not on the instance's default site; without it a miss says so. `languageId` picks a language. The live version is analysed, because that is what search engines see.
166
+
167
+ When the rendered HTML is checked and dotCMS has a title or description that the page does not output, the report says so: that points at the template, not at the content.
168
+
169
+ **Headless sites.** If the site is a front-end app that sets its own title and meta tags in the browser, the server HTML is an empty shell and every page will show an empty `<title>` and no `<h1>`. In that case leave `DOTCMS_SITE_URL` unset and rely on the field checks, or point it at the real public front-end rather than the dotCMS delivery domain.
170
+
171
+ #### SEO audit of many pages
172
+
173
+ `audit_seo_pages` checks every live page under a folder, so you can see which pages need attention first. It lists the pages with one content search and checks each page's own fields, with the same checks `analyze_seo` runs for a regular page.
174
+
175
+ ```
176
+ SEO audit: /blog on demo.dotcms.com (batch 1)
177
+
178
+ 3 page(s) checked: 0 with errors · 2 with warnings only · 1 without problems
179
+
180
+ ⚠2 /blog/first-post — Title (title) is 2 characters; aim for 30–60. · No description value found.
181
+ ⚠1 /blog/second_post — The URL uses underscores; hyphens are read as word separators, underscores are not.
182
+ ✓ /blog
183
+
184
+ Most common problems:
185
+ 1 page(s) · description-missing (warning)
186
+ 1 page(s) · title-short (warning)
187
+ ```
188
+
189
+ | Option | Default | Purpose |
190
+ | --- | --- | --- |
191
+ | `folder` | `/` | Folder to audit, including subfolders |
192
+ | `site` | none | Site host name (or alias). The search is limited to that site, so totals and batches count only its pages. Required when the pages exist on several sites |
193
+ | `languageId` | lowest per page | Which language version to check |
194
+ | `limit`, `page` | 25, 1 | Pages per call (up to 100), and which batch. The report says when more pages exist |
195
+ | `onlyIssues` | `false` | List only pages with errors or warnings |
196
+
197
+ With `DOTCMS_SITE_URL` set, each page's rendered HTML is also checked, four pages at a time, for up to about 45 seconds; pages after that are checked from their fields only, and the report says how many. Detail pages (URL-mapped content) are not pages in dotCMS, so check those one at a time with `analyze_seo`.
198
+
199
+ ### Only with `DOTCMS_ALLOW_WRITE=true`
200
+
201
+ | Tool | What it does |
202
+ | --- | --- |
203
+ | `plan_vtl_change` | Prepares a create or update of a VTL file and returns a plan: target, publish flag, line diff and warnings. Writes nothing |
204
+ | `apply_vtl_change` | Applies a previously created plan by its `planId` |
205
+
206
+ ## How writing works
207
+
208
+ 1. The assistant calls `plan_vtl_change` with the full new file content. The server compares it with the current file and stores a plan.
209
+ 2. The plan is shown: instance, site, path, language, whether it publishes, and the changed lines.
210
+ 3. The assistant calls `apply_vtl_change` with the `planId`. Only what the plan contains can be written.
211
+
212
+ Safeguards:
213
+
214
+ - Paths outside `DOTCMS_WRITE_ROOTS` are rejected.
215
+ - The site must be a plain host name.
216
+ - A plan is valid for 30 minutes, can be used once, and only in the server session that created it. A plan file that was edited on disk is refused.
217
+ - By default a change is saved as a working version; the live file is only replaced when publishing is explicitly requested.
218
+ - Before writing, the server asks you to confirm through your client when the client supports MCP elicitation (VS Code does). Declining writes nothing. Set `DOTCMS_CONFIRM=off` to turn this prompt off.
219
+
220
+ If your client does not support elicitation, its own tool-approval prompt is the only check before `apply_vtl_change` runs, so keep approval enabled for that tool and do not auto-approve it.
221
+
222
+ ### Optional: confirmation hook for Claude Code
223
+
224
+ The package ships a `PreToolUse` hook that shows the full plan and asks for approval every time `apply_vtl_change` is called, and denies calls without a valid plan. If you use it, you can set `DOTCMS_CONFIRM=off` to avoid being asked twice. Add it to your Claude Code `settings.json`:
225
+
226
+ ```json
227
+ {
228
+ "hooks": {
229
+ "PreToolUse": [
230
+ {
231
+ "matcher": "mcp__.*__apply_vtl_change",
232
+ "hooks": [
233
+ {
234
+ "type": "command",
235
+ "command": "npx -y -p dotcms-custom-mcp dotcms-custom-mcp-confirm-write"
236
+ }
237
+ ]
238
+ }
239
+ ]
240
+ }
241
+ }
242
+ ```
243
+
244
+ ## Troubleshooting
245
+
246
+ - **`Cannot reach dotCMS at …`** — the instance isn't running or isn't reachable from this machine. Check `DOTCMS_URL`.
247
+ - **`analyze_seo` says the HTML was not checked** — set `DOTCMS_SITE_URL` to the public website, and make sure the machine running the server can reach it (the proxy settings apply).
248
+ - **Timeouts or connection errors on a corporate network** — set `HTTPS_PROXY` (see *Behind a proxy*); if dotCMS is local, add `localhost` to `NO_PROXY`.
249
+ - **401 / 403 responses** — the token is missing, expired, or belongs to a different instance. Tokens are per instance.
250
+ - **Write tools are missing** — set `DOTCMS_ALLOW_WRITE=true` and restart the server.
251
+ - **A write is rejected** — the path is outside `DOTCMS_WRITE_ROOTS`, or the plan expired; create a new plan.
252
+
253
+ ## Security notes
254
+
255
+ - Give the token only the permissions the assistant needs; use a read-only user if you don't need writes.
256
+ - Use `https` for any dotCMS that isn't on your own machine; the server warns at startup when the token would travel over plain `http`.
257
+ - Never commit the token. Prefer your client's secret prompt or an environment variable.
258
+ - The server sends requests only to `DOTCMS_URL`.
package/dotcms.js ADDED
@@ -0,0 +1,322 @@
1
+ // Shared dotCMS client used by the MCP server (index.js) and the confirmation hook.
2
+ //
3
+ // Config (env):
4
+ // DOTCMS_URL base URL of the dotCMS instance
5
+ // DOTCMS_TOKEN API token
6
+ // DOTCMS_ALLOW_WRITE "true" to expose the create/update tools (default: read-only)
7
+ // DOTCMS_WRITE_ROOTS comma-separated folders the write tools are limited to
8
+ // (default: /application/apivtl/,/application/vtl/custom-fields/)
9
+ // DOTCMS_READ_EXTENSIONS comma-separated file extensions the read tools may return (default: vtl)
10
+ // DOTCMS_CONFIRM "off" to skip the server's own confirmation prompt before a write
11
+ // (default: ask through the client when it supports MCP elicitation)
12
+ // HTTP_PROXY / HTTPS_PROXY / NO_PROXY standard proxy settings, honored for every request
13
+ // DOTCMS_SITE_URL public URL of the website (e.g. https://www.example.com), so the SEO tool
14
+ // can also check the rendered HTML. The API token is never sent to it.
15
+
16
+ // undici's own fetch and FormData must be used together: its fetch does not recognise the
17
+ // FormData built into Node, and Node's built-in fetch ignores the proxy variables.
18
+ import { EnvHttpProxyAgent, FormData, fetch as undiciFetch } from "undici";
19
+
20
+ export const BASE_URL = (process.env.DOTCMS_URL || "http://localhost:8080").replace(/\/+$/, "");
21
+ export const TOKEN = process.env.DOTCMS_TOKEN || "";
22
+ export const ALLOW_WRITE = /^(true|1|yes)$/i.test(process.env.DOTCMS_ALLOW_WRITE || "");
23
+ export const WRITE_ROOTS = (
24
+ process.env.DOTCMS_WRITE_ROOTS || "/application/apivtl/,/application/vtl/custom-fields/"
25
+ )
26
+ .split(",")
27
+ .map((root) => root.trim().replace(/^\/+|\/+$/g, ""))
28
+ .filter(Boolean)
29
+ .map((root) => `/${root}/`);
30
+
31
+ export const READ_EXTENSIONS = (process.env.DOTCMS_READ_EXTENSIONS || "vtl")
32
+ .split(",")
33
+ .map((ext) => ext.trim().replace(/^\./, "").toLowerCase())
34
+ .filter((ext) => /^[a-z0-9]+$/.test(ext));
35
+ export const SITE_URL = (() => {
36
+ const raw = (process.env.DOTCMS_SITE_URL || "").trim();
37
+ if (!raw) return "";
38
+ try {
39
+ const u = new URL(raw);
40
+ return /^https?:$/.test(u.protocol) ? u.origin + u.pathname.replace(/\/+$/, "") : "";
41
+ } catch {
42
+ return "";
43
+ }
44
+ })();
45
+ export const CONFIRM =!/^(off|false|0|no)$/i.test(process.env.DOTCMS_CONFIRM || "");
46
+
47
+ /** True when the token would travel unencrypted to another machine. */
48
+ export const INSECURE_TRANSPORT = (() => {
49
+ try {
50
+ const { protocol, hostname } = new URL(BASE_URL);
51
+ const local = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname.endsWith(".localhost");
52
+ return !!TOKEN && protocol === "http:" && !local;
53
+ } catch {
54
+ return false;
55
+ }
56
+ })();
57
+
58
+ /** A site is a host name; anything else could change where `site:folder` points. */
59
+ export function assertSite(site) {
60
+ if (!/^[A-Za-z0-9]([A-Za-z0-9._-]{0,251}[A-Za-z0-9])?$/.test(String(site ?? ""))) {
61
+ throw new Error(`Invalid site '${site}': pass the site host name, e.g. 'demo.dotcms.com'.`);
62
+ }
63
+ return site;
64
+ }
65
+
66
+ /** Throws unless the file name ends in one of DOTCMS_READ_EXTENSIONS. */
67
+ export function assertReadable(fileName) {
68
+ const ext = String(fileName ?? "").split(".").pop().toLowerCase();
69
+ if (!String(fileName ?? "").includes(".") || !READ_EXTENSIONS.includes(ext)) {
70
+ throw new Error(
71
+ `'${fileName}' is not a ${READ_EXTENSIONS.map((e) => `.${e}`).join(" / ")} file. ` +
72
+ "This server only reads the extensions listed in DOTCMS_READ_EXTENSIONS.",
73
+ );
74
+ }
75
+ }
76
+
77
+ const authHeaders = (extra = {}) => (TOKEN ? { ...extra, Authorization: `Bearer ${TOKEN}` } : extra);
78
+
79
+ const dispatcher = new EnvHttpProxyAgent();
80
+
81
+ async function send(path, init = {}) {
82
+ try {
83
+ return await undiciFetch(BASE_URL + path, { ...init, dispatcher, signal: AbortSignal.timeout(30_000) });
84
+ } catch (err) {
85
+ throw new Error(`Cannot reach dotCMS at ${BASE_URL}: ${err.message}`);
86
+ }
87
+ }
88
+
89
+ const siteCache = new Map();
90
+
91
+ /** A site by host name (or alias) -> { identifier, hostname }. Cached for the life of the process. */
92
+ export async function resolveSite(name) {
93
+ const wanted = String(name ?? "").trim().toLowerCase();
94
+ if (!wanted) throw new Error("Pass the site's host name.");
95
+ if (siteCache.has(wanted)) return siteCache.get(wanted);
96
+ const data = await api("/api/v1/site", { params: { filter: wanted, per_page: 25 } });
97
+ const sites = (data.entity || []).filter((s) => s.identifier && s.hostname && !s.systemHost);
98
+ const match =
99
+ sites.find((s) => s.hostname.toLowerCase() === wanted) ||
100
+ sites.find((s) => String(s.aliases || "").toLowerCase().split(/\s+/).includes(wanted));
101
+ if (!match) {
102
+ const near = sites.slice(0, 10).map((s) => s.hostname);
103
+ throw new Error(`Site '${name}' not found.${near.length ? ` Sites matching it: ${near.join(", ")}.` : ""}`);
104
+ }
105
+ const site = {
106
+ identifier: match.identifier,
107
+ hostname: match.hostname,
108
+ aliases: String(match.aliases || "").split(/\s+/).filter(Boolean),
109
+ };
110
+ siteCache.set(wanted, site);
111
+ return site;
112
+ }
113
+
114
+ const MAX_HTML_BYTES = 3_000_000;
115
+
116
+ /** The rendered HTML of a page on the public site. Anonymous: the API token is not sent here. */
117
+ export async function fetchSiteHtml(path) {
118
+ if (!SITE_URL) throw new Error("DOTCMS_SITE_URL is not set.");
119
+ let res;
120
+ try {
121
+ res = await undiciFetch(SITE_URL + path, {
122
+ headers: { Accept: "text/html", "User-Agent": "dotcms-custom-mcp" },
123
+ dispatcher,
124
+ signal: AbortSignal.timeout(30_000),
125
+ });
126
+ } catch (err) {
127
+ throw new Error(`Cannot reach ${SITE_URL}: ${err.message}`);
128
+ }
129
+ const type = res.headers.get("content-type") || "";
130
+ if (!res.ok) {
131
+ await res.body?.cancel();
132
+ throw new Error(`${SITE_URL}${path} answered ${res.status} ${res.statusText}.`);
133
+ }
134
+ if (!/html/i.test(type) || Number(res.headers.get("content-length") || 0) > MAX_HTML_BYTES) {
135
+ await res.body?.cancel();
136
+ throw new Error(`${SITE_URL}${path} did not return an HTML page of a readable size (${type || "no content type"}).`);
137
+ }
138
+ return { html: (await res.text()).slice(0, MAX_HTML_BYTES), status: res.status, finalUrl: res.url };
139
+ }
140
+
141
+ /** JSON request against the dotCMS REST API. `body` may be an object (sent as JSON) or FormData. */
142
+ export async function api(path, { method = "GET", params = {}, body } = {}) {
143
+ const query = new URLSearchParams();
144
+ for (const [key, value] of Object.entries(params)) {
145
+ if (value !== undefined && value !== null && value !== "") query.set(key, String(value));
146
+ }
147
+ const url = path + (query.size ? `?${query}` : "");
148
+
149
+ const isForm = body instanceof FormData;
150
+ const headers = authHeaders({ Accept: "application/json" });
151
+ if (body && !isForm) headers["Content-Type"] = "application/json";
152
+
153
+ const res = await send(url, {
154
+ method,
155
+ headers,
156
+ body: body === undefined ? undefined : isForm ? body : JSON.stringify(body),
157
+ });
158
+ const text = await res.text();
159
+ if (!res.ok) {
160
+ const hint =
161
+ res.status === 401 || res.status === 403
162
+ ? " Check DOTCMS_TOKEN and the token user's permissions."
163
+ : res.status === 404
164
+ ? " Check the name/id and DOTCMS_URL."
165
+ : "";
166
+ throw new Error(`dotCMS responded ${res.status} ${res.statusText}.${hint} ${text.slice(0, 400)}`);
167
+ }
168
+ try {
169
+ return JSON.parse(text);
170
+ } catch {
171
+ throw new Error(`dotCMS returned a non-JSON response from ${path}`);
172
+ }
173
+ }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // Files
177
+ // ---------------------------------------------------------------------------
178
+
179
+ // Lucene special characters, except "/" which dotCMS accepts unescaped inside wildcards.
180
+ export const escapeLucene = (s) => s.replace(/[+\-!(){}[\]^"~*?:\\&|]/g, "\\$&");
181
+
182
+ export async function searchFiles(clauses, { limit = 50, offset = 0 } = {}) {
183
+ const data = await api("/api/content/_search", {
184
+ method: "POST",
185
+ body: { query: ["+baseType:4", ...clauses].join(" "), sort: "path asc", limit, offset },
186
+ });
187
+ const entity = data.entity || {};
188
+ return { total: entity.resultsSize ?? 0, files: entity.jsonObjectView?.contentlets || [] };
189
+ }
190
+
191
+ export const normalizePath = (path) => "/" + String(path).trim().replace(/^\/+/, "");
192
+
193
+ /**
194
+ * All versions (one per site/language) of the file at an exact path, or with an identifier.
195
+ */
196
+ export async function findFiles({ path, identifier, site }) {
197
+ let files;
198
+ if (identifier) {
199
+ ({ files } = await searchFiles([`+identifier:${escapeLucene(identifier)}`], { limit: 20 }));
200
+ } else {
201
+ const wanted = normalizePath(path).toLowerCase();
202
+ ({ files } = await searchFiles([`+path:*${escapeLucene(wanted)}`], { limit: 50 }));
203
+ files = files.filter((f) => f.path?.toLowerCase() === wanted);
204
+ }
205
+ if (site) files = files.filter((f) => f.hostName?.toLowerCase() === site.toLowerCase());
206
+ return files;
207
+ }
208
+
209
+ /** Pick one language version out of findFiles() results; throws a helpful error otherwise. */
210
+ export function pickVersion(files, { what, site, languageId }) {
211
+ if (!files.length) throw new Error(`File not found: ${what}${site ? ` on site ${site}` : ""}.`);
212
+ const sites = [...new Set(files.map((f) => f.hostName))];
213
+ if (sites.length > 1) {
214
+ throw new Error(`This path exists on several sites (${sites.join(", ")}). Pass 'site'.`);
215
+ }
216
+ const languages = [...new Set(files.map((f) => f.languageId))].sort((a, b) => a - b);
217
+ const file = files.find((f) => f.languageId === (languageId ?? languages[0]));
218
+ if (!file) {
219
+ throw new Error(
220
+ `No version of this file in language ${languageId}. Available language ids: ${languages.join(", ")}.`,
221
+ );
222
+ }
223
+ return { file, languages };
224
+ }
225
+
226
+ export async function downloadFile(file) {
227
+ const name = encodeURIComponent(file.fileName || file.name || "file.vtl");
228
+ // Inode first: it pins the exact language version. The identifier URL
229
+ // would silently return the default-language version instead.
230
+ const candidates = [
231
+ `/dA/${file.inode}/fileAsset/${name}`,
232
+ `/contentAsset/raw-data/${file.inode}/fileAsset`,
233
+ `/dA/${file.identifier}/fileAsset/${name}?language_id=${file.languageId ?? ""}`,
234
+ ];
235
+ const tried = [];
236
+ for (const path of candidates) {
237
+ const res = await send(path, { headers: authHeaders({ Accept: "text/plain, */*" }) });
238
+ const type = res.headers.get("content-type") || "";
239
+ // dotCMS answers with its HTML 404 page when the file may not be served.
240
+ if (res.ok && !(type.includes("text/html") && !/\.html?$/i.test(name))) {
241
+ return await res.text();
242
+ }
243
+ tried.push(`${path} -> ${res.status}`);
244
+ await res.body?.cancel();
245
+ }
246
+ throw new Error(
247
+ `dotCMS refused to serve the file contents (${tried.join("; ")}). ` +
248
+ (TOKEN
249
+ ? "The token user probably has no read permission on this file."
250
+ : "VTL files are not served to anonymous users: set DOTCMS_TOKEN."),
251
+ );
252
+ }
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // Writing (API VTL files only)
256
+ // ---------------------------------------------------------------------------
257
+
258
+ /** Validate a path for the write tools and split it into folder + file name. */
259
+ export function parseWritePath(path) {
260
+ const full = normalizePath(path);
261
+ if (!/^[A-Za-z0-9._\-/]+$/.test(full) || full.includes("..") || full.includes("//")) {
262
+ throw new Error(`Invalid path '${path}': use only letters, digits, '.', '_', '-' and '/'.`);
263
+ }
264
+ const root = WRITE_ROOTS.find((r) => full.toLowerCase().startsWith(r.toLowerCase()));
265
+ if (!root) {
266
+ throw new Error(`Writing is limited to ${WRITE_ROOTS.join(" and ")} — '${full}' is outside of them.`);
267
+ }
268
+ if (!full.toLowerCase().endsWith(".vtl")) {
269
+ throw new Error(`Only .vtl files can be written, got '${full}'.`);
270
+ }
271
+ const cut = full.lastIndexOf("/");
272
+ const folder = full.slice(0, cut + 1);
273
+ const fileName = full.slice(cut + 1);
274
+ if (!fileName.replace(/\.vtl$/i, "")) throw new Error(`Missing file name in '${full}'.`);
275
+ if (folder.toLowerCase() === root.toLowerCase()) {
276
+ throw new Error(`Put the file in its own folder, e.g. ${root}my-name/${fileName}.`);
277
+ }
278
+ const kind = /\/apivtl\//i.test(root) ? "api" : /\/custom-fields\//i.test(root) ? "custom-field" : "vtl";
279
+ return { full, folder, fileName, root, kind };
280
+ }
281
+
282
+ /**
283
+ * Create a new file asset, or a new version of an existing one (when `identifier` is given),
284
+ * through the dotCMS workflow API. Not published unless `publish` is true.
285
+ */
286
+ export async function saveFile({ site, folder, fileName, content, identifier, languageId, publish }) {
287
+ assertSite(site);
288
+ const contentlet = {
289
+ contentType: "FileAsset",
290
+ title: fileName,
291
+ fileName,
292
+ hostFolder: `${site}:${folder}`,
293
+ };
294
+ if (identifier) contentlet.identifier = identifier;
295
+ if (languageId) contentlet.languageId = languageId;
296
+
297
+ const form = new FormData();
298
+ form.append("json", JSON.stringify({ contentlet }));
299
+ form.append("file", new Blob([content], { type: "text/plain" }), fileName);
300
+
301
+ const action = publish ? "PUBLISH" : identifier ? "EDIT" : "NEW";
302
+ const data = await api(`/api/v1/workflow/actions/default/fire/${action}`, {
303
+ method: "PUT",
304
+ params: { indexPolicy: "WAIT_FOR" },
305
+ body: form,
306
+ });
307
+ return { action, entity: data.entity || {} };
308
+ }
309
+
310
+ /** Make sure a folder exists. Returns an error message instead of throwing. */
311
+ export async function ensureFolder(site, folder) {
312
+ try {
313
+ assertSite(site);
314
+ await api(`/api/v1/folder/createfolders/${encodeURIComponent(site)}`, {
315
+ method: "POST",
316
+ body: [folder],
317
+ });
318
+ return null;
319
+ } catch (err) {
320
+ return err.message;
321
+ }
322
+ }
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ // Claude Code PreToolUse hook: the human check of the plan -> human check -> write flow.
3
+ //
4
+ // apply_vtl_change is the only dotcms MCP tool that writes. This hook never lets it through
5
+ // on its own: it loads the plan the call refers to and answers "ask", so Claude Code shows
6
+ // the plan (target, publish flag, diff, warnings) and the write only happens if the user
7
+ // approves it. A call without a valid, unexpired plan is denied. Other tools are left alone.
8
+
9
+ import fs from "node:fs";
10
+ import { loadPlan, renderPlan } from "../plans.js";
11
+
12
+ const decide = (permissionDecision, reason) => {
13
+ process.stdout.write(
14
+ JSON.stringify({
15
+ hookSpecificOutput: {
16
+ hookEventName: "PreToolUse",
17
+ permissionDecision,
18
+ permissionDecisionReason: reason,
19
+ },
20
+ }),
21
+ );
22
+ process.exit(0);
23
+ };
24
+
25
+ let input;
26
+ try {
27
+ input = JSON.parse(fs.readFileSync(0, "utf8"));
28
+ } catch {
29
+ process.exit(0); // not a hook payload: stay out of the way
30
+ }
31
+ // Whatever name the server was registered under.
32
+ if (!/^mcp__.+__apply_vtl_change$/.test(String(input.tool_name ?? ""))) process.exit(0);
33
+
34
+ let plan;
35
+ try {
36
+ plan = loadPlan(input.tool_input?.planId);
37
+ } catch (err) {
38
+ decide("deny", `dotCMS write blocked: ${err.message}`);
39
+ }
40
+
41
+ decide("ask", `Approve this dotCMS change?\n\n${renderPlan(plan)}`);