@nera-static/mcp 0.0.0-stage → 1.0.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,222 @@
1
+ import { z } from 'zod'
2
+ import { freePort } from '../processes.js'
3
+ import { ok, tool, ToolError } from '../results.js'
4
+ import { failureText } from './cli.js'
5
+ import { resolveSite, siteInput } from './sites.js'
6
+
7
+ /** How long `preview` waits for `nera dev` to build the site and print its URL. */
8
+ export const PREVIEW_START_MS = 2 * 60 * 1000
9
+ /** How long one `publish` call waits for news (a sign-in step, the end) before it reports the run as still going. */
10
+ export const PUBLISH_WAIT_MS = 30 * 1000
11
+ /** The publish targets `nera publish --target` knows. */
12
+ const PUBLISH_TARGETS = ['github-pages', 'netlify']
13
+ /** How much of the CLI's last progress line a status carries. */
14
+ const PROGRESS_MAX = 300
15
+
16
+ /** Terminal colour codes (ESC [ … m), in case a child ignores NO_COLOR. Built from a string so the source holds no control character. */
17
+ const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g')
18
+ /** The address Vite prints once it listens: `➜ Local: http://localhost:3000/`. */
19
+ const LOCAL_URL = /Local:\s+(https?:\/\/[^\s]+)/
20
+
21
+ /**
22
+ * The lines of `nera publish` that ask the user to do something in the
23
+ * browser, and the lines that say it is done. Only these fixed shapes are
24
+ * read: the GitHub user code and verification page (the code is what the
25
+ * user types; it is not a credential — the device code and the tokens never
26
+ * appear in the CLI's output), the GitHub App installation page, and the
27
+ * Netlify authorization page.
28
+ */
29
+ const ACTIONS = [
30
+ {
31
+ kind: 'github_sign_in',
32
+ match: /To sign in to GitHub, enter the code ([A-Z0-9]{4,8}-[A-Z0-9]{4,8}) at (https:\/\/github\.com\/\S+)/,
33
+ action: ([, code, url]) => ({ kind: 'github_sign_in', code, url }),
34
+ done: /^Signed in as /,
35
+ },
36
+ {
37
+ kind: 'github_app_install',
38
+ match: /Install it at (https:\/\/github\.com\/apps\/\S+)/,
39
+ action: ([, url]) => ({ kind: 'github_app_install', url }),
40
+ done: /^Nera Static is installed on /,
41
+ },
42
+ {
43
+ kind: 'netlify_sign_in',
44
+ match: /To sign in to Netlify, open (https:\/\/app\.netlify\.com\/\S+) and choose "Authorize"/,
45
+ action: ([, url]) => ({ kind: 'netlify_sign_in', url }),
46
+ done: /^Signed in to Netlify/,
47
+ },
48
+ ]
49
+
50
+ const INSTRUCTIONS = {
51
+ github_sign_in: ({ code, url }) => `Ask the user to open ${url} and enter the code ${code}, then call publish again.`,
52
+ github_app_install: ({ url }) => `Ask the user to open ${url} and install the Nera Static app on their GitHub account, then call publish again.`,
53
+ netlify_sign_in: ({ url }) => `Ask the user to open ${url} and choose "Authorize", then call publish again.`,
54
+ }
55
+
56
+ function lines(text) {
57
+ return text.replace(ANSI, '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
58
+ }
59
+
60
+ /**
61
+ * What a running `nera publish` waits for: the last browser step it asked
62
+ * for that it has not reported done since, or null.
63
+ *
64
+ * @param {string} stderr the CLI's log (`--json` mode logs to stderr)
65
+ * @returns {{ kind: string, code?: string, url: string }|null}
66
+ */
67
+ export function pendingAction(stderr) {
68
+ let pending = null
69
+ for (const line of lines(stderr)) {
70
+ for (const known of ACTIONS) {
71
+ const found = line.match(known.match)
72
+ if (found) pending = known.action(found)
73
+ else if (pending?.kind === known.kind && known.done.test(line)) pending = null
74
+ }
75
+ }
76
+ return pending
77
+ }
78
+
79
+ function lastProgress(stderr) {
80
+ const last = lines(stderr).at(-1) ?? ''
81
+ return last.length > PROGRESS_MAX ? `${last.slice(0, PROGRESS_MAX)}…` : last
82
+ }
83
+
84
+ /**
85
+ * The local address `nera dev` serves on, once Vite has printed it.
86
+ *
87
+ * @param {string} stdout
88
+ * @returns {string|null}
89
+ */
90
+ export function previewUrl(stdout) {
91
+ return stdout.replace(ANSI, '').match(LOCAL_URL)?.[1] ?? null
92
+ }
93
+
94
+ function publishArgs({ target, repo, domain, private: isPrivate }) {
95
+ const args = ['publish', '--yes', '--json']
96
+ if (target !== undefined) args.push(`--target=${target}`)
97
+ if (repo !== undefined) args.push(`--repo=${repo}`)
98
+ if (domain !== undefined) args.push(`--domain=${domain}`)
99
+ if (isPrivate) args.push('--private')
100
+ return args
101
+ }
102
+
103
+ /**
104
+ * The tool result for a `nera publish` child: its JSON object once it has
105
+ * exited (and the record is dropped, so the next call publishes again), else
106
+ * where it stands.
107
+ */
108
+ function publishStatus(ctx, site, run) {
109
+ if (!run.exited) {
110
+ const action = pendingAction(run.stderr)
111
+ if (action) {
112
+ return ok(
113
+ { site, state: 'action_required', action },
114
+ `Publishing "${site}" waits for the user. ${INSTRUCTIONS[action.kind](action)}`,
115
+ )
116
+ }
117
+ return ok(
118
+ { site, state: 'running', progress: lastProgress(run.stderr) },
119
+ `Publishing "${site}" is still running (${lastProgress(run.stderr) || 'starting'}). Call publish again to follow it; the deploy can take a few minutes.`,
120
+ )
121
+ }
122
+
123
+ ctx.processes.forget(run.key)
124
+ let result
125
+ try {
126
+ result = JSON.parse(run.stdout)
127
+ } catch {
128
+ throw new ToolError(`Publishing "${site}" stopped without a result: ${failureText(run)}`)
129
+ }
130
+ if (!result.ok) {
131
+ const hint = result.deploy?.hint ? ` ${result.deploy.hint}` : ''
132
+ throw new ToolError(`Publishing "${site}" failed: ${result.error}.${hint}\n${JSON.stringify(result)}`)
133
+ }
134
+ return ok(
135
+ { site, state: 'published', result },
136
+ result.url ? `"${site}" is live at ${result.url}.` : `Publishing "${site}" finished.`,
137
+ )
138
+ }
139
+
140
+ /**
141
+ * Registers `preview` and `publish`, the two tools whose command outlives the
142
+ * call: they start a tracked child (`ctx.processes`) and later calls read it.
143
+ *
144
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
145
+ * @param {{ root: string, processes: ReturnType<typeof import('../processes.js').createProcesses>, timing?: { previewStartMs?: number, publishWaitMs?: number } }} ctx
146
+ */
147
+ export function registerLongRunningTools(server, ctx) {
148
+ const previewStartMs = ctx.timing?.previewStartMs ?? PREVIEW_START_MS
149
+ const publishWaitMs = ctx.timing?.publishWaitMs ?? PUBLISH_WAIT_MS
150
+
151
+ server.registerTool('preview', {
152
+ title: 'Preview a Nera site',
153
+ 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; edits show up there by themselves. Pass `stop: true` to stop it. The server stops when this MCP server closes. If it fails, call validate to find the cause.',
154
+ inputSchema: {
155
+ site: siteInput,
156
+ stop: z.boolean().optional().describe('Stop the site\'s running preview instead of starting one. Default false.'),
157
+ },
158
+ }, tool(async ({ site, stop = false }) => {
159
+ const resolved = await resolveSite(ctx, site)
160
+ const key = `preview:${resolved.dir}`
161
+ if (stop) {
162
+ const stopped = await ctx.processes.stop(key)
163
+ return ok(
164
+ { site: resolved.site, stopped },
165
+ stopped ? `Stopped the preview of "${resolved.site}".` : `No preview of "${resolved.site}" was running.`,
166
+ )
167
+ }
168
+
169
+ let run = ctx.processes.get(key)
170
+ let reused = Boolean(run && !run.exited)
171
+ if (!reused) {
172
+ ctx.processes.forget(key)
173
+ const port = await freePort()
174
+ // a call for the same site may have started one while this one looked for a port
175
+ run = ctx.processes.get(key)
176
+ reused = Boolean(run)
177
+ // BROWSER=none: Vite would open a browser on this computer otherwise
178
+ run ??= ctx.processes.start(key, 'nera', ['dev', '--port', String(port)], { cwd: resolved.dir, env: { BROWSER: 'none' } })
179
+ }
180
+ await run.waitFor((r) => r.exited || previewUrl(r.stdout) !== null, previewStartMs)
181
+
182
+ const url = previewUrl(run.stdout)
183
+ if (run.exited) {
184
+ ctx.processes.forget(key)
185
+ throw new ToolError(`The preview of "${resolved.site}" stopped: ${failureText(run)}\nCall validate to find the cause, fix it, then call preview again.`)
186
+ }
187
+ if (!url) {
188
+ await ctx.processes.stop(key)
189
+ throw new ToolError(`The preview of "${resolved.site}" printed no address within ${previewStartMs / 1000} s and was stopped.${run.stderr.trim() ? ` Its log: ${failureText(run)}` : ''}`)
190
+ }
191
+ return ok(
192
+ { site: resolved.site, url, reused },
193
+ `${reused ? 'The preview is running' : 'Started the preview'} at ${url}. Give the user this address; it updates by itself when files change.`,
194
+ )
195
+ }))
196
+
197
+ server.registerTool('publish', {
198
+ title: 'Publish a Nera site',
199
+ description: 'Puts a Nera site online (`nera publish`): signs in to GitHub, pushes the site to a GitHub repository and lets GitHub Actions build and deploy it to GitHub Pages (the default) or Netlify, then returns the live address. It runs in the background: the first call starts it and usually returns `action_required` with a sign-in code and a web address the user must open (GitHub sign-in, installing the Nera Static app, or Netlify authorization). Show the user exactly that, then call publish again with the same site — each call reports the current state (`action_required`, `running`) until it returns `published` with the live URL, or an error. `target`, `repo`, `domain` and `private` apply when a run starts; a call while one runs only reports on it. Run build first so you know the site builds.',
200
+ inputSchema: {
201
+ site: siteInput,
202
+ target: z.enum(PUBLISH_TARGETS).optional().describe('Where to host the site: `github-pages` (free, the default) or `netlify`. Leave out to keep the host the site was published to before.'),
203
+ repo: z.string().regex(/^[A-Za-z0-9._-]+$/, 'A repository name: letters, digits, `.`, `-`, `_`').optional().describe('The GitHub repository name to create or use (default: the site folder\'s name).'),
204
+ domain: z.string().optional().describe('A custom domain the user owns, e.g. `www.example.com`.'),
205
+ private: z.boolean().optional().describe('Make a new repository private (GitHub Pages then needs a paid GitHub plan). Default false.'),
206
+ },
207
+ }, tool(async ({ site, ...options }) => {
208
+ const resolved = await resolveSite(ctx, site)
209
+ const key = `publish:${resolved.dir}`
210
+ let run = ctx.processes.get(key)
211
+ if (!run) {
212
+ run = ctx.processes.start(key, 'nera', publishArgs(options), { cwd: resolved.dir })
213
+ }
214
+ const before = pendingAction(run.stderr)
215
+ await run.waitFor((r) => {
216
+ if (r.exited) return true
217
+ const now = pendingAction(r.stderr)
218
+ return now !== null && now.kind !== before?.kind
219
+ }, publishWaitMs)
220
+ return publishStatus(ctx, resolved.site, run)
221
+ }))
222
+ }
@@ -0,0 +1,182 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { resolveSiteModel } from '@nera-static/core'
4
+ import { z } from 'zod'
5
+ import { isInside, resolveInRoot } from '../paths.js'
6
+ import { ok, tool, ToolError } from '../results.js'
7
+
8
+ const CLI_PACKAGE = '@nera-static/nera'
9
+ const PLUGIN_PREFIX = '@nera-static/plugin-'
10
+ const NOT_PLUGINS = new Set(['@nera-static/plugin-utils'])
11
+ /** How deep `list_sites` looks below the root (the root itself is depth 0). */
12
+ const MAX_SITE_DEPTH = 3
13
+ const SKIPPED_FOLDERS = new Set(['node_modules', 'public'])
14
+
15
+ export const siteInput = z
16
+ .string()
17
+ .describe('The site folder, relative to the root folder this server works in (`.` for the root itself), as list_sites returns it.')
18
+
19
+ /**
20
+ * Reads a folder's `package.json`, or null when it has none or it is not JSON.
21
+ *
22
+ * @param {string} dir
23
+ * @returns {Promise<object|null>}
24
+ */
25
+ async function readPackage(dir) {
26
+ try {
27
+ return JSON.parse(await fs.readFile(path.join(dir, 'package.json'), 'utf8'))
28
+ } catch {
29
+ return null
30
+ }
31
+ }
32
+
33
+ function allDependencies(pkg) {
34
+ return { ...pkg?.devDependencies, ...pkg?.dependencies }
35
+ }
36
+
37
+ function isNeraSite(pkg) {
38
+ return Boolean(allDependencies(pkg)[CLI_PACKAGE])
39
+ }
40
+
41
+ /**
42
+ * The site-relative spelling of a path inside the root: forward slashes, `.`
43
+ * for the root itself.
44
+ */
45
+ export function relativeTo(base, target) {
46
+ return path.relative(base, target).split(path.sep).join('/') || '.'
47
+ }
48
+
49
+ /**
50
+ * Resolves a `site` argument to a Nera site inside the root: the folder must
51
+ * stay inside the root and its `package.json` must depend on `@nera-static/nera`.
52
+ *
53
+ * @param {{ root: string }} ctx
54
+ * @param {string} site path relative to the root
55
+ * @returns {Promise<{ dir: string, site: string, pkg: object }>} its real path, its normalised name and its package.json
56
+ * @throws {ToolError|import('../paths.js').PathError}
57
+ */
58
+ export async function resolveSite(ctx, site) {
59
+ const dir = await resolveInRoot(ctx.root, site, { label: 'site' })
60
+ const pkg = await readPackage(dir)
61
+ if (!isNeraSite(pkg)) {
62
+ throw new ToolError(`"${site}" is not a Nera site: it has no package.json that depends on ${CLI_PACKAGE}. Call list_sites to see the sites under the root, or create_site to make one.`)
63
+ }
64
+ return { dir, site: relativeTo(ctx.root, dir), pkg }
65
+ }
66
+
67
+ /**
68
+ * The site's model as the build sees it (`@nera-static/core`'s
69
+ * `resolveSiteModel`), plus the real paths of its pages and output folders,
70
+ * each checked to stay inside the site.
71
+ *
72
+ * @param {string} dir the site's real path
73
+ */
74
+ export async function siteFolders(dir) {
75
+ const model = resolveSiteModel({ cwd: dir })
76
+ const pagesDir = await resolveInRoot(dir, model.folders.pages, { label: 'pages folder (folders.pages in config/app.yaml)' })
77
+ const distDir = await resolveInRoot(dir, model.folders.dist, { label: 'output folder (folders.dist in config/app.yaml)' })
78
+ return { model, pagesDir, distDir }
79
+ }
80
+
81
+ /**
82
+ * Every `.md` file below `pagesDir`, site-relative and sorted. Symbolic links
83
+ * are not followed, so the listing never leaves the site.
84
+ */
85
+ async function listPages(dir, pagesDir) {
86
+ let entries
87
+ try {
88
+ entries = await fs.readdir(pagesDir, { recursive: true, withFileTypes: true })
89
+ } catch {
90
+ return []
91
+ }
92
+ return entries
93
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
94
+ .map((entry) => path.join(entry.parentPath, entry.name))
95
+ .filter((file) => isInside(pagesDir, file))
96
+ .map((file) => relativeTo(dir, file))
97
+ .sort()
98
+ }
99
+
100
+ /**
101
+ * Finds the Nera sites at or below `root`, up to `MAX_SITE_DEPTH` levels,
102
+ * without descending into a site, `node_modules`, `public` or hidden folders
103
+ * or following symbolic links.
104
+ */
105
+ export async function findSites(root) {
106
+ const found = []
107
+ async function visit(dir, depth) {
108
+ const pkg = await readPackage(dir)
109
+ if (isNeraSite(pkg)) {
110
+ found.push({
111
+ site: relativeTo(root, dir),
112
+ name: pkg.name ?? null,
113
+ nera: allDependencies(pkg)[CLI_PACKAGE],
114
+ })
115
+ return
116
+ }
117
+ if (depth >= MAX_SITE_DEPTH) return
118
+ let entries
119
+ try {
120
+ entries = await fs.readdir(dir, { withFileTypes: true })
121
+ } catch {
122
+ return
123
+ }
124
+ for (const entry of entries) {
125
+ if (!entry.isDirectory() || entry.name.startsWith('.') || SKIPPED_FOLDERS.has(entry.name)) continue
126
+ await visit(path.join(dir, entry.name), depth + 1)
127
+ }
128
+ }
129
+ await visit(root, 0)
130
+ return found.sort((a, b) => a.site.localeCompare(b.site))
131
+ }
132
+
133
+ /**
134
+ * Registers `list_sites` and `get_site`.
135
+ *
136
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
137
+ * @param {{ root: string }} ctx
138
+ */
139
+ export function registerSiteTools(server, ctx) {
140
+ server.registerTool('list_sites', {
141
+ title: 'List Nera sites',
142
+ description: 'Lists the Nera static sites in the folder this server works in. A Nera site is a folder whose package.json depends on @nera-static/nera; its pages are Markdown files in pages/, rendered through Pug layouts into plain HTML. Call this first to find the `site` value every other tool takes; if it returns no sites, call create_site.',
143
+ inputSchema: {},
144
+ annotations: { readOnlyHint: true },
145
+ }, tool(async () => {
146
+ const sites = await findSites(ctx.root)
147
+ const text = sites.length
148
+ ? `Found ${sites.length} Nera site(s): ${sites.map((s) => s.site).join(', ')}. Call get_site for one of them.`
149
+ : 'No Nera site in this folder yet. Call create_site to make one.'
150
+ return ok({ root: ctx.root, sites }, text)
151
+ }))
152
+
153
+ server.registerTool('get_site', {
154
+ title: 'Describe a Nera site',
155
+ description: 'Describes one Nera site: its configuration from config/app.yaml, the folders the build uses, its theme, its installed plugins and the list of its pages (Markdown files). 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.',
156
+ inputSchema: { site: siteInput },
157
+ annotations: { readOnlyHint: true },
158
+ }, tool(async ({ site }) => {
159
+ const resolved = await resolveSite(ctx, site)
160
+ const { model, pagesDir } = await siteFolders(resolved.dir)
161
+ const plugins = Object.keys(allDependencies(resolved.pkg))
162
+ .filter((name) => name.startsWith(PLUGIN_PREFIX) && !NOT_PLUGINS.has(name))
163
+ .sort()
164
+ const pages = await listPages(resolved.dir, pagesDir)
165
+ const structured = {
166
+ site: resolved.site,
167
+ name: resolved.pkg.name ?? null,
168
+ nera: allDependencies(resolved.pkg)[CLI_PACKAGE],
169
+ app: model.appConfig,
170
+ appConfigError: model.appConfigError,
171
+ folders: model.folders,
172
+ theme: model.theme ? { name: model.theme.name, package: model.theme.package } : null,
173
+ themeError: model.themeError,
174
+ plugins,
175
+ pages,
176
+ }
177
+ const problems = [model.appConfigError, model.themeError].filter(Boolean)
178
+ const text = `Site "${resolved.site}" has ${pages.length} page(s) and ${plugins.length} plugin(s).`
179
+ + (problems.length ? ` Problems: ${problems.join(' ')}` : '')
180
+ return ok(structured, text)
181
+ }))
182
+ }