@nera-static/mcp 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,254 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { hasErrors, validateSite } from '@nera-static/validate'
4
+ import { z } from 'zod'
5
+ import { PathError, resolveInRoot } from '../paths.js'
6
+ import { ok, tool, ToolError } from '../results.js'
7
+ import { relativeTo, resolveSite, siteFolders, siteInput } from './sites.js'
8
+
9
+ const PLUGIN_SCOPE = '@nera-static/'
10
+ const PLUGIN_NAME = /^[a-z0-9][a-z0-9-]*$/
11
+ const NOT_PLUGINS = new Set(['utils'])
12
+ /** A folder name `nera new` accepts, or `.` for the root itself. */
13
+ const SITE_FOLDER = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
14
+ /** A theme or starter package: a bare name (`blog`) or an npm package (`@scope/name`, `nera-starter-x`). */
15
+ const PACKAGE_SPEC = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
16
+ /** A starter on GitHub: `github:owner/repo` or `https://github.com/owner/repo`, each with an optional `#ref`. */
17
+ const GITHUB_STARTER = /^(?:github:|https:\/\/github\.com\/)[\w.-]+\/[\w.-]+(?:#[\w./-]+)?$/
18
+ /** A starter folder: a path starting with `.` or `/`, checked against the root. */
19
+ const LOCAL_STARTER = /^[./]/
20
+ /** How much of a command's log a tool result carries (its end). */
21
+ const LOG_TAIL = 4000
22
+
23
+ function tail(text) {
24
+ const trimmed = text.trim()
25
+ return trimmed.length > LOG_TAIL ? `…${trimmed.slice(-LOG_TAIL)}` : trimmed
26
+ }
27
+
28
+ /**
29
+ * The command's own error text (its stderr, else its stdout), for a failure message.
30
+ *
31
+ * @param {{ code: number|null, stdout: string, stderr: string }} run
32
+ * @returns {string}
33
+ */
34
+ export function failureText(run) {
35
+ return tail(run.stderr) || tail(run.stdout) || `exit code ${run.code}`
36
+ }
37
+
38
+ function countBySeverity(results) {
39
+ const errors = results.filter((r) => r.severity === 'error').length
40
+ return { errors, warnings: results.length - errors }
41
+ }
42
+
43
+ /**
44
+ * The `--starter` value for `nera new`: a package name as given, or a local
45
+ * starter folder checked against the root and passed relative to it (the
46
+ * command runs in the root).
47
+ */
48
+ async function starterArg(ctx, starter) {
49
+ if (PACKAGE_SPEC.test(starter) || GITHUB_STARTER.test(starter)) {
50
+ return starter
51
+ }
52
+ if (LOCAL_STARTER.test(starter)) {
53
+ const real = await resolveInRoot(ctx.root, starter, { label: 'starter folder' })
54
+ return `./${relativeTo(ctx.root, real)}`
55
+ }
56
+ throw new ToolError(`Invalid starter "${starter}". Use a starter name from list_starters (e.g. \`blog\`), a package name (\`@nera-static/starter-blog\`), a GitHub repository (\`github:owner/repo\`) or a starter folder inside the root (\`./my-starter\`).`)
57
+ }
58
+
59
+ /**
60
+ * The npm package of an `add_plugin` spec: `@nera-static/plugin-<name>` or
61
+ * just `<name>`; anything else (another scope, a version, a path, a URL) is
62
+ * refused.
63
+ */
64
+ function pluginPackage(spec) {
65
+ const name = spec.startsWith(`${PLUGIN_SCOPE}plugin-`) ? spec.slice(`${PLUGIN_SCOPE}plugin-`.length) : spec
66
+ if (!PLUGIN_NAME.test(name) || NOT_PLUGINS.has(name)) {
67
+ throw new ToolError(`"${spec}" is not a Nera plugin. Pass an official plugin as \`@nera-static/plugin-<name>\` or just \`<name>\` (e.g. \`sitemap\`); call list_plugins for the catalog.`)
68
+ }
69
+ return { name, pkg: `${PLUGIN_SCOPE}plugin-${name}` }
70
+ }
71
+
72
+ /**
73
+ * Copies the plugin's default `config/<name>.yaml` into the site's config
74
+ * folder when the site has none, so the model can read and edit it.
75
+ *
76
+ * @returns {Promise<{ file: string, status: 'copied'|'kept'|'none' }>}
77
+ */
78
+ async function copyDefaultConfig(dir, packageDir, configFolder, name) {
79
+ const target = await resolveInRoot(dir, path.join(configFolder, `${name}.yaml`), { label: 'plugin config file' })
80
+ const file = relativeTo(dir, target)
81
+ let source
82
+ try {
83
+ source = await resolveInRoot(dir, path.join(packageDir, 'config', `${name}.yaml`), { label: 'plugin default config' })
84
+ await fs.access(source)
85
+ } catch (error) {
86
+ if (error instanceof PathError || error.code === 'ENOENT') return { file, status: 'none' }
87
+ throw error
88
+ }
89
+ await fs.mkdir(path.dirname(target), { recursive: true })
90
+ try {
91
+ await fs.copyFile(source, target, fs.constants.COPYFILE_EXCL)
92
+ return { file, status: 'copied' }
93
+ } catch (error) {
94
+ if (error.code === 'EEXIST') return { file, status: 'kept' }
95
+ throw error
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The package's template-publishing script (the `bin` entry that points at
101
+ * `publish-template.js`), checked to stay inside the site, or null.
102
+ */
103
+ async function publishTemplateScript(dir, packageDir) {
104
+ let pkg
105
+ try {
106
+ pkg = JSON.parse(await fs.readFile(path.join(dir, packageDir, 'package.json'), 'utf8'))
107
+ } catch {
108
+ return null
109
+ }
110
+ const bins = typeof pkg.bin === 'string' ? [pkg.bin] : Object.values(pkg.bin ?? {})
111
+ const script = bins.find((bin) => typeof bin === 'string' && path.basename(bin) === 'publish-template.js')
112
+ if (!script) return null
113
+ return resolveInRoot(dir, path.join(packageDir, script), { label: 'plugin template script' })
114
+ }
115
+
116
+ /**
117
+ * Registers `create_site`, `build`, `validate` and `add_plugin`.
118
+ *
119
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
120
+ * @param {{ root: string, runner: ReturnType<typeof import('../runner.js').createRunner> }} ctx
121
+ */
122
+ export function registerCliTools(server, ctx) {
123
+ server.registerTool('create_site', {
124
+ title: 'Create a Nera site',
125
+ description: 'Creates a new Nera static site in a new folder of the root folder (`nera new`), installs its packages and returns the folder to pass as `site` to every other tool. Pick a starter from list_starters (`blank`, `blog`, `business`, `portfolio`) to begin with sample pages and a theme, or a theme from list_themes; with neither you get a minimal site. This can take a minute (npm install). Afterwards call get_site, then edit pages with write_page.',
126
+ inputSchema: {
127
+ name: z.string().describe('The new folder, created directly in the root: letters, digits, `.`, `-`, `_` (e.g. `my-bakery`). `.` creates the site in the root itself, which must then be empty.'),
128
+ starter: z.string().optional().describe('A starter kit from list_starters, e.g. `blog` or `@nera-static/starter-business`. Leave out for a minimal site.'),
129
+ theme: z.string().optional().describe('A theme from list_themes, e.g. `blog` or `@nera-static/theme-business`, when no starter is given (a starter brings its own theme).'),
130
+ title: z.string().optional().describe('The site\'s name as visitors see it (written to config/app.yaml).'),
131
+ lang: z.string().optional().describe('The site\'s language code, e.g. `en` or `de`.'),
132
+ },
133
+ }, tool(async ({ name, starter, theme, title, lang }, { signal }) => {
134
+ const inRoot = name === '.' || name === './'
135
+ if (!inRoot && !SITE_FOLDER.test(name)) {
136
+ throw new ToolError(`Invalid site folder "${name}". Use one folder name made of letters, digits, \`.\`, \`-\` and \`_\`, starting with a letter or digit (e.g. \`my-site\`), or \`.\` for the root itself.`)
137
+ }
138
+ const target = await resolveInRoot(ctx.root, inRoot ? '.' : name, { label: 'site folder' })
139
+ if (!inRoot && await exists(target)) {
140
+ throw new ToolError(`"${name}" already exists in ${ctx.root}. Choose another name, or call list_sites to work on an existing site.`)
141
+ }
142
+ if (theme !== undefined && !PACKAGE_SPEC.test(theme)) {
143
+ throw new ToolError(`Invalid theme "${theme}". Use a theme name from list_themes (e.g. \`blog\`) or a package name (\`@nera-static/theme-blog\`).`)
144
+ }
145
+
146
+ const args = ['new', inRoot ? '.' : name, '--yes']
147
+ if (starter !== undefined) args.push(`--starter=${await starterArg(ctx, starter)}`)
148
+ if (theme !== undefined) args.push(`--theme=${theme}`)
149
+ if (title !== undefined) args.push(`--name=${title}`)
150
+ if (lang !== undefined) args.push(`--lang=${lang}`)
151
+
152
+ const run = await ctx.runner('nera', args, { cwd: ctx.root, signal })
153
+ if (run.code !== 0 || !await exists(path.join(target, 'package.json'))) {
154
+ throw new ToolError(`Creating the site failed: ${failureText(run)}`)
155
+ }
156
+ const site = relativeTo(ctx.root, target)
157
+ return ok(
158
+ { site, log: tail(run.stdout) },
159
+ `Created the Nera site "${site}". Call get_site with site "${site}" to see its pages, then edit them with write_page.`,
160
+ )
161
+ }))
162
+
163
+ server.registerTool('build', {
164
+ title: 'Build a Nera site',
165
+ description: 'Builds a Nera site (`nera build`): renders its Markdown pages through their layouts into plain HTML in its output folder (`public/`), which is what gets published. With `check: true` it then checks the built HTML for accessibility, privacy and legal problems and returns those findings. Call validate first to catch broken layouts and YAML; call preview to look at the result in a browser.',
166
+ inputSchema: {
167
+ site: siteInput,
168
+ check: z.boolean().optional().describe('Also check the built HTML (accessibility, privacy, legal hints). Default false.'),
169
+ },
170
+ }, tool(async ({ site, check = false }, { signal }) => {
171
+ const resolved = await resolveSite(ctx, site)
172
+ const args = ['build', '--json', ...(check ? ['--check'] : [])]
173
+ const run = await ctx.runner('nera', args, { cwd: resolved.dir, signal })
174
+ let parsed
175
+ try {
176
+ parsed = JSON.parse(run.stdout)
177
+ } catch {
178
+ throw new ToolError(`The build of "${resolved.site}" gave no result: ${failureText(run)}`)
179
+ }
180
+ if (parsed.error) {
181
+ throw new ToolError(`The build of "${resolved.site}" failed: ${parsed.error}. Call validate to find the cause.${run.stderr.trim() ? `\nBuild log:\n${tail(run.stderr)}` : ''}`)
182
+ }
183
+ const results = parsed.results ?? []
184
+ const { errors, warnings } = countBySeverity(results)
185
+ const text = check
186
+ ? `Built "${resolved.site}"; the output check found ${errors} error(s) and ${warnings} warning(s).`
187
+ : `Built "${resolved.site}" into its output folder. Call preview to look at it.`
188
+ return ok({ site: resolved.site, ok: parsed.ok, results }, text)
189
+ }))
190
+
191
+ server.registerTool('validate', {
192
+ title: 'Validate a Nera site',
193
+ description: 'Checks a Nera site before building it, the way the build will read it: config/app.yaml and page frontmatter parse, every page has a `layout` that exists, every Pug include resolves, the theme is found. Returns one record per finding (`file`, `line`, `severity` error|warning, `rule`, `message` with the fix). Call it after editing pages, templates or configuration; fix every error, then build.',
194
+ inputSchema: { site: siteInput },
195
+ annotations: { readOnlyHint: true },
196
+ }, tool(async ({ site }) => {
197
+ const resolved = await resolveSite(ctx, site)
198
+ const results = validateSite({ cwd: resolved.dir })
199
+ const { errors, warnings } = countBySeverity(results)
200
+ const text = results.length
201
+ ? `"${resolved.site}" has ${errors} error(s) and ${warnings} warning(s); each message says how to fix it.`
202
+ : `"${resolved.site}" is valid. Call build or preview next.`
203
+ return ok({ site: resolved.site, ok: !hasErrors(results), results }, text)
204
+ }))
205
+
206
+ server.registerTool('add_plugin', {
207
+ title: 'Add a Nera plugin',
208
+ description: 'Installs an official Nera plugin into a site (npm install), copies its default configuration to `config/<name>.yaml` when the site has none, and copies its Pug templates to `views/vendor/plugin-<name>/` when it ships any. Call list_plugins for the catalog. Afterwards read the plugin\'s config with read_file and include its templates in a layout with write_file, then validate.',
209
+ inputSchema: {
210
+ site: siteInput,
211
+ plugin: z.string().describe('The plugin, as `@nera-static/plugin-<name>` or just `<name>` (e.g. `sitemap`, `tags`).'),
212
+ },
213
+ }, tool(async ({ site, plugin }, { signal }) => {
214
+ const { name, pkg } = pluginPackage(plugin)
215
+ const resolved = await resolveSite(ctx, site)
216
+ const install = await ctx.runner('npm', ['install', pkg], { cwd: resolved.dir, signal })
217
+ if (install.code !== 0) {
218
+ throw new ToolError(`Installing ${pkg} failed: ${failureText(install)}`)
219
+ }
220
+
221
+ const packageDir = path.join('node_modules', ...pkg.split('/'))
222
+ const { model } = await siteFolders(resolved.dir)
223
+ const config = await copyDefaultConfig(resolved.dir, packageDir, model.folders.config, name)
224
+
225
+ let templates = 'none'
226
+ const script = await publishTemplateScript(resolved.dir, packageDir)
227
+ if (script) {
228
+ const publish = await ctx.runner('node', [script], { cwd: resolved.dir, signal })
229
+ if (publish.code !== 0) {
230
+ throw new ToolError(`${pkg} is installed, but copying its templates failed: ${failureText(publish)}`)
231
+ }
232
+ templates = 'published'
233
+ }
234
+
235
+ const steps = [
236
+ config.status === 'copied' ? `its configuration is in ${config.file}` : null,
237
+ config.status === 'kept' ? `the site's own ${config.file} was kept` : null,
238
+ templates === 'published' ? 'its templates are in the site\'s views/vendor folder' : null,
239
+ ].filter(Boolean)
240
+ return ok(
241
+ { site: resolved.site, plugin: pkg, config, templates, log: tail(install.stdout) },
242
+ `Installed ${pkg} in "${resolved.site}"${steps.length ? `; ${steps.join(', ')}` : ''}. Then call validate.`,
243
+ )
244
+ }))
245
+ }
246
+
247
+ async function exists(target) {
248
+ try {
249
+ await fs.lstat(target)
250
+ return true
251
+ } catch {
252
+ return false
253
+ }
254
+ }
@@ -0,0 +1,294 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { isDeepStrictEqual } from 'node:util'
4
+ import yaml from 'yaml'
5
+ import { z } from 'zod'
6
+ import { isInside, resolveInRoot } from '../paths.js'
7
+ import { ok, tool, ToolError } from '../results.js'
8
+ import { relativeTo, resolveSite, siteFolders, siteInput } from './sites.js'
9
+
10
+ /** Larger files are refused by read_file: a model cannot use them whole. */
11
+ const MAX_READ_BYTES = 1024 * 1024
12
+ const FENCE = '---'
13
+ /** Path segments no file tool reads or writes: git internals may hold credentials. */
14
+ const FORBIDDEN_SEGMENTS = new Set(['.git'])
15
+ /** File names no file tool reads or writes: `.env` files and `.npmrc` (npm `_authToken`) hold tokens. */
16
+ const SECRET_FILE = /^(\.env(\..*)?|\.npmrc)$/
17
+ /** Path segments write_file refuses: installed packages belong to npm. */
18
+ const NO_WRITE_SEGMENTS = new Set(['node_modules'])
19
+
20
+ const pageInput = z
21
+ .string()
22
+ .describe('The page file, relative to the site folder, inside its pages folder and ending in .md — e.g. `pages/about.md` or `pages/blog/first-post.md`. The page is published at the same path with .html (`/about.html`).')
23
+ const fileInput = z
24
+ .string()
25
+ .describe('The file, relative to the site folder — e.g. `config/app.yaml`, `theme/views/layouts/default.pug`, `assets/css/main.css`.')
26
+
27
+ /**
28
+ * Splits a page into its frontmatter YAML and its Markdown body, the way the
29
+ * build reads it: a `---` first line opens the block, the next `---` line
30
+ * closes it (no closing line: the rest is frontmatter).
31
+ *
32
+ * @param {string} raw the file's text
33
+ * @returns {{ yamlText: string|null, body: string }} `yamlText` null when the page has no frontmatter
34
+ */
35
+ function splitPage(raw) {
36
+ // markdown-it, which the build parses pages with, reads CRLF as LF.
37
+ const lines = raw.replace(/\r\n/g, '\n').split('\n')
38
+ if (lines[0] !== FENCE) return { yamlText: null, body: raw }
39
+ const close = lines.indexOf(FENCE, 1)
40
+ if (close === -1) return { yamlText: lines.slice(1).join('\n'), body: '' }
41
+ return {
42
+ yamlText: lines.slice(1, close).join('\n'),
43
+ body: lines.slice(close + 1).join('\n'),
44
+ }
45
+ }
46
+
47
+ /** Parses frontmatter YAML into a document that keeps comments and quoting. */
48
+ function parseFrontmatter(yamlText) {
49
+ const doc = yaml.parseDocument(yamlText ?? '', { merge: true, uniqueKeys: false })
50
+ if (doc.errors.length) {
51
+ return { doc: null, error: doc.errors[0].message }
52
+ }
53
+ if (doc.contents !== null && !yaml.isMap(doc.contents)) {
54
+ return { doc: null, error: 'The frontmatter is not a list of `key: value` lines.' }
55
+ }
56
+ return { doc, error: null }
57
+ }
58
+
59
+ /**
60
+ * The frontmatter YAML for `frontmatter`, edited into the page's existing
61
+ * frontmatter when it has one that parses: unchanged keys keep their comments,
62
+ * quoting and order, a changed value keeps its quoting style, keys left out are
63
+ * removed, new keys are appended. Nothing changed: the block stays byte for byte.
64
+ */
65
+ function frontmatterText(existingYaml, frontmatter) {
66
+ const { doc } = existingYaml === null ? { doc: null } : parseFrontmatter(existingYaml)
67
+ if (!doc || doc.contents === null) {
68
+ return new yaml.Document(frontmatter).toString({ flowCollectionPadding: false })
69
+ }
70
+ const current = doc.toJS() ?? {}
71
+ let changed = false
72
+ for (const key of Object.keys(current)) {
73
+ if (!Object.hasOwn(frontmatter, key)) {
74
+ doc.delete(key)
75
+ changed = true
76
+ }
77
+ }
78
+ for (const [key, value] of Object.entries(frontmatter)) {
79
+ if (!isDeepStrictEqual(current[key], value)) {
80
+ doc.set(key, value)
81
+ changed = true
82
+ }
83
+ }
84
+ if (!changed) return withTrailingNewline(existingYaml)
85
+ return doc.toString({ flowCollectionPadding: false })
86
+ }
87
+
88
+ function withTrailingNewline(text) {
89
+ return text.endsWith('\n') ? text : `${text}\n`
90
+ }
91
+
92
+ async function statOrNull(file) {
93
+ try {
94
+ return await fs.stat(file)
95
+ } catch (error) {
96
+ if (error.code === 'ENOENT') return null
97
+ throw error
98
+ }
99
+ }
100
+
101
+ async function readText(file, shown) {
102
+ try {
103
+ return await fs.readFile(file, 'utf8')
104
+ } catch (error) {
105
+ if (error.code === 'ENOENT') return null
106
+ if (error.code === 'EISDIR') throw new ToolError(`"${shown}" is a folder, not a page.`)
107
+ throw error
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Refuses `input` when it, or the site-relative real path it resolved to (a
113
+ * symbolic link may point into `.git/`), has a segment from `segments`.
114
+ */
115
+ function refuseSegments(input, resolved, segments, why) {
116
+ const hit = [input, resolved]
117
+ .flatMap((candidate) => candidate.split(/[\\/]/))
118
+ .find((segment) => segments.has(segment))
119
+ if (hit) throw new ToolError(`"${input}" is inside ${hit}/, which ${why}.`)
120
+ }
121
+
122
+ function refuseSecrets(input, resolved) {
123
+ refuseSegments(input, resolved, FORBIDDEN_SEGMENTS, 'these tools never read or change')
124
+ if ([input, resolved].some((candidate) => SECRET_FILE.test(path.basename(candidate)))) {
125
+ throw new ToolError(`"${input}" can hold secrets (tokens, passwords); these tools never read or change it.`)
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Resolves a page argument: inside the site, inside its pages folder, a `.md`
131
+ * file.
132
+ */
133
+ async function resolvePage(ctx, site, page) {
134
+ const resolved = await resolveSite(ctx, site)
135
+ const { pagesDir } = await siteFolders(resolved.dir)
136
+ const file = await resolveInRoot(resolved.dir, page, { label: 'page path' })
137
+ const pagesFolder = relativeTo(resolved.dir, pagesDir)
138
+ if (file === pagesDir || !isInside(pagesDir, file)) {
139
+ throw new ToolError(`"${page}" is not inside the site's pages folder (${pagesFolder}/). Give a path like ${pagesFolder}/about.md; for other files use read_file / write_file.`)
140
+ }
141
+ if (path.extname(file) !== '.md') {
142
+ throw new ToolError(`"${page}" does not end in .md. Pages are Markdown files, e.g. ${pagesFolder}/about.md.`)
143
+ }
144
+ return { ...resolved, file, path: relativeTo(resolved.dir, file) }
145
+ }
146
+
147
+ /**
148
+ * Resolves a file argument inside the site, refusing git internals and `.env`
149
+ * files — by the name given and by the real path a symbolic link leads to.
150
+ */
151
+ async function resolveFile(ctx, site, input) {
152
+ const resolved = await resolveSite(ctx, site)
153
+ const file = await resolveInRoot(resolved.dir, input, { label: 'file path' })
154
+ if (file === resolved.dir) {
155
+ throw new ToolError('Give a file inside the site, not the site folder itself.')
156
+ }
157
+ const relative = relativeTo(resolved.dir, file)
158
+ refuseSecrets(input, relative)
159
+ return { ...resolved, file, path: relative }
160
+ }
161
+
162
+ /**
163
+ * Registers the page tools (`read_page`, `write_page`, `delete_page`) and the
164
+ * file tools (`read_file`, `write_file`).
165
+ *
166
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
167
+ * @param {{ root: string }} ctx
168
+ */
169
+ export function registerFileTools(server, ctx) {
170
+ server.registerTool('read_page', {
171
+ title: 'Read a page',
172
+ description: 'Reads one page of a Nera site: its frontmatter (the YAML block at the top: `layout`, `title`, `description`, …) as JSON and its Markdown body. Call get_site first for the list of pages. To change the page, pass the frontmatter and body back to write_page.',
173
+ inputSchema: { site: siteInput, path: pageInput },
174
+ annotations: { readOnlyHint: true },
175
+ }, tool(async ({ site, path: page }) => {
176
+ const target = await resolvePage(ctx, site, page)
177
+ const raw = await readText(target.file, target.path)
178
+ if (raw === null) {
179
+ throw new ToolError(`The page "${target.path}" does not exist. Call get_site for the list of pages, or write_page to create it.`)
180
+ }
181
+ const { yamlText, body } = splitPage(raw)
182
+ const { doc, error } = parseFrontmatter(yamlText)
183
+ const frontmatter = doc ? (doc.toJS() ?? {}) : null
184
+ const structured = { site: target.site, path: target.path, frontmatter, body: body.replace(/^\n+/, '') }
185
+ if (error) structured.frontmatterError = error
186
+ const text = error
187
+ ? `Read ${target.path}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, passing the whole frontmatter.`
188
+ : `Read ${target.path} (layout: ${frontmatter.layout ?? 'none — the build skips this page'}).`
189
+ return ok(structured, text)
190
+ }))
191
+
192
+ server.registerTool('write_page', {
193
+ title: 'Create or update a page',
194
+ description: 'Creates a page of a Nera site, or replaces an existing one. `frontmatter` becomes the YAML block at the top of the file and must contain `layout` (the Pug layout under the theme\'s views folder that renders the page, e.g. `pages/default.pug` — read an existing page to see which layouts the site uses); `title` and `description` are usual too. Keys you leave out are removed; comments and quoting of unchanged keys are kept. `body` is the Markdown content; leave it out to keep the existing body. Afterwards call validate, then build or preview.',
195
+ inputSchema: {
196
+ site: siteInput,
197
+ path: pageInput,
198
+ frontmatter: z.record(z.string(), z.unknown()).describe('The page\'s frontmatter as a JSON object; must contain `layout`.'),
199
+ body: z.string().optional().describe('The page\'s Markdown content, without the frontmatter. Leave out to keep the existing body.'),
200
+ },
201
+ }, tool(async ({ site, path: page, frontmatter, body }) => {
202
+ if (typeof frontmatter.layout !== 'string' || frontmatter.layout.trim() === '') {
203
+ throw new ToolError('The frontmatter has no `layout`. Nera only renders pages that name their layout — add e.g. `layout: pages/default.pug` (read an existing page with read_page to see which layout the site uses).')
204
+ }
205
+ const target = await resolvePage(ctx, site, page)
206
+ const raw = await readText(target.file, target.path)
207
+ const existing = raw === null ? null : splitPage(raw)
208
+ const head = `${FENCE}\n${frontmatterText(existing?.yamlText ?? null, frontmatter)}${FENCE}\n`
209
+ const content = body === undefined
210
+ ? head + (existing?.body ?? '')
211
+ : `${head}\n${withTrailingNewline(body.replace(/^\n+/, ''))}`
212
+ await fs.mkdir(path.dirname(target.file), { recursive: true })
213
+ await fs.writeFile(target.file, content)
214
+ const created = raw === null
215
+ return ok(
216
+ { site: target.site, path: target.path, created },
217
+ `${created ? 'Created' : 'Updated'} ${target.path}. Call validate to check it, then build or preview.`,
218
+ )
219
+ }))
220
+
221
+ server.registerTool('delete_page', {
222
+ title: 'Delete a page',
223
+ description: 'Deletes one page (a Markdown file in the pages folder) of a Nera site. Links to it from other pages or the navigation are not changed — check them with validate afterwards.',
224
+ inputSchema: { site: siteInput, path: pageInput },
225
+ annotations: { destructiveHint: true },
226
+ }, tool(async ({ site, path: page }) => {
227
+ const target = await resolvePage(ctx, site, page)
228
+ try {
229
+ await fs.unlink(target.file)
230
+ } catch (error) {
231
+ if (error.code === 'ENOENT') {
232
+ throw new ToolError(`The page "${target.path}" does not exist. Call get_site for the list of pages.`)
233
+ }
234
+ throw error
235
+ }
236
+ return ok({ site: target.site, path: target.path, deleted: true }, `Deleted ${target.path}.`)
237
+ }))
238
+
239
+ server.registerTool('read_file', {
240
+ title: 'Read a site file',
241
+ description: 'Reads a text file of a Nera site: configuration (`config/app.yaml`, `config/<plugin>.yaml`), Pug templates (`theme/views/…`), styles and scripts (`assets/…`), or any other text file in the site. For pages use read_page instead.',
242
+ inputSchema: { site: siteInput, path: fileInput },
243
+ annotations: { readOnlyHint: true },
244
+ }, tool(async ({ site, path: input }) => {
245
+ const target = await resolveFile(ctx, site, input)
246
+ const stat = await statOrNull(target.file)
247
+ if (stat === null) {
248
+ throw new ToolError(`The file "${target.path}" does not exist in site "${target.site}". Call get_site to see the site's folders.`)
249
+ }
250
+ if (stat.isDirectory()) {
251
+ throw new ToolError(`"${target.path}" is a folder, not a file.`)
252
+ }
253
+ if (stat.size > MAX_READ_BYTES) {
254
+ throw new ToolError(`"${target.path}" is ${stat.size} bytes, more than the ${MAX_READ_BYTES} bytes read_file returns.`)
255
+ }
256
+ const buffer = await fs.readFile(target.file)
257
+ if (buffer.includes(0)) {
258
+ throw new ToolError(`"${target.path}" is a binary file (an image, a font, …); read_file only returns text.`)
259
+ }
260
+ const content = buffer.toString('utf8')
261
+ return ok({ site: target.site, path: target.path, content }, content)
262
+ }))
263
+
264
+ server.registerTool('write_file', {
265
+ title: 'Create or update a site file',
266
+ description: 'Creates or replaces a text file of a Nera site: configuration (`config/app.yaml`, `config/<plugin>.yaml`), Pug templates (`theme/views/…`), styles and scripts (`assets/…`). Missing folders are created. Pages (Markdown in the pages folder) go through write_page instead; the output folder (`public/`) is rebuilt on every build, so nothing is written there. Afterwards call validate.',
267
+ inputSchema: {
268
+ site: siteInput,
269
+ path: fileInput,
270
+ content: z.string().describe('The complete new text of the file.'),
271
+ },
272
+ }, tool(async ({ site, path: input, content }) => {
273
+ const target = await resolveFile(ctx, site, input)
274
+ refuseSegments(input, target.path, NO_WRITE_SEGMENTS, 'npm manages; add plugins with add_plugin')
275
+ const { pagesDir, distDir } = await siteFolders(target.dir)
276
+ if (isInside(distDir, target.file)) {
277
+ throw new ToolError(`"${target.path}" is in the output folder (${relativeTo(target.dir, distDir)}/), which every build deletes and recreates. Change the page, template or asset it is built from instead.`)
278
+ }
279
+ if (isInside(pagesDir, target.file) && path.extname(target.file) === '.md') {
280
+ throw new ToolError(`"${target.path}" is a page. Use write_page, which checks the frontmatter.`)
281
+ }
282
+ const stat = await statOrNull(target.file)
283
+ if (stat?.isDirectory()) {
284
+ throw new ToolError(`"${target.path}" is a folder, not a file.`)
285
+ }
286
+ const created = stat === null
287
+ await fs.mkdir(path.dirname(target.file), { recursive: true })
288
+ await fs.writeFile(target.file, content)
289
+ return ok(
290
+ { site: target.site, path: target.path, created },
291
+ `${created ? 'Created' : 'Updated'} ${target.path} in site "${target.site}". Call validate to check the site.`,
292
+ )
293
+ }))
294
+ }