@nera-static/mcp 1.2.1 → 1.4.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.
@@ -0,0 +1,336 @@
1
+ // The read tools of the hosted mode (L7b, plan D2–D4): `list_sites`,
2
+ // `get_site`, `read_page` and `read_file` over the signed-in user's GitHub
3
+ // repositories. A site is a repository as `owner/name` that the GitHub App can
4
+ // reach with the user's token and whose package.json depends on
5
+ // `@nera-static/nera`; any other name is refused before a file is read. Reads
6
+ // come from the draft branch `nera-draft` while it exists (that is where the
7
+ // write tools commit), else from `main`. The page rules are the local mode's
8
+ // (src/pages.js), the folders are core's (`computeFolders`). The site lookup
9
+ // (`createSiteAccess`) and the error wrapper (`hostedTool`) are shared with
10
+ // the write, validate and publish tools (./write.js, ./validate.js,
11
+ // ./publish.js).
12
+ import fs from 'node:fs'
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+ import { computeFolders, defaultSettings } from '@nera-static/core'
16
+ import yaml from 'yaml'
17
+ import { z } from 'zod'
18
+ import { parsePage, refuseSecrets } from '../../pages.js'
19
+ import { fail, ok, tool, ToolError } from '../../results.js'
20
+ import { isNeraSite, neraRange, sitePlugins } from '../../tools/sites.js'
21
+ import { GitHubError } from '../github.js'
22
+ import { SignInRequiredError } from '../provider.js'
23
+ import { BASE_BRANCH, DRAFT_BRANCH, repoName, repoPath } from '../repo.js'
24
+
25
+ /** Larger files are refused by read_file: a model cannot use them whole. */
26
+ export const MAX_READ_BYTES = 1024 * 1024
27
+ /** What a user does when GitHub no longer accepts their sign-in. */
28
+ const RECONNECT = 'Sign in again: remove the Nera connector in your AI assistant and connect it once more.'
29
+ /** git's mode of a symbolic link: never listed, never read through. */
30
+ export const SYMLINK_MODE = '120000'
31
+
32
+ export const hostedSiteInput = z
33
+ .string()
34
+ .describe('The site: its GitHub repository as owner/name (e.g. `octo/my-site`), as list_sites returns it.')
35
+ export const pageInput = z
36
+ .string()
37
+ .describe('The page file, relative to the repository root, inside the site\'s 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`).')
38
+ export const fileInput = z
39
+ .string()
40
+ .describe('The file, relative to the repository root — e.g. `config/app.yaml`, `theme/views/layouts/default.pug`, `assets/css/main.css`.')
41
+
42
+ /**
43
+ * A folder from `config/app.yaml` (`./pages`, `public/`) as a repository path
44
+ * (`pages`, `public`), refused when it leaves the repository.
45
+ *
46
+ * @param {string} folder
47
+ * @param {string} key the `folders.<key>` it came from
48
+ * @returns {string}
49
+ * @throws {ToolError}
50
+ */
51
+ export function repoFolder(folder, key) {
52
+ const normalized = path.posix.normalize(String(folder)).replace(/\/+$/, '')
53
+ return repoPath(normalized, `${key} folder (folders.${key} in config/app.yaml)`)
54
+ }
55
+
56
+ /**
57
+ * The folders the build uses, as core's `computeFolders` computes them. It
58
+ * probes the site folder for `theme/` and `views/`; the hosted server has no
59
+ * checkout, so the probe runs against an empty temporary folder that holds
60
+ * just those two names when the repository's tree has them.
61
+ *
62
+ * @param {object} appConfig the parsed `config/app.yaml`
63
+ * @param {Array<{path: string, mode: string}>} entries the repository's tree
64
+ * @returns {Record<string, string>}
65
+ */
66
+ export function treeFolders(appConfig, entries) {
67
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nera-mcp-folders-'))
68
+ try {
69
+ for (const name of ['theme', 'views']) {
70
+ if (entries.some((entry) => entry.path === name && entry.mode !== SYMLINK_MODE)) {
71
+ fs.mkdirSync(path.join(dir, name))
72
+ }
73
+ }
74
+ return computeFolders(appConfig, { cwd: dir })
75
+ } finally {
76
+ fs.rmSync(dir, { recursive: true, force: true })
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Parses `config/app.yaml` the way core's `resolveSiteModel` does.
82
+ *
83
+ * @param {{content: Buffer|null, size: number}|null} file null when the file is missing
84
+ * @returns {{ appConfig: object, appConfigError: string|null }}
85
+ */
86
+ function parseAppConfig(file) {
87
+ if (file === null) return { appConfig: {}, appConfigError: null }
88
+ if (file.content === null) {
89
+ return { appConfig: {}, appConfigError: `config/app.yaml is ${file.size} bytes, more than the ${MAX_READ_BYTES} bytes these tools read.` }
90
+ }
91
+ try {
92
+ const parsed = yaml.parse(file.content.toString('utf8')) || {}
93
+ if (typeof parsed !== 'object' || Array.isArray(parsed)) {
94
+ return { appConfig: {}, appConfigError: 'config/app.yaml is not a list of `key: value` lines.' }
95
+ }
96
+ return { appConfig: parsed, appConfigError: null }
97
+ } catch (error) {
98
+ return { appConfig: {}, appConfigError: error.message }
99
+ }
100
+ }
101
+
102
+ /** Parses a package.json from the repository; null when it is missing or no JSON. */
103
+ function parsePackage(file) {
104
+ if (file?.type !== 'file') return null
105
+ try {
106
+ return JSON.parse(file.content.toString('utf8'))
107
+ } catch {
108
+ return null
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Wraps a hosted tool handler: besides a user mistake (`tool`), a sign-in that
114
+ * is gone and a refusal by GitHub become `isError` results too, with their own
115
+ * messages, which never hold a token.
116
+ */
117
+ export function hostedTool(handler) {
118
+ const wrapped = tool(handler)
119
+ return async (args, extra) => {
120
+ try {
121
+ return await wrapped(args, extra)
122
+ } catch (error) {
123
+ if (error instanceof SignInRequiredError) return fail(error.message)
124
+ if (error instanceof GitHubError) {
125
+ // 401: GitHub no longer accepts the token (revoked, App uninstalled).
126
+ return fail(error.status === 401 ? `${error.message} ${RECONNECT}` : error.message)
127
+ }
128
+ throw error
129
+ }
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Checks that `file` is a page: inside the site's pages folder, ending in `.md`.
135
+ *
136
+ * @param {string} file a repository path, already checked with `repoPath`
137
+ * @param {Record<string, string>} folders the site's folders (`treeFolders`)
138
+ * @throws {ToolError}
139
+ */
140
+ export function requirePagePath(file, folders) {
141
+ const pagesFolder = repoFolder(folders.pages, 'pages')
142
+ if (!file.startsWith(`${pagesFolder}/`)) {
143
+ throw new ToolError(`"${file}" is not inside the site's pages folder (${pagesFolder}/). Give a path like ${pagesFolder}/about.md; for other files use read_file / write_file.`)
144
+ }
145
+ if (path.posix.extname(file) !== '.md') {
146
+ throw new ToolError(`"${file}" does not end in .md. Pages are Markdown files, e.g. ${pagesFolder}/about.md.`)
147
+ }
148
+ }
149
+
150
+ /**
151
+ * The site lookup every hosted tool goes through (plan D3), bound to the
152
+ * signed-in user's repository client.
153
+ *
154
+ * @param {() => Promise<ReturnType<import('../repo.js').createRepoClient>>} repos
155
+ */
156
+ export function createSiteAccess(repos) {
157
+ /**
158
+ * Resolves a `site` argument: a repository the user's installations reach,
159
+ * whose package.json (on the branch reads come from) depends on
160
+ * `@nera-static/nera`.
161
+ *
162
+ * @returns {Promise<{ client: object, site: string, branch: string, ref: string, draft: {exists: boolean, sha: string|null}, mainSha: string|null, pkg: object }>}
163
+ */
164
+ async function openSite(input) {
165
+ const wanted = repoName(input).toLowerCase()
166
+ const client = await repos()
167
+ const repo = (await client.listRepos()).find((candidate) => candidate.site.toLowerCase() === wanted)
168
+ if (!repo) {
169
+ throw new ToolError(`The repository "${input}" is not one the Nera Static GitHub App can reach for you. Call list_sites for the sites you can edit; to add a repository, grant the Nera Static GitHub App access to it in your GitHub settings (Applications → Nera Static → Configure).`)
170
+ }
171
+ const site = repo.site
172
+ const draftSha = await client.branchHead(site, DRAFT_BRANCH)
173
+ const mainSha = await client.branchHead(site, BASE_BRANCH)
174
+ const ref = draftSha ?? mainSha
175
+ if (!ref) {
176
+ throw new ToolError(`The repository "${site}" has no ${BASE_BRANCH} branch, so it holds no Nera site yet.`)
177
+ }
178
+ const branch = draftSha ? DRAFT_BRANCH : BASE_BRANCH
179
+ const pkg = parsePackage(await client.readFile(site, 'package.json', ref))
180
+ if (!isNeraSite(pkg)) {
181
+ throw new ToolError(`"${site}" is not a Nera site: its package.json on ${branch} does not depend on @nera-static/nera. Call list_sites for the sites you can edit.`)
182
+ }
183
+ return { client, site, branch, ref, draft: { exists: Boolean(draftSha), sha: draftSha }, mainSha, pkg }
184
+ }
185
+
186
+ /**
187
+ * Reads `file` at `ref` (default: the site's read ref), refusing a
188
+ * symbolic link and a folder.
189
+ */
190
+ async function readAt(target, file, what, ref = target.ref) {
191
+ const found = await target.client.readFile(target.site, file, ref, { maxBytes: MAX_READ_BYTES })
192
+ if (found?.type === 'symlink') {
193
+ throw new ToolError(`"${file}" is a symbolic link in ${target.site}; these tools do not follow links. Use the file it points to instead.`)
194
+ }
195
+ if (found?.type === 'dir') throw new ToolError(`"${file}" is a folder, not ${what}.`)
196
+ return found
197
+ }
198
+
199
+ /** The parsed `config/app.yaml` at `ref` (default: the site's read ref). */
200
+ async function appConfigAt(target, ref = target.ref) {
201
+ return parseAppConfig(
202
+ await readAt(target, `${repoFolder(defaultSettings.folders.config, 'config')}/app.yaml`, 'a file', ref),
203
+ )
204
+ }
205
+
206
+ /** The site's folders and its tree at the read ref. */
207
+ async function siteModel(target) {
208
+ const { appConfig, appConfigError } = await appConfigAt(target)
209
+ const tree = await target.client.readTree(target.site, target.ref)
210
+ const folders = treeFolders(appConfig, tree.entries)
211
+ return { appConfig, appConfigError, folders, tree }
212
+ }
213
+
214
+ return { openSite, readAt, appConfigAt, siteModel }
215
+ }
216
+
217
+ /**
218
+ * Registers the hosted read tools.
219
+ *
220
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
221
+ * @param {object} ctx
222
+ * @param {() => Promise<ReturnType<import('../repo.js').createRepoClient>>} ctx.repos the signed-in user's repository client
223
+ */
224
+ export function registerHostedReadTools(server, { repos }) {
225
+ const { openSite, readAt, siteModel } = createSiteAccess(repos)
226
+
227
+ server.registerTool('list_sites', {
228
+ title: 'List Nera sites',
229
+ description: 'Lists the Nera static sites you can edit: your GitHub repositories that the Nera Static GitHub App can reach and whose package.json depends on @nera-static/nera. A site\'s pages are Markdown files in pages/, rendered through Pug layouts into plain HTML. Call this first to find the `site` value (owner/name) every other tool takes. A repository missing here needs the GitHub App granted access to it.',
230
+ inputSchema: {},
231
+ annotations: { readOnlyHint: true },
232
+ }, hostedTool(async () => {
233
+ const client = await repos()
234
+ const reachable = await client.listRepos()
235
+ const checked = await Promise.all(reachable.map(async (repo) => {
236
+ const pkg = parsePackage(await client.readFile(repo.site, 'package.json', BASE_BRANCH))
237
+ return isNeraSite(pkg) ? { site: repo.site, name: pkg.name ?? null, nera: neraRange(pkg), private: repo.private } : null
238
+ }))
239
+ const sites = checked.filter(Boolean)
240
+ const text = sites.length
241
+ ? `Found ${sites.length} Nera site(s): ${sites.map((s) => s.site).join(', ')}. Call get_site for one of them.`
242
+ : `None of the ${reachable.length} repositories the Nera Static GitHub App can reach is a Nera site. Grant the App access to your site's repository in your GitHub settings.`
243
+ return ok({ sites }, text)
244
+ }))
245
+
246
+ server.registerTool('get_site', {
247
+ title: 'Describe a Nera site',
248
+ description: 'Describes one Nera site in a GitHub repository: its configuration from config/app.yaml, the folders the build uses, its theme, its plugins, the list of its pages (Markdown files) and its draft. Changes are committed to the draft branch nera-draft and go live only with publish; `draft.ahead` says how many unpublished commits it holds. Call it before editing a site so you know which pages exist; then use read_page / write_page for pages and read_file / write_file for configuration, layouts and styles.',
249
+ inputSchema: { site: hostedSiteInput },
250
+ annotations: { readOnlyHint: true },
251
+ }, hostedTool(async ({ site }) => {
252
+ const target = await openSite(site)
253
+ const { appConfig, appConfigError, folders, tree } = await siteModel(target)
254
+ const pagesFolder = repoFolder(folders.pages, 'pages')
255
+ const pages = tree.entries
256
+ .filter((entry) => entry.type === 'blob' && entry.mode !== SYMLINK_MODE)
257
+ .map((entry) => entry.path)
258
+ .filter((file) => file.startsWith(`${pagesFolder}/`) && file.endsWith('.md'))
259
+ .sort()
260
+ const ahead = target.draft.exists && target.mainSha
261
+ ? await target.client.aheadBy(target.site, target.mainSha, target.draft.sha)
262
+ : 0
263
+ const plugins = sitePlugins(target.pkg)
264
+ const structured = {
265
+ site: target.site,
266
+ branch: target.branch,
267
+ name: target.pkg.name ?? null,
268
+ nera: neraRange(target.pkg),
269
+ app: appConfig,
270
+ appConfigError,
271
+ folders,
272
+ theme: appConfig.theme ? { name: String(appConfig.theme) } : null,
273
+ plugins,
274
+ pages,
275
+ draft: { exists: target.draft.exists, ahead },
276
+ }
277
+ if (tree.truncated) structured.pagesTruncated = true
278
+ const draftText = target.draft.exists
279
+ ? ` Its draft (${DRAFT_BRANCH}) holds ${ahead} unpublished commit(s); publish puts them live.`
280
+ : ' It has no unpublished changes.'
281
+ const text = `Site "${target.site}" has ${pages.length} page(s) and ${plugins.length} plugin(s).${draftText}`
282
+ + (tree.truncated ? ' The repository is too large for GitHub to list in full, so the page list may be incomplete.' : '')
283
+ + (appConfigError ? ` Problem: config/app.yaml is invalid YAML: ${appConfigError}` : '')
284
+ return ok(structured, text)
285
+ }))
286
+
287
+ server.registerTool('read_page', {
288
+ title: 'Read a page',
289
+ description: 'Reads one page of a Nera site in a GitHub repository (from the draft branch nera-draft when it exists, else from main): 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.',
290
+ inputSchema: { site: hostedSiteInput, path: pageInput },
291
+ annotations: { readOnlyHint: true },
292
+ }, hostedTool(async ({ site, path: page }) => {
293
+ const file = repoPath(page, 'page path')
294
+ refuseSecrets(file, file)
295
+ const target = await openSite(site)
296
+ const { folders } = await siteModel(target)
297
+ requirePagePath(file, folders)
298
+ const found = await readAt(target, file, 'a page')
299
+ if (!found) {
300
+ throw new ToolError(`The page "${file}" does not exist on ${target.branch} of ${target.site}. Call get_site for the list of pages, or write_page to create it.`)
301
+ }
302
+ if (found.content === null) {
303
+ throw new ToolError(`The page "${file}" is ${found.size} bytes, more than the ${MAX_READ_BYTES} bytes read_page returns.`)
304
+ }
305
+ const { frontmatter, body, error } = parsePage(found.content.toString('utf8'))
306
+ const structured = { site: target.site, branch: target.branch, path: file, frontmatter, body }
307
+ if (error) structured.frontmatterError = error
308
+ const text = error
309
+ ? `Read ${file}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, passing the whole frontmatter.`
310
+ : `Read ${file} (layout: ${frontmatter.layout ?? 'none — the build skips this page'}).`
311
+ return ok(structured, text)
312
+ }))
313
+
314
+ server.registerTool('read_file', {
315
+ title: 'Read a site file',
316
+ description: 'Reads a text file of a Nera site in a GitHub repository (from the draft branch nera-draft when it exists, else from main): 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.',
317
+ inputSchema: { site: hostedSiteInput, path: fileInput },
318
+ annotations: { readOnlyHint: true },
319
+ }, hostedTool(async ({ site, path: input }) => {
320
+ const file = repoPath(input, 'file path')
321
+ refuseSecrets(file, file)
322
+ const target = await openSite(site)
323
+ const found = await readAt(target, file, 'a file')
324
+ if (!found) {
325
+ throw new ToolError(`The file "${file}" does not exist on ${target.branch} of ${target.site}. Call get_site to see the site's folders.`)
326
+ }
327
+ if (found.content === null) {
328
+ throw new ToolError(`"${file}" is ${found.size} bytes, more than the ${MAX_READ_BYTES} bytes read_file returns.`)
329
+ }
330
+ if (found.content.includes(0)) {
331
+ throw new ToolError(`"${file}" is a binary file (an image, a font, …); read_file only returns text.`)
332
+ }
333
+ const content = found.content.toString('utf8')
334
+ return ok({ site: target.site, branch: target.branch, path: file, content }, content)
335
+ }))
336
+ }
@@ -0,0 +1,44 @@
1
+ // The hosted `validate` (L7b, plan D1/D6): the validator of `nera validate`
2
+ // over a temporary checkout of the site's draft (or of `main` when there is
3
+ // none), made by src/hosted/checkout.js and deleted afterwards. The records
4
+ // come back exactly as `validate({ cwd })` of `@nera-static/nera` returns
5
+ // them, like the local tool's. There is no hosted `build`: it would run the
6
+ // site's local plugins, which is user code, on the server.
7
+ import { hasErrors, validate as neraValidate } from '@nera-static/nera'
8
+ import { ok } from '../../results.js'
9
+ import { countBySeverity } from '../../tools/cli.js'
10
+ import { DRAFT_BRANCH } from '../repo.js'
11
+ import { createSiteAccess, hostedSiteInput, hostedTool } from './read.js'
12
+
13
+ /**
14
+ * Registers the hosted `validate`.
15
+ *
16
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
17
+ * @param {object} ctx
18
+ * @param {() => Promise<ReturnType<import('../repo.js').createRepoClient>>} ctx.repos the signed-in user's repository client
19
+ * @param {string} ctx.userId the signed-in user, whose checkouts run one at a time
20
+ * @param {ReturnType<typeof import('../checkout.js').createCheckouts>} ctx.checkouts
21
+ * @param {typeof neraValidate} [ctx.validate] the validator (`@nera-static/nera`'s)
22
+ */
23
+ export function registerHostedValidateTool(server, { repos, userId, checkouts, validate = neraValidate }) {
24
+ const { openSite } = createSiteAccess(repos)
25
+
26
+ server.registerTool('validate', {
27
+ title: 'Validate a Nera site',
28
+ description: `Checks a Nera site in a GitHub repository the way the build will read it, on the draft branch ${DRAFT_BRANCH} when it exists (your unpublished changes), else on main: 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 write_page, write_file or delete_page; fix every error, then call publish. It takes a few seconds: the repository is downloaded for the check, plus the theme package when config/app.yaml names one (nothing is installed or run).`,
29
+ inputSchema: { site: hostedSiteInput },
30
+ annotations: { readOnlyHint: true },
31
+ }, hostedTool(async ({ site }, { signal }) => {
32
+ const target = await openSite(site)
33
+ const results = await checkouts.withCheckout(
34
+ userId,
35
+ { client: target.client, site: target.site, ref: target.ref, signal },
36
+ (dir) => validate({ cwd: dir }),
37
+ )
38
+ const counts = countBySeverity(results)
39
+ const text = results.length
40
+ ? `"${target.site}" (${target.branch}) has ${counts.errors} error(s) and ${counts.warnings} warning(s); each message says how to fix it.`
41
+ : `"${target.site}" (${target.branch}) is valid.${target.draft.exists ? ' Call publish to put the draft live.' : ''}`
42
+ return ok({ site: target.site, branch: target.branch, ok: !hasErrors(results), counts, results }, text)
43
+ }))
44
+ }
@@ -0,0 +1,182 @@
1
+ // The write tools of the hosted mode (L7b, plan D2–D5): `write_page`,
2
+ // `write_file` and `delete_page` on the signed-in user's GitHub repositories.
3
+ // Each call makes exactly one commit, with the message the model passes, on
4
+ // the draft branch `nera-draft`; the first write creates it from `main`. The
5
+ // deploy workflow only runs on pushes to `main`, so nothing goes live until
6
+ // `publish` merges the draft. The page and path rules are the local mode's
7
+ // (src/pages.js); the site lookup is the read tools' (`createSiteAccess`).
8
+ import path from 'node:path'
9
+ import { z } from 'zod'
10
+ import { NO_WRITE_SEGMENTS, composePage, refuseSecrets, refuseSegments, requireLayout } from '../../pages.js'
11
+ import { ok, ToolError } from '../../results.js'
12
+ import { DRAFT_BRANCH, commitMessage, repoPath } from '../repo.js'
13
+ import {
14
+ MAX_READ_BYTES,
15
+ SYMLINK_MODE,
16
+ createSiteAccess,
17
+ fileInput,
18
+ hostedSiteInput,
19
+ hostedTool,
20
+ pageInput,
21
+ repoFolder,
22
+ requirePagePath,
23
+ } from './read.js'
24
+
25
+ const messageInput = z
26
+ .string()
27
+ .describe('The commit message: one line saying what the change does, e.g. "Add the about page" or "Fix a typo on the home page". Each call makes one commit with it.')
28
+
29
+ /** What every successful write tells the model to do next. */
30
+ const NEXT = `Nothing is live yet: the change waits on the draft branch ${DRAFT_BRANCH}. Call validate to check the site, then publish to put the draft live.`
31
+
32
+ /**
33
+ * Refuses a path the repository's tree cannot take as a file: one below a
34
+ * symbolic link or below a file. The path itself being a link is caught when
35
+ * it is read.
36
+ *
37
+ * @param {Array<{path: string, type: string, mode: string}>} entries the tree at the read ref
38
+ * @param {string} file a repository path
39
+ * @throws {ToolError}
40
+ */
41
+ export function refuseBlockedPath(entries, file) {
42
+ const segments = file.split('/')
43
+ for (let i = 1; i < segments.length; i += 1) {
44
+ const ancestor = segments.slice(0, i).join('/')
45
+ const entry = entries.find((candidate) => candidate.path === ancestor)
46
+ if (entry?.mode === SYMLINK_MODE) {
47
+ throw new ToolError(`"${file}" is below ${ancestor}, which is a symbolic link; these tools do not follow links.`)
48
+ }
49
+ if (entry?.type === 'blob') {
50
+ throw new ToolError(`"${file}" is below ${ancestor}, which is a file, not a folder.`)
51
+ }
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Registers the hosted write tools.
57
+ *
58
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
59
+ * @param {object} ctx
60
+ * @param {() => Promise<ReturnType<import('../repo.js').createRepoClient>>} ctx.repos the signed-in user's repository client
61
+ */
62
+ export function registerHostedWriteTools(server, { repos }) {
63
+ const { openSite, readAt, siteModel } = createSiteAccess(repos)
64
+
65
+ /**
66
+ * Commits one change of `file` to the draft. `decide` gets the file as it
67
+ * is on the branch the change goes onto (the draft, or `main` before the
68
+ * first write) and returns the new content (null: delete), or throws a
69
+ * `ToolError`. The draft is only created once `decide` accepted the
70
+ * change; when it then starts from a newer `main` than the one read,
71
+ * `decide` runs again on that.
72
+ *
73
+ * @param {Awaited<ReturnType<typeof openSite>>} target
74
+ * @param {string} file
75
+ * @param {string} what how a refusal names the file ("a page")
76
+ * @param {(current: {content: Buffer|null, size: number}|null) => string|null} decide
77
+ * @param {string} message
78
+ * @returns {Promise<{ current: object|null, commit: string }>}
79
+ */
80
+ async function commitToDraft(target, file, what, decide, message) {
81
+ let current = await readAt(target, file, what)
82
+ let content = decide(current)
83
+ if (!target.draft.exists) {
84
+ const { sha } = await target.client.ensureDraft(target.site)
85
+ if (sha !== target.ref) {
86
+ current = await readAt(target, file, what, sha)
87
+ content = decide(current)
88
+ }
89
+ }
90
+ const { sha: commit } = await target.client.commitFile(target.site, { path: file, content, message })
91
+ return { current, commit }
92
+ }
93
+
94
+ server.registerTool('write_page', {
95
+ title: 'Create or update a page',
96
+ description: `Creates a page of a Nera site in a GitHub repository, or replaces an existing one, as one commit on the draft branch ${DRAFT_BRANCH} (created from main on the first change; nothing goes live until publish). \`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 publish.`,
97
+ inputSchema: {
98
+ site: hostedSiteInput,
99
+ path: pageInput,
100
+ frontmatter: z.record(z.string(), z.unknown()).describe('The page\'s frontmatter as a JSON object; must contain `layout`.'),
101
+ body: z.string().optional().describe('The page\'s Markdown content, without the frontmatter. Leave out to keep the existing body.'),
102
+ message: messageInput,
103
+ },
104
+ }, hostedTool(async ({ site, path: page, frontmatter, body, message }) => {
105
+ commitMessage(message)
106
+ requireLayout(frontmatter)
107
+ const file = repoPath(page, 'page path')
108
+ refuseSecrets(file, file)
109
+ const target = await openSite(site)
110
+ const { folders, tree } = await siteModel(target)
111
+ requirePagePath(file, folders)
112
+ refuseBlockedPath(tree.entries, file)
113
+ const { current, commit } = await commitToDraft(target, file, 'a page', (existing) => {
114
+ if (existing?.content === null) {
115
+ throw new ToolError(`The page "${file}" is ${existing.size} bytes, more than the ${MAX_READ_BYTES} bytes write_page edits.`)
116
+ }
117
+ return composePage(existing ? existing.content.toString('utf8') : null, frontmatter, body)
118
+ }, message)
119
+ const created = current === null
120
+ return ok(
121
+ { site: target.site, path: file, created, commit, branch: DRAFT_BRANCH },
122
+ `${created ? 'Created' : 'Updated'} ${file} in ${target.site}. ${NEXT}`,
123
+ )
124
+ }))
125
+
126
+ server.registerTool('write_file', {
127
+ title: 'Create or update a site file',
128
+ description: `Creates or replaces a text file of a Nera site in a GitHub repository, as one commit on the draft branch ${DRAFT_BRANCH} (created from main on the first change; nothing goes live until publish): configuration (\`config/app.yaml\`, \`config/<plugin>.yaml\`), Pug templates (\`theme/views/…\`), styles and scripts (\`assets/…\`). 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, then publish.`,
129
+ inputSchema: {
130
+ site: hostedSiteInput,
131
+ path: fileInput,
132
+ content: z.string().describe('The complete new text of the file.'),
133
+ message: messageInput,
134
+ },
135
+ }, hostedTool(async ({ site, path: input, content, message }) => {
136
+ commitMessage(message)
137
+ const file = repoPath(input, 'file path')
138
+ refuseSecrets(file, file)
139
+ refuseSegments(file, file, NO_WRITE_SEGMENTS, 'npm manages; add plugins to package.json instead')
140
+ const target = await openSite(site)
141
+ const { folders, tree } = await siteModel(target)
142
+ const distFolder = repoFolder(folders.dist, 'dist')
143
+ if (file === distFolder || file.startsWith(`${distFolder}/`)) {
144
+ throw new ToolError(`"${file}" is in the output folder (${distFolder}/), which every build deletes and recreates. Change the page, template or asset it is built from instead.`)
145
+ }
146
+ const pagesFolder = repoFolder(folders.pages, 'pages')
147
+ if (file.startsWith(`${pagesFolder}/`) && path.posix.extname(file) === '.md') {
148
+ throw new ToolError(`"${file}" is a page. Use write_page, which checks the frontmatter.`)
149
+ }
150
+ refuseBlockedPath(tree.entries, file)
151
+ const { current, commit } = await commitToDraft(target, file, 'a file', () => content, message)
152
+ const created = current === null
153
+ return ok(
154
+ { site: target.site, path: file, created, commit, branch: DRAFT_BRANCH },
155
+ `${created ? 'Created' : 'Updated'} ${file} in ${target.site}. ${NEXT}`,
156
+ )
157
+ }))
158
+
159
+ server.registerTool('delete_page', {
160
+ title: 'Delete a page',
161
+ description: `Deletes one page (a Markdown file in the pages folder) of a Nera site in a GitHub repository, as one commit on the draft branch ${DRAFT_BRANCH} (nothing goes live until publish). Links to it from other pages or the navigation are not changed — check them with validate afterwards, then publish.`,
162
+ inputSchema: { site: hostedSiteInput, path: pageInput, message: messageInput },
163
+ annotations: { destructiveHint: true },
164
+ }, hostedTool(async ({ site, path: page, message }) => {
165
+ commitMessage(message)
166
+ const file = repoPath(page, 'page path')
167
+ refuseSecrets(file, file)
168
+ const target = await openSite(site)
169
+ const { folders } = await siteModel(target)
170
+ requirePagePath(file, folders)
171
+ const { commit } = await commitToDraft(target, file, 'a page', (existing) => {
172
+ if (existing === null) {
173
+ throw new ToolError(`The page "${file}" does not exist in ${target.site}. Call get_site for the list of pages.`)
174
+ }
175
+ return null
176
+ }, message)
177
+ return ok(
178
+ { site: target.site, path: file, deleted: true, commit, branch: DRAFT_BRANCH },
179
+ `Deleted ${file} in ${target.site}. ${NEXT}`,
180
+ )
181
+ }))
182
+ }