@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,119 @@
1
+ import fs from 'node:fs/promises'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'
4
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'
5
+ import { KINDS, loadCatalog } from './catalog.js'
6
+ import { PathError, resolveInRoot } from './paths.js'
7
+ import { ToolError } from './results.js'
8
+ import { findSites, resolveSite } from './tools/sites.js'
9
+
10
+ export const DOCS_URL = 'https://nera.js.org/llms-full.txt'
11
+ /** Where `scripts/fetch-docs.js` puts the docs at release (`prepack`). */
12
+ export const BUNDLED_DOCS = fileURLToPath(new URL('../docs/llms-full.txt', import.meta.url))
13
+ const AGENTS_FILE = 'AGENTS.md'
14
+
15
+ /**
16
+ * Reads a resource, turning a user mistake (a path outside the root, a folder
17
+ * that is no site, an unreachable registry) into an `InvalidParams` resource
18
+ * error with our message. Resources have no `isError` result, so this is the
19
+ * protocol's way to say what is wrong.
20
+ */
21
+ function resource(read) {
22
+ return async (...args) => {
23
+ try {
24
+ return await read(...args)
25
+ } catch (error) {
26
+ if (error instanceof ToolError || error instanceof PathError) {
27
+ throw new McpError(ErrorCode.InvalidParams, error.message)
28
+ }
29
+ throw error
30
+ }
31
+ }
32
+ }
33
+
34
+ function text(uri, mimeType, body) {
35
+ return { contents: [{ uri: uri.href, mimeType, text: body }] }
36
+ }
37
+
38
+ /**
39
+ * The `AGENTS.md` URI of a site (`.` is the root itself, whose URI has no site
40
+ * segment: a URL parser removes a `.` segment anyway).
41
+ */
42
+ export function agentsUri(site) {
43
+ return site === '.' ? `nera://site/${AGENTS_FILE}` : `nera://site/${site.split('/').map(encodeURIComponent).join('/')}/${AGENTS_FILE}`
44
+ }
45
+
46
+ /** The `{site}` variable of a resource URI, percent-decoded. */
47
+ function decodeSite(site) {
48
+ try {
49
+ return decodeURIComponent(String(site))
50
+ } catch {
51
+ throw new PathError(`The site "${site}" in the resource URI is not validly percent-encoded. Use the URI list_sites or the resource list gives.`)
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Registers the docs, the three catalogs and each site's `AGENTS.md`.
57
+ *
58
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
59
+ * @param {{ root: string, fetch: typeof fetch, docsFile?: string }} ctx
60
+ */
61
+ export function registerResources(server, ctx) {
62
+ const docsFile = ctx.docsFile ?? BUNDLED_DOCS
63
+
64
+ server.registerResource('nera_docs', 'nera://docs/llms-full.txt', {
65
+ title: 'Nera documentation',
66
+ description: 'The complete Nera documentation and tutorials in one Markdown file (pages, layouts, configuration, plugins, themes, publishing), as published on nera.js.org for this release. Read it when a task needs more than the tool descriptions say.',
67
+ mimeType: 'text/markdown',
68
+ }, resource(async (uri) => {
69
+ try {
70
+ return text(uri, 'text/markdown', await fs.readFile(docsFile, 'utf8'))
71
+ } catch (error) {
72
+ if (error.code !== 'ENOENT') throw error
73
+ return text(uri, 'text/markdown', `The Nera documentation is not bundled with this copy of the server (it is added when the package is released). Read it online: ${DOCS_URL}`)
74
+ }
75
+ }))
76
+
77
+ for (const kindName of Object.keys(KINDS)) {
78
+ server.registerResource(`nera_${kindName}`, `nera://catalog/${kindName}`, {
79
+ title: `Nera ${KINDS[kindName].title}`,
80
+ description: `The Nera ${KINDS[kindName].title} on npm as JSON, official ones first (the same list as the list_${kindName} tool).`,
81
+ mimeType: 'application/json',
82
+ }, resource(async (uri) => {
83
+ const items = await loadCatalog(ctx.fetch, kindName)
84
+ return text(uri, 'application/json', JSON.stringify({ [kindName]: items }, null, 2))
85
+ }))
86
+ }
87
+
88
+ const readAgents = resource(async (uri, { site = '.' } = {}) => {
89
+ const resolved = await resolveSite(ctx, decodeSite(site))
90
+ const file = await resolveInRoot(resolved.dir, AGENTS_FILE, { label: 'AGENTS.md' })
91
+ try {
92
+ return text(uri, 'text/markdown', await fs.readFile(file, 'utf8'))
93
+ } catch (error) {
94
+ if (error.code !== 'ENOENT') throw error
95
+ throw new ToolError(`The site "${resolved.site}" has no ${AGENTS_FILE} (sites created before @nera-static/nera 1.6.0 lack it; running \`nera update\` in the site writes one). Call get_site instead.`)
96
+ }
97
+ })
98
+ const listAgents = async () => {
99
+ const sites = await findSites(ctx.root)
100
+ return {
101
+ resources: sites.map(({ site }) => ({
102
+ uri: agentsUri(site),
103
+ name: `${site} ${AGENTS_FILE}`,
104
+ mimeType: 'text/markdown',
105
+ })),
106
+ }
107
+ }
108
+ const agentsMetadata = {
109
+ title: 'A site\'s AGENTS.md',
110
+ description: 'The AGENTS.md of a Nera site: how that site is built, which commands it runs and what to keep in mind when editing it. Read it before changing a site. `{site}` is the folder list_sites returns.',
111
+ mimeType: 'text/markdown',
112
+ }
113
+ // A site below the root; the root itself has no site segment (see agentsUri).
114
+ server.registerResource('site_agents', new ResourceTemplate(`nera://site/{+site}/${AGENTS_FILE}`, { list: listAgents }), agentsMetadata, readAgents)
115
+ server.registerResource('root_site_agents', new ResourceTemplate(`nera://site/${AGENTS_FILE}`, { list: undefined }), {
116
+ ...agentsMetadata,
117
+ description: 'The AGENTS.md of the Nera site in the root folder itself, when the root is a site.',
118
+ }, readAgents)
119
+ }
package/src/results.js ADDED
@@ -0,0 +1,66 @@
1
+ import { PathError } from './paths.js'
2
+
3
+ /**
4
+ * A mistake in what a tool was asked to do (a missing site, a page without
5
+ * `layout`, a file that does not exist). The tool wrapper turns it into an
6
+ * `isError` result whose text is this message, so it must say what is wrong,
7
+ * where, and what to do instead.
8
+ */
9
+ export class ToolError extends Error {
10
+ constructor(message) {
11
+ super(message)
12
+ this.name = 'ToolError'
13
+ }
14
+ }
15
+
16
+ /**
17
+ * A successful tool result: the JSON a client can use, plus a short text for
18
+ * a human or a client that ignores structured content.
19
+ *
20
+ * @param {object} structured the result as JSON (`structuredContent`)
21
+ * @param {string} text one or two sentences saying what happened and what to do next
22
+ * @returns {{ content: Array<{ type: 'text', text: string }>, structuredContent: object }}
23
+ */
24
+ export function ok(structured, text) {
25
+ return {
26
+ content: [{ type: 'text', text }],
27
+ structuredContent: structured,
28
+ }
29
+ }
30
+
31
+ /**
32
+ * A failed tool result (`isError: true`) — the model sees the message and can
33
+ * correct its call; the protocol call itself succeeds.
34
+ *
35
+ * @param {string} message what is wrong, where, and what to do instead
36
+ * @returns {{ content: Array<{ type: 'text', text: string }>, isError: true }}
37
+ */
38
+ export function fail(message) {
39
+ return {
40
+ content: [{ type: 'text', text: message }],
41
+ isError: true,
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Wraps a tool handler so a user mistake (`ToolError`, `PathError`) becomes an
47
+ * `isError` result instead of an exception. Anything else is a defect and is
48
+ * rethrown; the SDK reports it as an `isError` result too, but without our
49
+ * wording.
50
+ *
51
+ * @template T
52
+ * @param {(args: T, extra: object) => Promise<object>} handler
53
+ * @returns {(args: T, extra: object) => Promise<object>}
54
+ */
55
+ export function tool(handler) {
56
+ return async (args, extra) => {
57
+ try {
58
+ return await handler(args, extra)
59
+ } catch (error) {
60
+ if (error instanceof ToolError || error instanceof PathError) {
61
+ return fail(error.message)
62
+ }
63
+ throw error
64
+ }
65
+ }
66
+ }
package/src/runner.js ADDED
@@ -0,0 +1,261 @@
1
+ import { spawn as nodeSpawn } from 'node:child_process'
2
+ import { existsSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import path from 'node:path'
5
+
6
+ const require = createRequire(import.meta.url)
7
+ const NERA_BIN = path.join('node_modules', '@nera-static', 'nera', 'bin', 'nera.js')
8
+ /** `npm install` inside `nera new` can take minutes; past this a run is stopped. */
9
+ export const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000
10
+ /** Each captured stream keeps at most this many characters (its end). */
11
+ const MAX_CAPTURE = 1024 * 1024
12
+ /** How long a stopped child gets to exit after SIGTERM before it gets SIGKILL. */
13
+ export const KILL_GRACE_MS = 5000
14
+
15
+ /**
16
+ * The `nera` script a command in `cwd` runs: the site's own
17
+ * `node_modules/@nera-static/nera` when it has one (so a site builds with the
18
+ * CLI version it pins), else the one this server depends on.
19
+ *
20
+ * @param {string} cwd
21
+ * @returns {string} absolute path of `bin/nera.js`
22
+ */
23
+ export function neraBin(cwd) {
24
+ const local = path.join(cwd, NERA_BIN)
25
+ if (existsSync(local)) return local
26
+ return path.join(path.dirname(require.resolve('@nera-static/nera/package.json')), 'bin', 'nera.js')
27
+ }
28
+
29
+ /**
30
+ * How to start npm without a shell: its `npm-cli.js` next to the running Node
31
+ * (where every Node installer puts it), else the `npm` executable on the PATH.
32
+ * Running the script through `process.execPath` avoids `npm.cmd` on Windows,
33
+ * which Node refuses to spawn without a shell.
34
+ *
35
+ * @param {string} [execPath] the Node binary
36
+ * @returns {{ file: string, prefix: string[] }}
37
+ */
38
+ export function npmCommand(execPath = process.execPath) {
39
+ const bin = path.dirname(execPath)
40
+ const candidates = [
41
+ path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
42
+ path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
43
+ ]
44
+ const script = candidates.find((candidate) => existsSync(candidate))
45
+ return script ? { file: execPath, prefix: [script] } : { file: 'npm', prefix: [] }
46
+ }
47
+
48
+ /**
49
+ * The executable and leading arguments for `nera`, `npm` or `node` in `cwd`.
50
+ *
51
+ * @param {'nera'|'npm'|'node'} command
52
+ * @param {string} cwd
53
+ * @returns {{ file: string, prefix: string[] }}
54
+ * @throws {Error} for any other command
55
+ */
56
+ export function commandFor(command, cwd) {
57
+ switch (command) {
58
+ case 'nera':
59
+ return { file: process.execPath, prefix: [neraBin(cwd)] }
60
+ case 'npm':
61
+ return npmCommand()
62
+ case 'node':
63
+ return { file: process.execPath, prefix: [] }
64
+ default:
65
+ throw new Error(`Unknown command "${command}": the runner starts nera, npm or node only.`)
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Keeps the end of a captured stream, at most `MAX_CAPTURE` characters.
71
+ *
72
+ * @param {string} text
73
+ * @returns {string}
74
+ */
75
+ export function capped(text) {
76
+ return text.length > MAX_CAPTURE ? text.slice(-MAX_CAPTURE) : text
77
+ }
78
+
79
+ /**
80
+ * The options every child is spawned with: no shell (arguments are never
81
+ * interpreted), no stdin (nothing can wait for an answer), both output streams
82
+ * piped (none of it reaches this process's stdout), no colour codes, and — on
83
+ * POSIX — its own process group, so `stopChild` reaches the processes it
84
+ * starts in turn (npm's scripts, Vite's workers). Windows has no process
85
+ * groups to signal; `stopChild` ends the tree with `taskkill /T` there.
86
+ *
87
+ * @param {string} cwd
88
+ * @param {Record<string, string>} [env] added to this process's environment
89
+ * @param {NodeJS.Platform} [platform] injected in tests
90
+ * @returns {import('node:child_process').SpawnOptions}
91
+ */
92
+ export function spawnOptions(cwd, env = {}, platform = process.platform) {
93
+ return {
94
+ cwd,
95
+ stdio: ['ignore', 'pipe', 'pipe'],
96
+ shell: false,
97
+ detached: platform !== 'win32',
98
+ env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', ...env },
99
+ }
100
+ }
101
+
102
+ function hasExited(child) {
103
+ return child.exitCode !== null || child.signalCode !== null
104
+ }
105
+
106
+ /**
107
+ * `taskkill` by its absolute path: Windows looks for a bare command name in
108
+ * the working directory before PATH, so a `taskkill.exe` there would run
109
+ * instead.
110
+ */
111
+ const TASKKILL = path.win32.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe')
112
+
113
+ /**
114
+ * Ends a child's whole process tree on Windows: `taskkill /pid <pid> /T /F`,
115
+ * spawned without a shell and with its output ignored. Its failure (the
116
+ * process is gone already) is swallowed; when `taskkill` cannot even start,
117
+ * the child itself is terminated, so at least it does not survive.
118
+ *
119
+ * @param {import('node:child_process').ChildProcess} child
120
+ * @param {typeof nodeSpawn} spawn
121
+ */
122
+ function killWindowsTree(child, spawn) {
123
+ const killChild = () => {
124
+ try {
125
+ child.kill('SIGKILL')
126
+ } catch {
127
+ // already gone
128
+ }
129
+ }
130
+ try {
131
+ const taskkill = spawn(TASKKILL, ['/pid', String(child.pid), '/T', '/F'], {
132
+ stdio: 'ignore',
133
+ shell: false,
134
+ windowsHide: true,
135
+ })
136
+ taskkill.on('error', killChild)
137
+ } catch {
138
+ killChild()
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Sends `signal` to a child and everything it started: its process group on
144
+ * POSIX, its process tree (`taskkill /T /F`, always forced) on Windows.
145
+ *
146
+ * @param {import('node:child_process').ChildProcess} child
147
+ * @param {NodeJS.Signals} signal
148
+ * @param {{ platform: NodeJS.Platform, spawn: typeof nodeSpawn }} options
149
+ */
150
+ function signalGroup(child, signal, { platform, spawn }) {
151
+ if (platform === 'win32') {
152
+ killWindowsTree(child, spawn)
153
+ return
154
+ }
155
+ try {
156
+ if (child.pid) {
157
+ process.kill(-child.pid, signal)
158
+ return
159
+ }
160
+ } catch {
161
+ // the group is gone already, or this child leads none: signal the child itself
162
+ }
163
+ try {
164
+ child.kill(signal)
165
+ } catch {
166
+ // already gone
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Stops a child and everything it started. On POSIX: SIGTERM to its process
172
+ * group, then SIGKILL when it is still running after `grace` milliseconds, and
173
+ * SIGKILL to what is left of the group once it has exited. On Windows:
174
+ * `taskkill /T /F` at once (a console process has no SIGTERM to honour),
175
+ * again after `grace` if it still runs, never after it exited — its pid may
176
+ * belong to someone else by then. Resolves once the child has exited (at once
177
+ * when it already has).
178
+ *
179
+ * @param {import('node:child_process').ChildProcess} child
180
+ * @param {object} [options]
181
+ * @param {number} [options.grace]
182
+ * @param {NodeJS.Platform} [options.platform] injected in tests
183
+ * @param {typeof nodeSpawn} [options.spawn] starts `taskkill`; injected in tests
184
+ * @returns {Promise<void>}
185
+ */
186
+ export function stopChild(child, { grace = KILL_GRACE_MS, platform = process.platform, spawn = nodeSpawn } = {}) {
187
+ // never started (no pid), or exited long ago: nothing to stop, and its
188
+ // group id may belong to someone else by now
189
+ if (!child.pid || hasExited(child)) return Promise.resolve()
190
+ const tree = { platform, spawn }
191
+ return new Promise((resolve) => {
192
+ const timer = setTimeout(() => signalGroup(child, 'SIGKILL', tree), grace)
193
+ child.once('exit', () => {
194
+ clearTimeout(timer)
195
+ // what the child started may outlive it: end the rest of the group
196
+ if (platform !== 'win32') signalGroup(child, 'SIGKILL', tree)
197
+ resolve()
198
+ })
199
+ signalGroup(child, 'SIGTERM', tree)
200
+ })
201
+ }
202
+
203
+ /**
204
+ * Creates the function the tools run `nera`, `npm` and `node` through, for
205
+ * commands that finish (`nera new`, `nera build`, `npm install`). Every run
206
+ * gets its arguments as an array and the options of `spawnOptions`. A run is
207
+ * stopped (with everything it started) when it exceeds `timeout` or when `signal`
208
+ * aborts — the client cancelled the request, or the server closed.
209
+ *
210
+ * @param {object} [options]
211
+ * @param {typeof nodeSpawn} [options.spawn] injected in tests
212
+ * @param {number} [options.timeout] milliseconds before a run is stopped
213
+ * @param {number} [options.grace] milliseconds between SIGTERM and SIGKILL
214
+ * @param {NodeJS.Platform} [options.platform] injected in tests
215
+ * @returns {(command: 'nera'|'npm'|'node', args: string[], options: { cwd: string, signal?: AbortSignal }) => Promise<{ code: number|null, stdout: string, stderr: string, timedOut: boolean, cancelled: boolean }>}
216
+ * `code` is null when the process was stopped or could not start; `stderr` then says why
217
+ */
218
+ export function createRunner({ spawn = nodeSpawn, timeout = DEFAULT_TIMEOUT_MS, grace = KILL_GRACE_MS, platform = process.platform } = {}) {
219
+ return (command, args, { cwd, signal }) => new Promise((resolve) => {
220
+ const { file, prefix } = commandFor(command, cwd)
221
+ if (signal?.aborted) {
222
+ resolve({ code: null, stdout: '', stderr: 'Cancelled before it started.', timedOut: false, cancelled: true })
223
+ return
224
+ }
225
+ const child = spawn(file, [...prefix, ...args], spawnOptions(cwd, {}, platform))
226
+ let stdout = ''
227
+ let stderr = ''
228
+ let timedOut = false
229
+ let cancelled = false
230
+ let settled = false
231
+ const finish = (code) => {
232
+ if (settled) return
233
+ settled = true
234
+ clearTimeout(timer)
235
+ signal?.removeEventListener('abort', onAbort)
236
+ resolve({ code, stdout, stderr, timedOut, cancelled })
237
+ }
238
+ const stop = (reason) => {
239
+ stderr = capped(`${stderr}\n${reason}`)
240
+ stopChild(child, { grace, platform, spawn })
241
+ }
242
+ const onAbort = () => {
243
+ cancelled = true
244
+ stop('Cancelled.')
245
+ }
246
+ const timer = setTimeout(() => {
247
+ timedOut = true
248
+ stop(`Stopped after ${timeout / 1000} s.`)
249
+ }, timeout)
250
+ signal?.addEventListener('abort', onAbort, { once: true })
251
+ child.stdout.setEncoding('utf8')
252
+ child.stderr.setEncoding('utf8')
253
+ child.stdout.on('data', (chunk) => { stdout = capped(stdout + chunk) })
254
+ child.stderr.on('data', (chunk) => { stderr = capped(stderr + chunk) })
255
+ child.on('error', (error) => {
256
+ stderr = capped(`${stderr}\nCould not start ${command}: ${error.message}`)
257
+ finish(null)
258
+ })
259
+ child.on('close', (code) => finish(code))
260
+ })
261
+ }
package/src/server.js ADDED
@@ -0,0 +1,51 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
2
+ import pkg from '../package.json' with { type: 'json' }
3
+ import { registerCatalogTools } from './catalog.js'
4
+ import { realRoot } from './paths.js'
5
+ import { createProcesses } from './processes.js'
6
+ import { registerPrompts } from './prompts.js'
7
+ import { registerResources } from './resources.js'
8
+ import { createRunner } from './runner.js'
9
+ import { registerCliTools } from './tools/cli.js'
10
+ import { registerFileTools } from './tools/files.js'
11
+ import { registerLongRunningTools } from './tools/long-running.js'
12
+ import { registerSiteTools } from './tools/sites.js'
13
+
14
+ /**
15
+ * Builds the Nera MCP server for one root folder, with every tool registered
16
+ * but no transport attached: the stdio bin connects a `StdioServerTransport`,
17
+ * tests an in-memory one, the hosted mode (L7b) a Streamable HTTP one.
18
+ *
19
+ * @param {object} options
20
+ * @param {string} options.root the folder the server may work in; every path a tool takes is checked against it
21
+ * @param {ReturnType<typeof createRunner>} [options.runner] runs the `nera`, `npm` and `node` commands (injected so tests spawn nothing)
22
+ * @param {typeof fetch} [options.fetch] fetches the npm registry catalogs (injected so tests stay offline)
23
+ * @param {string} [options.docsFile] the bundled `llms-full.txt` (default: the package's `docs/`; injected so tests can point at a missing one)
24
+ * @param {ReturnType<typeof createProcesses>} [options.processes] tracks the children that outlive a call (`preview`, `publish`); all are stopped when the server closes
25
+ * @param {{ previewStartMs?: number, publishWaitMs?: number }} [options.timing] how long `preview` and `publish` wait (shortened in tests)
26
+ * @returns {Promise<McpServer>}
27
+ * @throws {import('./paths.js').PathError} when `root` does not exist or is not a folder
28
+ */
29
+ export async function createServer({ root, runner = createRunner(), fetch = globalThis.fetch, docsFile, processes = createProcesses(), timing }) {
30
+ const ctx = { root: await realRoot(root), runner, fetch, docsFile, processes, timing }
31
+ const server = new McpServer(
32
+ { name: pkg.name, version: pkg.version },
33
+ {
34
+ instructions: `Tools for Nera, a static site generator: a site is Markdown pages (pages/) rendered through Pug layouts into plain HTML. You work in ${ctx.root}. Start with list_sites; read get_site before editing a site. The prompts walk through whole tasks, the nera://docs/llms-full.txt resource holds the full documentation.`,
35
+ },
36
+ )
37
+ registerSiteTools(server, ctx)
38
+ registerFileTools(server, ctx)
39
+ registerCliTools(server, ctx)
40
+ registerLongRunningTools(server, ctx)
41
+ registerCatalogTools(server, ctx)
42
+ registerResources(server, ctx)
43
+ registerPrompts(server)
44
+ // Closing (server.close(), or the client hanging up) aborts every running
45
+ // call, which stops the short commands through their signal; the
46
+ // long-running children are stopped here.
47
+ server.server.onclose = () => {
48
+ processes.stopAll().catch((error) => console.error(`Stopping the preview and publish processes failed: ${error.message}`))
49
+ }
50
+ return server
51
+ }