@nera-static/mcp 1.3.0 → 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.
- package/.claude-plugin/plugin.json +2 -2
- package/CHANGELOG.md +28 -0
- package/README.md +58 -1
- package/bin/nera-mcp.js +203 -61
- package/docs/llms-full.txt +1122 -153
- package/package.json +3 -1
- package/src/hosted/app.js +129 -0
- package/src/hosted/checkout.js +427 -0
- package/src/hosted/config.js +89 -0
- package/src/hosted/consent.js +141 -0
- package/src/hosted/crypto.js +90 -0
- package/src/hosted/github.js +157 -0
- package/src/hosted/mcp.js +62 -0
- package/src/hosted/provider.js +369 -0
- package/src/hosted/repo.js +475 -0
- package/src/hosted/store.js +472 -0
- package/src/hosted/tools/publish.js +166 -0
- package/src/hosted/tools/read.js +336 -0
- package/src/hosted/tools/validate.js +44 -0
- package/src/hosted/tools/write.js +182 -0
- package/src/pages.js +168 -0
- package/src/prompts.js +52 -0
- package/src/resources.js +15 -3
- package/src/runner.js +17 -9
- package/src/tools/cli.js +7 -1
- package/src/tools/files.js +5 -104
- package/src/tools/long-running.js +2 -2
- package/src/tools/sites.js +31 -7
package/src/pages.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The page and path rules both modes share (plan D4): how a page file splits
|
|
2
|
+
// into frontmatter and body, how new frontmatter is edited into an existing
|
|
3
|
+
// block, that a page names its `layout`, and which paths no tool reads or
|
|
4
|
+
// writes. Pure functions only — the local file tools (src/tools/files.js) and
|
|
5
|
+
// the hosted repo tools apply them to a file on disk and a file on GitHub alike.
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { isDeepStrictEqual } from 'node:util'
|
|
8
|
+
import yaml from 'yaml'
|
|
9
|
+
import { ToolError } from './results.js'
|
|
10
|
+
|
|
11
|
+
export const FENCE = '---'
|
|
12
|
+
/** Path segments no file tool reads or writes: git internals may hold credentials. */
|
|
13
|
+
export const FORBIDDEN_SEGMENTS = new Set(['.git'])
|
|
14
|
+
/** File names no file tool reads or writes: `.env` files and `.npmrc` (npm `_authToken`) hold tokens. */
|
|
15
|
+
export const SECRET_FILE = /^(\.env(\..*)?|\.npmrc)$/
|
|
16
|
+
/** Path segments write_file refuses: installed packages belong to npm. */
|
|
17
|
+
export const NO_WRITE_SEGMENTS = new Set(['node_modules'])
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Splits a page into its frontmatter YAML and its Markdown body, the way the
|
|
21
|
+
* build reads it: a `---` first line opens the block, the next `---` line
|
|
22
|
+
* closes it (no closing line: the rest is frontmatter).
|
|
23
|
+
*
|
|
24
|
+
* @param {string} raw the file's text
|
|
25
|
+
* @returns {{ yamlText: string|null, body: string }} `yamlText` null when the page has no frontmatter
|
|
26
|
+
*/
|
|
27
|
+
export function splitPage(raw) {
|
|
28
|
+
// markdown-it, which the build parses pages with, reads CRLF as LF.
|
|
29
|
+
const lines = raw.replace(/\r\n/g, '\n').split('\n')
|
|
30
|
+
if (lines[0] !== FENCE) return { yamlText: null, body: raw }
|
|
31
|
+
const close = lines.indexOf(FENCE, 1)
|
|
32
|
+
if (close === -1) return { yamlText: lines.slice(1).join('\n'), body: '' }
|
|
33
|
+
return {
|
|
34
|
+
yamlText: lines.slice(1, close).join('\n'),
|
|
35
|
+
body: lines.slice(close + 1).join('\n'),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Parses frontmatter YAML into a document that keeps comments and quoting.
|
|
41
|
+
*
|
|
42
|
+
* @param {string|null} yamlText
|
|
43
|
+
* @returns {{ doc: import('yaml').Document|null, error: string|null }}
|
|
44
|
+
*/
|
|
45
|
+
export function parseFrontmatter(yamlText) {
|
|
46
|
+
const doc = yaml.parseDocument(yamlText ?? '', { merge: true, uniqueKeys: false })
|
|
47
|
+
if (doc.errors.length) {
|
|
48
|
+
return { doc: null, error: doc.errors[0].message }
|
|
49
|
+
}
|
|
50
|
+
if (doc.contents !== null && !yaml.isMap(doc.contents)) {
|
|
51
|
+
return { doc: null, error: 'The frontmatter is not a list of `key: value` lines.' }
|
|
52
|
+
}
|
|
53
|
+
return { doc, error: null }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Reads a page's text the way read_page returns it: the frontmatter as JSON
|
|
58
|
+
* (null when its YAML is invalid, with `error` saying why) and the body
|
|
59
|
+
* without its leading blank lines.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} raw the file's text
|
|
62
|
+
* @returns {{ frontmatter: object|null, body: string, error: string|null }}
|
|
63
|
+
*/
|
|
64
|
+
export function parsePage(raw) {
|
|
65
|
+
const { yamlText, body } = splitPage(raw)
|
|
66
|
+
const { doc, error } = parseFrontmatter(yamlText)
|
|
67
|
+
return { frontmatter: doc ? (doc.toJS() ?? {}) : null, body: body.replace(/^\n+/, ''), error }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The frontmatter YAML for `frontmatter`, edited into the page's existing
|
|
72
|
+
* frontmatter when it has one that parses: unchanged keys keep their comments,
|
|
73
|
+
* quoting and order, a changed value keeps its quoting style, keys left out are
|
|
74
|
+
* removed, new keys are appended. Nothing changed: the block stays byte for byte.
|
|
75
|
+
*
|
|
76
|
+
* @param {string|null} existingYaml the page's current frontmatter, null for none
|
|
77
|
+
* @param {Record<string, unknown>} frontmatter
|
|
78
|
+
* @returns {string}
|
|
79
|
+
*/
|
|
80
|
+
export function frontmatterText(existingYaml, frontmatter) {
|
|
81
|
+
const { doc } = existingYaml === null ? { doc: null } : parseFrontmatter(existingYaml)
|
|
82
|
+
if (!doc || doc.contents === null) {
|
|
83
|
+
return new yaml.Document(frontmatter).toString({ flowCollectionPadding: false })
|
|
84
|
+
}
|
|
85
|
+
const current = doc.toJS() ?? {}
|
|
86
|
+
let changed = false
|
|
87
|
+
for (const key of Object.keys(current)) {
|
|
88
|
+
if (!Object.hasOwn(frontmatter, key)) {
|
|
89
|
+
doc.delete(key)
|
|
90
|
+
changed = true
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
for (const [key, value] of Object.entries(frontmatter)) {
|
|
94
|
+
if (!isDeepStrictEqual(current[key], value)) {
|
|
95
|
+
doc.set(key, value)
|
|
96
|
+
changed = true
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (!changed) return withTrailingNewline(existingYaml)
|
|
100
|
+
return doc.toString({ flowCollectionPadding: false })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param {string} text
|
|
105
|
+
* @returns {string} `text`, ending in exactly the newline it had or one added
|
|
106
|
+
*/
|
|
107
|
+
export function withTrailingNewline(text) {
|
|
108
|
+
return text.endsWith('\n') ? text : `${text}\n`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Refuses frontmatter without `layout`: core never renders such a page.
|
|
113
|
+
*
|
|
114
|
+
* @param {Record<string, unknown>} frontmatter
|
|
115
|
+
* @throws {ToolError}
|
|
116
|
+
*/
|
|
117
|
+
export function requireLayout(frontmatter) {
|
|
118
|
+
if (typeof frontmatter.layout !== 'string' || frontmatter.layout.trim() === '') {
|
|
119
|
+
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).')
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The new text of a page written by write_page.
|
|
125
|
+
*
|
|
126
|
+
* @param {string|null} raw the page's current text, null for a new page
|
|
127
|
+
* @param {Record<string, unknown>} frontmatter
|
|
128
|
+
* @param {string} [body] the new Markdown body; undefined keeps the existing one
|
|
129
|
+
* @returns {string}
|
|
130
|
+
*/
|
|
131
|
+
export function composePage(raw, frontmatter, body) {
|
|
132
|
+
const existing = raw === null ? null : splitPage(raw)
|
|
133
|
+
const head = `${FENCE}\n${frontmatterText(existing?.yamlText ?? null, frontmatter)}${FENCE}\n`
|
|
134
|
+
return body === undefined
|
|
135
|
+
? head + (existing?.body ?? '')
|
|
136
|
+
: `${head}\n${withTrailingNewline(body.replace(/^\n+/, ''))}`
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Refuses `input` when it, or the site-relative real path it resolved to (a
|
|
141
|
+
* symbolic link may point into `.git/`), has a segment from `segments`.
|
|
142
|
+
*
|
|
143
|
+
* @param {string} input the path as the model gave it
|
|
144
|
+
* @param {string} resolved the site-relative path it resolved to
|
|
145
|
+
* @param {Set<string>} segments
|
|
146
|
+
* @param {string} why completes "…, which <why>."
|
|
147
|
+
* @throws {ToolError}
|
|
148
|
+
*/
|
|
149
|
+
export function refuseSegments(input, resolved, segments, why) {
|
|
150
|
+
const hit = [input, resolved]
|
|
151
|
+
.flatMap((candidate) => candidate.split(/[\\/]/))
|
|
152
|
+
.find((segment) => segments.has(segment))
|
|
153
|
+
if (hit) throw new ToolError(`"${input}" is inside ${hit}/, which ${why}.`)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Refuses git internals and files that can hold secrets (`.env*`, `.npmrc`).
|
|
158
|
+
*
|
|
159
|
+
* @param {string} input the path as the model gave it
|
|
160
|
+
* @param {string} resolved the site-relative path it resolved to
|
|
161
|
+
* @throws {ToolError}
|
|
162
|
+
*/
|
|
163
|
+
export function refuseSecrets(input, resolved) {
|
|
164
|
+
refuseSegments(input, resolved, FORBIDDEN_SEGMENTS, 'these tools never read or change')
|
|
165
|
+
if ([input, resolved].some((candidate) => SECRET_FILE.test(path.basename(candidate)))) {
|
|
166
|
+
throw new ToolError(`"${input}" can hold secrets (tokens, passwords); these tools never read or change it.`)
|
|
167
|
+
}
|
|
168
|
+
}
|
package/src/prompts.js
CHANGED
|
@@ -95,3 +95,55 @@ Steps:
|
|
|
95
95
|
3. Call publish for the site. It returns a short code and a GitHub web address: give me both and ask me to open the address, sign in to GitHub (or create a free account) and enter the code. Never ask me for a password or token.
|
|
96
96
|
4. After I confirm, call publish again for the same site until it reports the result, and give me the address where the site is now online. Tell me that later changes go online by calling publish again.`))
|
|
97
97
|
}
|
|
98
|
+
|
|
99
|
+
/** What the hosted prompts add: the site is a GitHub repository and changes wait on a draft. */
|
|
100
|
+
const ABOUT_HOSTED = 'Here each site is a GitHub repository of the user. write_page, write_file and delete_page commit to its draft branch nera-draft, one commit each with the message you pass; nothing goes live until publish merges the draft into main, which starts the site\'s deploy workflow once for all changes.'
|
|
101
|
+
|
|
102
|
+
const VALIDATE_AND_PUBLISH = 'Call validate and fix every error it reports (each message says how). Then ask me whether to put the changes live; when I agree, call publish, give me the address it reports and tell me the deploy takes a minute or two (preview shows how it went).'
|
|
103
|
+
|
|
104
|
+
const hostedSiteArg = z.string().optional().describe('The site as `owner/name`, as list_sites returns it; leave out to choose one with list_sites.')
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Registers the task prompts of the hosted mode, worded for its tools (write
|
|
108
|
+
* → validate → publish, no build): add a page, put my site online. The
|
|
109
|
+
* `new_*` prompts need `create_site`, which the hosted mode does not have.
|
|
110
|
+
*
|
|
111
|
+
* @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
|
|
112
|
+
*/
|
|
113
|
+
export function registerHostedPrompts(server) {
|
|
114
|
+
server.registerPrompt('add_page', {
|
|
115
|
+
title: 'Add a page',
|
|
116
|
+
description: 'Add a new page (or blog post) to a Nera site in a GitHub repository, in the style of its other pages, and put it live.',
|
|
117
|
+
argsSchema: {
|
|
118
|
+
site: hostedSiteArg,
|
|
119
|
+
topic: z.string().optional().describe('What the new page is about, e.g. "our new opening hours" or "a post about my trip to Lisbon".'),
|
|
120
|
+
},
|
|
121
|
+
}, ({ site, topic }) => userMessage(`Add a new page to my Nera site.${given('Site', site)}${given('The page', topic)}
|
|
122
|
+
|
|
123
|
+
${ABOUT_NERA}
|
|
124
|
+
|
|
125
|
+
${ABOUT_HOSTED}
|
|
126
|
+
|
|
127
|
+
Steps:
|
|
128
|
+
1. ${site ? `Call get_site with site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one. Then call get_site.'} Read the site's AGENTS.md with read_file if it has one.
|
|
129
|
+
2. Call read_page on an existing page of the same kind (a post for a post, a normal page otherwise) and copy its frontmatter fields and \`layout\`.
|
|
130
|
+
3. Choose a file name that fits the site's other pages (lowercase, hyphens, \`.md\`, in the same folder as its siblings) and write the page with write_page, with a short commit message. Ask me for content you do not know.
|
|
131
|
+
4. If the site has a navigation config (e.g. config/navigation.yaml, see get_site's plugins and read_file), add the page there when it belongs in the menu, with write_file.
|
|
132
|
+
5. ${VALIDATE_AND_PUBLISH}`))
|
|
133
|
+
|
|
134
|
+
server.registerPrompt('put_site_online', {
|
|
135
|
+
title: 'Put my site online',
|
|
136
|
+
description: 'Put the unpublished changes of a Nera site in a GitHub repository live: check them, publish them in one deploy and report the live address.',
|
|
137
|
+
argsSchema: { site: hostedSiteArg },
|
|
138
|
+
}, ({ site }) => userMessage(`Put my Nera site online.${given('Site', site)}
|
|
139
|
+
|
|
140
|
+
${ABOUT_NERA}
|
|
141
|
+
|
|
142
|
+
${ABOUT_HOSTED}
|
|
143
|
+
|
|
144
|
+
Steps:
|
|
145
|
+
1. ${site ? `Use site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one.'} Call preview to see the live address, the last deploy and how many changes wait unpublished.
|
|
146
|
+
2. Call validate and fix every error with write_page or write_file; tell me what you changed.
|
|
147
|
+
3. Call publish for the site. It merges the draft into main in one push and returns the deploy run and the address. If it reports that the repository has no deploy workflow, tell me to run \`nera publish\` once in the site on my computer, which sets it up.
|
|
148
|
+
4. Call preview after a minute or two and tell me whether the deploy succeeded and where the site is live. Tell me that later changes go live by calling publish again.`))
|
|
149
|
+
}
|
package/src/resources.js
CHANGED
|
@@ -53,12 +53,14 @@ function decodeSite(site) {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
/**
|
|
56
|
-
* Registers the
|
|
56
|
+
* Registers the resources that need no folder: the docs and the three
|
|
57
|
+
* catalogs. The hosted mode offers these alone; a site's `AGENTS.md` is its
|
|
58
|
+
* `read_file` there.
|
|
57
59
|
*
|
|
58
60
|
* @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
|
|
59
|
-
* @param {{
|
|
61
|
+
* @param {{ fetch: typeof fetch, docsFile?: string }} ctx
|
|
60
62
|
*/
|
|
61
|
-
export function
|
|
63
|
+
export function registerDocsResources(server, ctx) {
|
|
62
64
|
const docsFile = ctx.docsFile ?? BUNDLED_DOCS
|
|
63
65
|
|
|
64
66
|
server.registerResource('nera_docs', 'nera://docs/llms-full.txt', {
|
|
@@ -84,6 +86,16 @@ export function registerResources(server, ctx) {
|
|
|
84
86
|
return text(uri, 'application/json', JSON.stringify({ [kindName]: items }, null, 2))
|
|
85
87
|
}))
|
|
86
88
|
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Registers the docs, the three catalogs and each site's `AGENTS.md`.
|
|
93
|
+
*
|
|
94
|
+
* @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
|
|
95
|
+
* @param {{ root: string, fetch: typeof fetch, docsFile?: string }} ctx
|
|
96
|
+
*/
|
|
97
|
+
export function registerResources(server, ctx) {
|
|
98
|
+
registerDocsResources(server, ctx)
|
|
87
99
|
|
|
88
100
|
const readAgents = resource(async (uri, { site = '.' } = {}) => {
|
|
89
101
|
const resolved = await resolveSite(ctx, decodeSite(site))
|
package/src/runner.js
CHANGED
|
@@ -61,9 +61,11 @@ export function npmCommand(execPath = process.execPath, own = ownNpm()) {
|
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
/**
|
|
64
|
-
* The executable and leading arguments for `nera`, `npm` or `
|
|
64
|
+
* The executable and leading arguments for `nera`, `npm`, `node` or `tar` in
|
|
65
|
+
* `cwd`. `tar` is the system's, found on the child's PATH (the hosted
|
|
66
|
+
* `validate` unpacks a checkout with it).
|
|
65
67
|
*
|
|
66
|
-
* @param {'nera'|'npm'|'node'} command
|
|
68
|
+
* @param {'nera'|'npm'|'node'|'tar'} command
|
|
67
69
|
* @param {string} cwd
|
|
68
70
|
* @returns {{ file: string, prefix: string[] }}
|
|
69
71
|
* @throws {Error} for any other command
|
|
@@ -76,8 +78,10 @@ export function commandFor(command, cwd) {
|
|
|
76
78
|
return npmCommand()
|
|
77
79
|
case 'node':
|
|
78
80
|
return { file: process.execPath, prefix: [] }
|
|
81
|
+
case 'tar':
|
|
82
|
+
return { file: 'tar', prefix: [] }
|
|
79
83
|
default:
|
|
80
|
-
throw new Error(`Unknown command "${command}": the runner starts nera, npm or
|
|
84
|
+
throw new Error(`Unknown command "${command}": the runner starts nera, npm, node or tar only.`)
|
|
81
85
|
}
|
|
82
86
|
}
|
|
83
87
|
|
|
@@ -235,9 +239,11 @@ export function stopChild(child, { grace = KILL_GRACE_MS, platform = process.pla
|
|
|
235
239
|
}
|
|
236
240
|
|
|
237
241
|
/**
|
|
238
|
-
* Creates the function the tools run `nera`, `npm` and `
|
|
239
|
-
* commands that finish (`nera new`, `nera build`, `npm install`). Every
|
|
240
|
-
* gets its arguments as an array and the options of `spawnOptions
|
|
242
|
+
* Creates the function the tools run `nera`, `npm`, `node` and `tar` through,
|
|
243
|
+
* for commands that finish (`nera new`, `nera build`, `npm install`). Every
|
|
244
|
+
* run gets its arguments as an array and the options of `spawnOptions`; a run
|
|
245
|
+
* given `env` gets exactly that environment instead of `childEnv`'s (the
|
|
246
|
+
* hosted checkout strips it to PATH). A run is
|
|
241
247
|
* stopped (with everything it started) when it exceeds `timeout` or when `signal`
|
|
242
248
|
* aborts — the client cancelled the request, or the server closed.
|
|
243
249
|
*
|
|
@@ -246,17 +252,19 @@ export function stopChild(child, { grace = KILL_GRACE_MS, platform = process.pla
|
|
|
246
252
|
* @param {number} [options.timeout] milliseconds before a run is stopped
|
|
247
253
|
* @param {number} [options.grace] milliseconds between SIGTERM and SIGKILL
|
|
248
254
|
* @param {NodeJS.Platform} [options.platform] injected in tests
|
|
249
|
-
* @returns {(command: 'nera'|'npm'|'node', args: string[], options: { cwd: string, signal?: AbortSignal }) => Promise<{ code: number|null, stdout: string, stderr: string, timedOut: boolean, cancelled: boolean }>}
|
|
255
|
+
* @returns {(command: 'nera'|'npm'|'node'|'tar', args: string[], options: { cwd: string, signal?: AbortSignal, env?: Record<string, string> }) => Promise<{ code: number|null, stdout: string, stderr: string, timedOut: boolean, cancelled: boolean }>}
|
|
250
256
|
* `code` is null when the process was stopped or could not start; `stderr` then says why
|
|
251
257
|
*/
|
|
252
258
|
export function createRunner({ spawn = nodeSpawn, timeout = DEFAULT_TIMEOUT_MS, grace = KILL_GRACE_MS, platform = process.platform } = {}) {
|
|
253
|
-
return (command, args, { cwd, signal }) => new Promise((resolve) => {
|
|
259
|
+
return (command, args, { cwd, signal, env }) => new Promise((resolve) => {
|
|
254
260
|
const { file, prefix } = commandFor(command, cwd)
|
|
255
261
|
if (signal?.aborted) {
|
|
256
262
|
resolve({ code: null, stdout: '', stderr: 'Cancelled before it started.', timedOut: false, cancelled: true })
|
|
257
263
|
return
|
|
258
264
|
}
|
|
259
|
-
const
|
|
265
|
+
const options = spawnOptions(cwd, {}, platform)
|
|
266
|
+
if (env) options.env = env
|
|
267
|
+
const child = spawn(file, [...prefix, ...args], options)
|
|
260
268
|
let stdout = ''
|
|
261
269
|
let stderr = ''
|
|
262
270
|
let timedOut = false
|
package/src/tools/cli.js
CHANGED
|
@@ -36,7 +36,13 @@ export function failureText(run) {
|
|
|
36
36
|
return tail(run.stderr) || tail(run.stdout) || `exit code ${run.code}`
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
/**
|
|
40
|
+
* How many of the validator's records are errors and how many warnings.
|
|
41
|
+
*
|
|
42
|
+
* @param {Array<{severity: string}>} results
|
|
43
|
+
* @returns {{ errors: number, warnings: number }}
|
|
44
|
+
*/
|
|
45
|
+
export function countBySeverity(results) {
|
|
40
46
|
const errors = results.filter((r) => r.severity === 'error').length
|
|
41
47
|
return { errors, warnings: results.length - errors }
|
|
42
48
|
}
|
package/src/tools/files.js
CHANGED
|
@@ -1,21 +1,13 @@
|
|
|
1
1
|
import fs from 'node:fs/promises'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
-
import { isDeepStrictEqual } from 'node:util'
|
|
4
|
-
import yaml from 'yaml'
|
|
5
3
|
import { z } from 'zod'
|
|
4
|
+
import { NO_WRITE_SEGMENTS, composePage, parsePage, refuseSecrets, refuseSegments, requireLayout } from '../pages.js'
|
|
6
5
|
import { isInside, resolveInRoot } from '../paths.js'
|
|
7
6
|
import { ok, tool, ToolError } from '../results.js'
|
|
8
7
|
import { relativeTo, resolveSite, siteFolders, siteInput } from './sites.js'
|
|
9
8
|
|
|
10
9
|
/** Larger files are refused by read_file: a model cannot use them whole. */
|
|
11
10
|
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
11
|
|
|
20
12
|
const pageInput = z
|
|
21
13
|
.string()
|
|
@@ -24,71 +16,6 @@ const fileInput = z
|
|
|
24
16
|
.string()
|
|
25
17
|
.describe('The file, relative to the site folder — e.g. `config/app.yaml`, `theme/views/layouts/default.pug`, `assets/css/main.css`.')
|
|
26
18
|
|
|
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
19
|
async function statOrNull(file) {
|
|
93
20
|
try {
|
|
94
21
|
return await fs.stat(file)
|
|
@@ -108,24 +35,6 @@ async function readText(file, shown) {
|
|
|
108
35
|
}
|
|
109
36
|
}
|
|
110
37
|
|
|
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
38
|
/**
|
|
130
39
|
* Resolves a page argument: inside the site, inside its pages folder, a `.md`
|
|
131
40
|
* file.
|
|
@@ -178,10 +87,8 @@ export function registerFileTools(server, ctx) {
|
|
|
178
87
|
if (raw === null) {
|
|
179
88
|
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
89
|
}
|
|
181
|
-
const {
|
|
182
|
-
const {
|
|
183
|
-
const frontmatter = doc ? (doc.toJS() ?? {}) : null
|
|
184
|
-
const structured = { site: target.site, path: target.path, frontmatter, body: body.replace(/^\n+/, '') }
|
|
90
|
+
const { frontmatter, body, error } = parsePage(raw)
|
|
91
|
+
const structured = { site: target.site, path: target.path, frontmatter, body }
|
|
185
92
|
if (error) structured.frontmatterError = error
|
|
186
93
|
const text = error
|
|
187
94
|
? `Read ${target.path}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, passing the whole frontmatter.`
|
|
@@ -199,16 +106,10 @@ export function registerFileTools(server, ctx) {
|
|
|
199
106
|
body: z.string().optional().describe('The page\'s Markdown content, without the frontmatter. Leave out to keep the existing body.'),
|
|
200
107
|
},
|
|
201
108
|
}, tool(async ({ site, path: page, frontmatter, body }) => {
|
|
202
|
-
|
|
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
|
-
}
|
|
109
|
+
requireLayout(frontmatter)
|
|
205
110
|
const target = await resolvePage(ctx, site, page)
|
|
206
111
|
const raw = await readText(target.file, target.path)
|
|
207
|
-
const
|
|
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+/, ''))}`
|
|
112
|
+
const content = composePage(raw, frontmatter, body)
|
|
212
113
|
await fs.mkdir(path.dirname(target.file), { recursive: true })
|
|
213
114
|
await fs.writeFile(target.file, content)
|
|
214
115
|
const created = raw === null
|
|
@@ -204,7 +204,7 @@ export function registerLongRunningTools(server, ctx) {
|
|
|
204
204
|
|
|
205
205
|
server.registerTool('preview', {
|
|
206
206
|
title: 'Preview a Nera site',
|
|
207
|
-
description: 'Builds a Nera site and serves it on this computer (`nera dev`), rebuilding whenever a page, template or setting changes, and returns the local address (e.g. http://localhost:3000/) for the user to open in a browser. Calling it again for the same site returns the running server\'s address
|
|
207
|
+
description: 'Builds a Nera site and serves it on this computer (`nera dev`), rebuilding whenever a page, template or setting changes, and returns the local address (e.g. http://localhost:3000/) for the user to open in a browser. Calling it again for the same site returns the running server\'s address. After a change the user may need to reload the page in the browser to see it. Pass `stop: true` to stop it. The server stops when this MCP server closes. If it fails, call validate to find the cause.',
|
|
208
208
|
inputSchema: {
|
|
209
209
|
site: siteInput,
|
|
210
210
|
stop: z.boolean().optional().describe('Stop the site\'s running preview instead of starting one. Default false.'),
|
|
@@ -244,7 +244,7 @@ export function registerLongRunningTools(server, ctx) {
|
|
|
244
244
|
}
|
|
245
245
|
return ok(
|
|
246
246
|
{ site: resolved.site, url, reused },
|
|
247
|
-
`${reused ? 'The preview is running' : 'Started the preview'} at ${url}. Give the user this address;
|
|
247
|
+
`${reused ? 'The preview is running' : 'Started the preview'} at ${url}. Give the user this address. The site rebuilds after every change; the user may need to reload the page to see it.`,
|
|
248
248
|
)
|
|
249
249
|
}))
|
|
250
250
|
|
package/src/tools/sites.js
CHANGED
|
@@ -30,12 +30,38 @@ async function readPackage(dir) {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* @param {object|null} pkg a parsed package.json
|
|
35
|
+
* @returns {Record<string, string>} its dependencies and devDependencies
|
|
36
|
+
*/
|
|
33
37
|
function allDependencies(pkg) {
|
|
34
38
|
return { ...pkg?.devDependencies, ...pkg?.dependencies }
|
|
35
39
|
}
|
|
36
40
|
|
|
37
|
-
|
|
38
|
-
|
|
41
|
+
/**
|
|
42
|
+
* @param {object|null} pkg a parsed package.json
|
|
43
|
+
* @returns {boolean} whether it is a Nera site's: it depends on `@nera-static/nera`
|
|
44
|
+
*/
|
|
45
|
+
export function isNeraSite(pkg) {
|
|
46
|
+
return Boolean(neraRange(pkg))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {object|null} pkg a parsed package.json
|
|
51
|
+
* @returns {string|undefined} the `@nera-static/nera` range it depends on
|
|
52
|
+
*/
|
|
53
|
+
export function neraRange(pkg) {
|
|
54
|
+
return allDependencies(pkg)[CLI_PACKAGE]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param {object|null} pkg a parsed package.json
|
|
59
|
+
* @returns {string[]} the Nera plugins it depends on, sorted
|
|
60
|
+
*/
|
|
61
|
+
export function sitePlugins(pkg) {
|
|
62
|
+
return Object.keys(allDependencies(pkg))
|
|
63
|
+
.filter((name) => name.startsWith(PLUGIN_PREFIX) && !NOT_PLUGINS.has(name))
|
|
64
|
+
.sort()
|
|
39
65
|
}
|
|
40
66
|
|
|
41
67
|
/**
|
|
@@ -110,7 +136,7 @@ export async function findSites(root) {
|
|
|
110
136
|
found.push({
|
|
111
137
|
site: relativeTo(root, dir),
|
|
112
138
|
name: pkg.name ?? null,
|
|
113
|
-
nera:
|
|
139
|
+
nera: neraRange(pkg),
|
|
114
140
|
})
|
|
115
141
|
return
|
|
116
142
|
}
|
|
@@ -158,14 +184,12 @@ export function registerSiteTools(server, ctx) {
|
|
|
158
184
|
}, tool(async ({ site }) => {
|
|
159
185
|
const resolved = await resolveSite(ctx, site)
|
|
160
186
|
const { model, pagesDir } = await siteFolders(resolved.dir)
|
|
161
|
-
const plugins =
|
|
162
|
-
.filter((name) => name.startsWith(PLUGIN_PREFIX) && !NOT_PLUGINS.has(name))
|
|
163
|
-
.sort()
|
|
187
|
+
const plugins = sitePlugins(resolved.pkg)
|
|
164
188
|
const pages = await listPages(resolved.dir, pagesDir)
|
|
165
189
|
const structured = {
|
|
166
190
|
site: resolved.site,
|
|
167
191
|
name: resolved.pkg.name ?? null,
|
|
168
|
-
nera:
|
|
192
|
+
nera: neraRange(resolved.pkg),
|
|
169
193
|
app: model.appConfig,
|
|
170
194
|
appConfigError: model.appConfigError,
|
|
171
195
|
folders: model.folders,
|