@nera-static/mcp 1.0.1 → 1.2.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,50 @@
1
+ # Recipe: multilingual site
2
+
3
+ A second language beside the first, e.g. English at `/` and German at
4
+ `/de/`.
5
+
6
+ ## Steps
7
+
8
+ 1. Keep the default language at the root of `pages/` and put each other
9
+ language in its own folder: `pages/de/index.md` becomes `/de/index.html`.
10
+ 2. Give every page in another language `lang` in its frontmatter
11
+ (`lang: de`). Pages without it use `lang` from `config/app.yaml`.
12
+ 3. Pair the versions of a page with the same `slug` in their frontmatter
13
+ (`slug: about` on `pages/about.md` and `pages/de/ueber-uns.md`).
14
+ 4. Template texts: write `t('key')` in Pug and add the texts per language
15
+ under `translations:` in `config/app.yaml`:
16
+
17
+ ```yaml
18
+ lang: en
19
+ translations:
20
+ en:
21
+ read_more: Read more
22
+ de:
23
+ read_more: Weiterlesen
24
+ ```
25
+
26
+ `t()` uses the page's `lang`, else the site's.
27
+ 5. In `theme/views/layouts/layout.pug`, set the document language from the
28
+ page: `html(lang=meta.lang || app.lang)`.
29
+ 6. Menus: one group per language in `config/navigation.yaml` (`main:` and
30
+ `main_de:`), each rendered with the menu mixin and the language root,
31
+ e.g. `+linkListNav(app.nav.main_de.elements, 'nav--main', '/de')`.
32
+ Add a link to the other language's version of the page.
33
+ 7. Search engines: `@nera-static/plugin-canonical-links` with
34
+ `available_languages` in `config/canonical-links.yaml` adds `hreflang`
35
+ links; `@nera-static/plugin-sitemap` lists the pairs too. Both use
36
+ `lang` and `slug`.
37
+ 8. Search and tags can keep one index or tag list per language
38
+ (`group_by_lang` in `config/search.yaml` or `config/tags.yaml`).
39
+ 9. `npx nera validate`, then `npx nera build --check`.
40
+
41
+ ## Files touched
42
+
43
+ `pages/<lang>/*.md`, `config/app.yaml`, `config/navigation.yaml`,
44
+ `config/canonical-links.yaml`, `theme/views/layouts/layout.pug`.
45
+
46
+ ## Read next
47
+
48
+ - https://nera.js.org/docs/core-concepts.md
49
+ - https://nera.js.org/tutorials/canonical-links-seo.md
50
+ - https://nera.js.org/tutorials/custom-navigation.md
@@ -0,0 +1,51 @@
1
+ # Recipe: portfolio
2
+
3
+ A home page with a grid of projects, one page per project, large responsive
4
+ images.
5
+
6
+ ## Fast path
7
+
8
+ `npx @nera-static/nera new my-portfolio --starter portfolio` creates a
9
+ portfolio on `@nera-static/theme-business`: project pages with image
10
+ galleries, about, a contact form, navigation, responsive images and a
11
+ sitemap. Read its `AGENTS.md`, then replace the sample projects and images
12
+ and the placeholder `origin: https://example.com` in `config/app.yaml`;
13
+ step 7 below still applies. The steps below build the portfolio by hand
14
+ instead, with different files.
15
+
16
+ ## Steps
17
+
18
+ 1. Scaffold: `npx @nera-static/nera new my-portfolio`, then read its
19
+ `AGENTS.md`.
20
+ 2. Images: put originals in `theme/assets/images/` and set up
21
+ [images](images.md) first, so every photo is served as AVIF/WebP in
22
+ several widths.
23
+ 3. One Markdown file per project in `pages/projects/`, each with `layout`,
24
+ `title`, `description`, `date` and `image: /images/<file>.jpg` (the cover
25
+ picture). Show more photos in the body with
26
+ `![Alt text](/images/<file>.jpg "Caption")`.
27
+ 4. Project list: `npm install @nera-static/plugin-simple-page-list`, set
28
+ `page_path: /projects` in `config/simple-page-list.yaml`, run
29
+ `npx nera-simple-page-list`, and render `app.pageList` on the home page.
30
+ For a grid with cover images, loop over `app.pageList` in your own Pug
31
+ template instead of the published one.
32
+ 5. A project template, `theme/views/pages/project.pug`, extending
33
+ `../layouts/layout`, that shows the cover with the images plugin's
34
+ `+picture` mixin and then `content`, with exactly one `main`.
35
+ 6. Optional: `@nera-static/plugin-tags` to group projects by kind,
36
+ `@nera-static/plugin-page-pagination` for previous/next project,
37
+ `@nera-static/plugin-social-media-links`, `@nera-static/plugin-sitemap`.
38
+ 7. `npx nera validate`, then `npx nera build --check`. The check reports
39
+ images without alt text; describe what each picture shows.
40
+
41
+ ## Files touched
42
+
43
+ `theme/assets/images/`, `pages/projects/*.md`, `pages/index.md`,
44
+ `config/images.yaml` (optional), `config/simple-page-list.yaml`,
45
+ `theme/views/pages/project.pug`, `theme/views/vendor/plugin-*/`,
46
+ `package.json`.
47
+
48
+ ## Read next
49
+
50
+ - https://nera.js.org/docs/writing-content.md
51
+ - https://nera.js.org/docs/plugins.md
@@ -0,0 +1,52 @@
1
+ # Recipe: search
2
+
3
+ Client-side search with `@nera-static/plugin-search`: the build writes a
4
+ JSON index, a small script searches it in the browser. No backend.
5
+
6
+ ## Steps
7
+
8
+ 1. `npm install @nera-static/plugin-search`. It works without config;
9
+ `config/search.yaml` can change the indexed `fields` or set
10
+ `group_by_lang: true` for one index per language.
11
+ 2. `npx nera-search` copies the search template to
12
+ `theme/views/vendor/plugin-search/` and its script to
13
+ `theme/assets/js/search.js`.
14
+ 3. A page template for the search page, `theme/views/pages/search.pug`:
15
+
16
+ ```pug
17
+ extends ../layouts/layout
18
+
19
+ block content
20
+ main
21
+ | !{ content }
22
+ include /vendor/plugin-search/search.pug
23
+ ```
24
+
25
+ 4. `pages/search.md` with `layout: pages/search.pug`, a `title` and a
26
+ `# Search` heading, and `show_title: false` in `config/search.yaml`, so
27
+ that heading is the page's only `h1` (without the key the template adds
28
+ its own and `nera build --check` warns `a11y-h1`). Link the page from
29
+ the menu.
30
+ 5. The template's input is already labelled (`aria-label`, default
31
+ "Search"). To translate the template, add `search_label`, `search_title`
32
+ and `search_placeholder` to the site's translations. A copy published
33
+ before plugin-search 2.3.0 lacks both: refresh it with
34
+ `npx nera-search --force` if it was never edited.
35
+ 6. The index is written to `theme/assets/search-index.json` on every build
36
+ and served as `/search-index.json`. It is generated: add
37
+ `theme/assets/search-index*.json` to `.gitignore`.
38
+ 7. Only pages with a `layout` are indexed. If other plugins add pages (tags),
39
+ run search last with `config/plugin-order.yaml` as the README shows.
40
+ 8. `npx nera validate`, then `npx nera build --check`; try a query with
41
+ `npm run dev`.
42
+
43
+ ## Files touched
44
+
45
+ `package.json`, `config/search.yaml` (optional), `pages/search.md`,
46
+ `theme/views/pages/search.pug`, `theme/views/vendor/plugin-search/`,
47
+ `theme/assets/js/search.js`, `.gitignore`.
48
+
49
+ ## Read next
50
+
51
+ - https://nera.js.org/tutorials/add-search.md
52
+ - Plugin README: https://github.com/seebaermichi/nera-plugin-search
package/src/catalog.js CHANGED
@@ -1,112 +1,47 @@
1
+ import { CatalogError, listCatalog } from '@nera-static/nera'
1
2
  import { z } from 'zod'
2
3
  import { ok, tool, ToolError } from './results.js'
3
4
 
4
- export const REGISTRY_SEARCH = 'https://registry.npmjs.org/-/v1/search'
5
- /** Every official package carries this keyword; not every one carries `nera-<kind>`. */
6
- const OFFICIAL_KEYWORD = 'nera'
7
- const OFFICIAL_SCOPE = '@nera-static/'
8
- /** The most results one registry search returns. */
9
- const SEARCH_SIZE = 250
10
- const TIMEOUT_MS = 10000
11
-
12
5
  /**
13
- * The three catalogs. `prefix` names the official packages of the kind,
14
- * `keyword` finds third-party ones, `usable` keeps only third-party names the
15
- * consuming tool reads back as the same package (a bare unscoped name would be
16
- * read as `@nera-static/<kind>-<name>`).
6
+ * The three catalogs, as the tools and resources present them. The registry
7
+ * search itself is the CLI's `listCatalog` (ROADMAP principle 4).
17
8
  */
18
9
  export const KINDS = {
19
10
  starters: {
20
11
  title: 'starter kits',
21
- prefix: `${OFFICIAL_SCOPE}starter-`,
22
- keyword: 'nera-starter',
23
- exclude: new Set(),
24
- usable: (name) => name.startsWith('@') || /^nera-starter-[a-z0-9][a-z0-9._-]*$/.test(name),
25
12
  next: 'Pass `name` as `starter` to create_site.',
26
13
  },
27
14
  themes: {
28
15
  title: 'themes',
29
- prefix: `${OFFICIAL_SCOPE}theme-`,
30
- keyword: 'nera-theme',
31
- exclude: new Set(),
32
- usable: (name) => name.startsWith('@'),
33
16
  next: 'Pass `name` as `theme` to create_site.',
34
17
  },
35
18
  plugins: {
36
19
  title: 'plugins',
37
- prefix: `${OFFICIAL_SCOPE}plugin-`,
38
- keyword: 'nera-plugin',
39
- exclude: new Set([`${OFFICIAL_SCOPE}plugin-utils`]),
40
- usable: () => true,
41
20
  next: 'Pass `name` of an official plugin to add_plugin.',
42
21
  },
43
22
  }
44
23
 
45
24
  /**
46
- * A failure to reach or read the npm registry. The tools turn it into an
47
- * `isError` result, the resources into a resource error.
48
- */
49
- export class CatalogError extends ToolError {
50
- constructor(message) {
51
- super(message)
52
- this.name = 'CatalogError'
53
- }
54
- }
55
-
56
- async function search(fetch, text) {
57
- const url = `${REGISTRY_SEARCH}?text=${encodeURIComponent(text)}&size=${SEARCH_SIZE}`
58
- let body
59
- try {
60
- const response = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS) })
61
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
62
- body = await response.json()
63
- } catch (error) {
64
- throw new CatalogError(`The npm registry could not be reached (${error.message}), so the catalog is not available. Check the network connection and try again, or use a name you already know (official ones are listed on https://nera.js.org).`)
65
- }
66
- if (!Array.isArray(body?.objects)) {
67
- throw new CatalogError('The npm registry answered with an unexpected search result, so the catalog is not available. Try again later.')
68
- }
69
- return body.objects.map((object) => object?.package).filter((pkg) => typeof pkg?.name === 'string')
70
- }
71
-
72
- function entry(kind, pkg, official) {
73
- return {
74
- name: official ? pkg.name.slice(kind.prefix.length) : pkg.name,
75
- package: pkg.name,
76
- version: typeof pkg.version === 'string' ? pkg.version : null,
77
- description: typeof pkg.description === 'string' ? pkg.description : '',
78
- official,
79
- npm: pkg.links?.npm ?? `https://www.npmjs.com/package/${pkg.name}`,
80
- }
81
- }
82
-
83
- /**
84
- * One catalog from the npm registry: the official `@nera-static/<kind>-*`
85
- * packages (keyword `nera`, which every official package carries, while only
86
- * some carry `nera-<kind>`), then third-party ones (keyword `nera-<kind>`),
87
- * each group sorted by package name and listed once.
25
+ * One catalog, from the CLI's `listCatalog`: official packages first, then
26
+ * third-party ones. Starters fall back to the official starters bundled with
27
+ * the CLI when the registry cannot be reached.
88
28
  *
89
- * @param {typeof fetch} fetch
29
+ * The CLI's `CatalogError` extends `Error`, not our `ToolError`, so it is
30
+ * rethrown as a `ToolError`: the tools turn that into an `isError` result, the
31
+ * resources into an `InvalidParams` error, both with the CLI's message.
32
+ *
33
+ * @param {{ fetch: typeof fetch }} ctx
90
34
  * @param {keyof typeof KINDS} kindName
91
35
  * @returns {Promise<Array<{ name: string, package: string, version: string|null, description: string, official: boolean, npm: string }>>}
92
- * @throws {CatalogError} when the registry cannot be reached or answers oddly
36
+ * @throws {ToolError} when the registry cannot be reached or answers oddly (themes, plugins)
93
37
  */
94
- export async function loadCatalog(fetch, kindName) {
95
- const kind = KINDS[kindName]
96
- const [officialHits, keywordHits] = await Promise.all([
97
- search(fetch, `keywords:${OFFICIAL_KEYWORD}`),
98
- search(fetch, `keywords:${kind.keyword}`),
99
- ])
100
- const official = [...officialHits, ...keywordHits].filter((pkg) => pkg.name.startsWith(kind.prefix) && !kind.exclude.has(pkg.name))
101
- const thirdParty = keywordHits.filter((pkg) => !pkg.name.startsWith(OFFICIAL_SCOPE) && kind.usable(pkg.name))
102
- const byName = new Map()
103
- for (const [group, isOfficial] of [[official, true], [thirdParty, false]]) {
104
- const sorted = [...group].sort((a, b) => a.name.localeCompare(b.name))
105
- for (const pkg of sorted) {
106
- if (!byName.has(pkg.name)) byName.set(pkg.name, entry(kind, pkg, isOfficial))
107
- }
38
+ export async function readCatalog(ctx, kindName) {
39
+ try {
40
+ return await listCatalog(kindName, { fetch: ctx.fetch })
41
+ } catch (error) {
42
+ if (error instanceof CatalogError) throw new ToolError(error.message)
43
+ throw error
108
44
  }
109
- return [...byName.values()]
110
45
  }
111
46
 
112
47
  /**
@@ -117,7 +52,7 @@ export async function loadCatalog(fetch, kindName) {
117
52
  */
118
53
  export function registerCatalogTools(server, ctx) {
119
54
  const descriptions = {
120
- starters: 'Lists the Nera starter kits on npm: ready-to-edit sites with sample pages, a theme and plugins (e.g. `blog`, `business`, `portfolio`, `blank`). Call it before create_site when the user wants a site of a certain kind, and pass the chosen entry\'s `name` as `starter`.',
55
+ starters: 'Lists the Nera starter kits on npm: ready-to-edit sites with sample pages, a theme and plugins (e.g. `blog`, `business`, `portfolio`, `blank`). Call it before create_site when the user wants a site of a certain kind, and pass the chosen entry\'s `name` as `starter`. Without a network connection it lists the official starters only.',
121
56
  themes: 'Lists the Nera themes on npm: the layouts and styles of a site, installable as a package. A starter already brings its theme; use this only for create_site without a starter, and pass the chosen entry\'s `name` as `theme`.',
122
57
  plugins: 'Lists the Nera plugins on npm: features such as navigation, tags, a sitemap, a feed, image resizing, code highlighting or a contact form. Call it when the user wants a feature the site lacks; official plugins (`official: true`) are installed with add_plugin by their `name`.',
123
58
  }
@@ -131,7 +66,7 @@ export function registerCatalogTools(server, ctx) {
131
66
  },
132
67
  annotations: { readOnlyHint: true, openWorldHint: true },
133
68
  }, tool(async ({ query }) => {
134
- const all = await loadCatalog(ctx.fetch, kindName)
69
+ const all = await readCatalog(ctx, kindName)
135
70
  const needle = query?.toLowerCase()
136
71
  const items = needle
137
72
  ? all.filter((item) => `${item.package} ${item.description}`.toLowerCase().includes(needle))
package/src/resources.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs/promises'
2
2
  import { fileURLToPath } from 'node:url'
3
3
  import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'
4
4
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'
5
- import { KINDS, loadCatalog } from './catalog.js'
5
+ import { KINDS, readCatalog } from './catalog.js'
6
6
  import { PathError, resolveInRoot } from './paths.js'
7
7
  import { ToolError } from './results.js'
8
8
  import { findSites, resolveSite } from './tools/sites.js'
@@ -80,7 +80,7 @@ export function registerResources(server, ctx) {
80
80
  description: `The Nera ${KINDS[kindName].title} on npm as JSON, official ones first (the same list as the list_${kindName} tool).`,
81
81
  mimeType: 'application/json',
82
82
  }, resource(async (uri) => {
83
- const items = await loadCatalog(ctx.fetch, kindName)
83
+ const items = await readCatalog(ctx, kindName)
84
84
  return text(uri, 'application/json', JSON.stringify({ [kindName]: items }, null, 2))
85
85
  }))
86
86
  }
package/src/runner.js CHANGED
@@ -2,6 +2,7 @@ import { spawn as nodeSpawn } from 'node:child_process'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { createRequire } from 'node:module'
4
4
  import path from 'node:path'
5
+ import { activeShim, npmScripts, ownNpm, withPathPrefix } from './runtime.js'
5
6
 
6
7
  const require = createRequire(import.meta.url)
7
8
  const NERA_BIN = path.join('node_modules', '@nera-static', 'nera', 'bin', 'nera.js')
@@ -27,22 +28,19 @@ export function neraBin(cwd) {
27
28
  }
28
29
 
29
30
  /**
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.
31
+ * How to start npm without a shell: its `npm-cli.js` from the server's own
32
+ * `node_modules/npm` (the Desktop extension bundles one) or next to the running
33
+ * Node (where every Node installer puts it), else the `npm` executable on the
34
+ * PATH. Running the script through `process.execPath` avoids `npm.cmd` on
35
+ * Windows, which Node refuses to spawn without a shell.
34
36
  *
35
37
  * @param {string} [execPath] the Node binary
38
+ * @param {string|null} [own] the server's own npm package folder
36
39
  * @returns {{ file: string, prefix: string[] }}
37
40
  */
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: [] }
41
+ export function npmCommand(execPath = process.execPath, own = ownNpm()) {
42
+ const scripts = npmScripts(execPath, own)
43
+ return scripts ? { file: execPath, prefix: [scripts.npmCli] } : { file: 'npm', prefix: [] }
46
44
  }
47
45
 
48
46
  /**
@@ -76,26 +74,45 @@ export function capped(text) {
76
74
  return text.length > MAX_CAPTURE ? text.slice(-MAX_CAPTURE) : text
77
75
  }
78
76
 
77
+ /**
78
+ * The environment every child gets: this process's, without colour codes and
79
+ * with `env` added. Under the bundled runtime the shim folder
80
+ * (`src/runtime.js`) comes first on the PATH, so the child and everything it
81
+ * starts find `node`, `npm` and `npx`. Also what `create_site` hands
82
+ * `createSite`, whose children (`npm pack`, `tar`, `npm install`) the runner
83
+ * does not start.
84
+ *
85
+ * @param {Record<string, string>} [env] added to this process's environment
86
+ * @param {NodeJS.Platform} [platform] injected in tests
87
+ * @param {string|null} [shim] the shim folder; the active one by default
88
+ * @returns {Record<string, string|undefined>}
89
+ */
90
+ export function childEnv(env = {}, platform = process.platform, shim = activeShim()) {
91
+ const merged = { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', ...env }
92
+ return shim ? withPathPrefix(merged, shim, platform) : merged
93
+ }
94
+
79
95
  /**
80
96
  * The options every child is spawned with: no shell (arguments are never
81
97
  * 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.
98
+ * piped (none of it reaches this process's stdout), the env of `childEnv`,
99
+ * and — on POSIX — its own process group, so `stopChild` reaches the
100
+ * processes it starts in turn (npm's scripts, Vite's workers). Windows has no
101
+ * process groups to signal; `stopChild` ends the tree with `taskkill /T` there.
86
102
  *
87
103
  * @param {string} cwd
88
104
  * @param {Record<string, string>} [env] added to this process's environment
89
105
  * @param {NodeJS.Platform} [platform] injected in tests
106
+ * @param {string|null} [shim] the shim folder; the active one by default
90
107
  * @returns {import('node:child_process').SpawnOptions}
91
108
  */
92
- export function spawnOptions(cwd, env = {}, platform = process.platform) {
109
+ export function spawnOptions(cwd, env = {}, platform = process.platform, shim = activeShim()) {
93
110
  return {
94
111
  cwd,
95
112
  stdio: ['ignore', 'pipe', 'pipe'],
96
113
  shell: false,
97
114
  detached: platform !== 'win32',
98
- env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', ...env },
115
+ env: childEnv(env, platform, shim),
99
116
  }
100
117
  }
101
118
 
package/src/runtime.js ADDED
@@ -0,0 +1,213 @@
1
+ // The bundled runtime of the Claude Desktop extension: Claude Desktop runs the
2
+ // server on the Node it ships, which comes without npm and puts nothing on the
3
+ // PATH. Every child (`createSite`'s `npm pack` and `npm install`, `nera dev`
4
+ // → Vite's `#!/usr/bin/env node` scripts, npm's lifecycle scripts) looks
5
+ // `node`, `npm` and `npx` up on the PATH, so under `NERA_MCP_RUNTIME=bundled`
6
+ // the bin writes a shim folder for the three and every child gets it first on
7
+ // its PATH (`childEnv` in `src/runner.js`).
8
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { createRequire } from 'node:module'
10
+ import os from 'node:os'
11
+ import path from 'node:path'
12
+
13
+ const require = createRequire(import.meta.url)
14
+
15
+ /** The environment variable that switches the bundled runtime on. */
16
+ export const RUNTIME_ENV = 'NERA_MCP_RUNTIME'
17
+ /** Its one value that does; any other leaves children as they were. */
18
+ export const BUNDLED = 'bundled'
19
+
20
+ /**
21
+ * The `npm` package folder this server can load itself: the one the
22
+ * Desktop extension bundles in its `node_modules`, or null when there is none
23
+ * (an ordinary install from npm brings none). Only `node_modules` folders
24
+ * count, not Node's legacy global folders (`~/.node_modules`, `$PREFIX/lib/node`).
25
+ *
26
+ * @returns {string|null}
27
+ */
28
+ export function ownNpm() {
29
+ const folders = (require.resolve.paths('npm') || []).filter((folder) => path.basename(folder) === 'node_modules')
30
+ const found = folders.find((folder) => existsSync(path.join(folder, 'npm', 'bin', 'npm-cli.js')))
31
+ return found ? path.join(found, 'npm') : null
32
+ }
33
+
34
+ /**
35
+ * Where npm's two entry scripts are: in the server's own `node_modules/npm`
36
+ * first (the bundled one), else next to the Node binary, where every Node
37
+ * installer puts npm (`lib/node_modules/npm` on POSIX, `node_modules/npm` on
38
+ * Windows). Null when neither has it.
39
+ *
40
+ * @param {string} [execPath] the Node binary
41
+ * @param {string|null} [own] the server's own npm package folder
42
+ * @returns {{ npmCli: string, npxCli: string }|null}
43
+ */
44
+ export function npmScripts(execPath = process.execPath, own = ownNpm()) {
45
+ const bin = path.dirname(execPath)
46
+ const folders = [
47
+ own,
48
+ path.join(bin, '..', 'lib', 'node_modules', 'npm'),
49
+ path.join(bin, 'node_modules', 'npm'),
50
+ ].filter(Boolean)
51
+ const folder = folders.find((candidate) => existsSync(path.join(candidate, 'bin', 'npm-cli.js')))
52
+ if (!folder) return null
53
+ return {
54
+ npmCli: path.join(folder, 'bin', 'npm-cli.js'),
55
+ npxCli: path.join(folder, 'bin', 'npx-cli.js'),
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Quotes a path for a POSIX `sh` script: in single quotes, where nothing is
61
+ * expanded, with each `'` closed, escaped and reopened.
62
+ *
63
+ * @param {string} value
64
+ * @returns {string}
65
+ */
66
+ function shQuote(value) {
67
+ return `'${value.replaceAll('\'', '\'\\\'\'')}'`
68
+ }
69
+
70
+ /**
71
+ * Quotes a path for a Windows `.cmd` script: in double quotes (a Windows path
72
+ * cannot contain one), with `%` doubled so cmd does not expand it as a
73
+ * variable.
74
+ *
75
+ * @param {string} value
76
+ * @returns {string}
77
+ */
78
+ function cmdQuote(value) {
79
+ return `"${value.replaceAll('%', '%%')}"`
80
+ }
81
+
82
+ /**
83
+ * The shim scripts for a platform: file name → content. Each one runs its
84
+ * target with the Node binary and passes every argument on unchanged (`"$@"`
85
+ * in `sh`, `%*` in `cmd`). `npm` and `npx` are left out when no npm was found.
86
+ *
87
+ * @param {object} options
88
+ * @param {string} options.execPath the Node binary the children run on
89
+ * @param {{ npmCli: string, npxCli: string }|null} options.npm
90
+ * @param {NodeJS.Platform} options.platform
91
+ * @returns {Record<string, string>}
92
+ */
93
+ export function shimScripts({ execPath, npm, platform }) {
94
+ const targets = { node: [execPath] }
95
+ if (npm) {
96
+ targets.npm = [execPath, npm.npmCli]
97
+ targets.npx = [execPath, npm.npxCli]
98
+ }
99
+ const scripts = {}
100
+ for (const [name, command] of Object.entries(targets)) {
101
+ if (platform === 'win32') {
102
+ scripts[`${name}.cmd`] = `@echo off\r\n${command.map(cmdQuote).join(' ')} %*\r\n`
103
+ } else {
104
+ scripts[name] = `#!/bin/sh\nexec ${command.map(shQuote).join(' ')} "$@"\n`
105
+ }
106
+ }
107
+ return scripts
108
+ }
109
+
110
+ /**
111
+ * Writes the shim folder: a fresh temp folder (never inside a site or the
112
+ * root) holding the scripts of `shimScripts`, executable on POSIX.
113
+ *
114
+ * @param {object} [options]
115
+ * @param {string} [options.execPath]
116
+ * @param {{ npmCli: string, npxCli: string }|null} [options.npm]
117
+ * @param {NodeJS.Platform} [options.platform]
118
+ * @param {string} [options.parent] the folder the shim folder is created in
119
+ * @returns {{ dir: string, npm: boolean, remove: () => void }} `remove` deletes the folder, and may be called more than once
120
+ */
121
+ export function writeShim({
122
+ execPath = process.execPath,
123
+ npm = npmScripts(execPath),
124
+ platform = process.platform,
125
+ parent = os.tmpdir(),
126
+ } = {}) {
127
+ const dir = mkdtempSync(path.join(parent, 'nera-mcp-runtime-'))
128
+ for (const [name, content] of Object.entries(shimScripts({ execPath, npm, platform }))) {
129
+ writeFileSync(path.join(dir, name), content, { mode: 0o755 })
130
+ }
131
+ return {
132
+ dir,
133
+ npm: Boolean(npm),
134
+ remove: () => rmSync(dir, { recursive: true, force: true }),
135
+ }
136
+ }
137
+
138
+ /**
139
+ * The name of the PATH variable in `env`. On Windows the name is
140
+ * case-insensitive and is usually `Path`; an env object spread from
141
+ * `process.env` keeps that spelling, so it is looked up rather than assumed.
142
+ *
143
+ * @param {Record<string, string|undefined>} env
144
+ * @param {NodeJS.Platform} platform
145
+ * @returns {string}
146
+ */
147
+ export function pathKey(env, platform = process.platform) {
148
+ if (platform !== 'win32') return 'PATH'
149
+ return Object.keys(env).find((key) => key.toUpperCase() === 'PATH') || 'Path'
150
+ }
151
+
152
+ /**
153
+ * A copy of `env` with `dir` first on its PATH. On Windows every spelling of
154
+ * the variable is folded into one, so the child does not get two that
155
+ * disagree.
156
+ *
157
+ * @param {Record<string, string|undefined>} env
158
+ * @param {string} dir
159
+ * @param {NodeJS.Platform} [platform]
160
+ * @returns {Record<string, string|undefined>}
161
+ */
162
+ export function withPathPrefix(env, dir, platform = process.platform) {
163
+ const key = pathKey(env, platform)
164
+ const delimiter = platform === 'win32' ? ';' : ':'
165
+ const result = { ...env }
166
+ if (platform === 'win32') {
167
+ for (const name of Object.keys(result)) {
168
+ if (name.toUpperCase() === 'PATH') delete result[name]
169
+ }
170
+ }
171
+ result[key] = env[key] ? `${dir}${delimiter}${env[key]}` : dir
172
+ return result
173
+ }
174
+
175
+ /** @type {string|null} */
176
+ let activeDir = null
177
+
178
+ /**
179
+ * Makes `dir` the shim folder every child is spawned with (`spawnOptions`);
180
+ * null switches that off again.
181
+ *
182
+ * @param {string|null} dir
183
+ */
184
+ export function activateShim(dir) {
185
+ activeDir = dir
186
+ }
187
+
188
+ /**
189
+ * The shim folder in use, or null when children get the PATH unchanged.
190
+ *
191
+ * @returns {string|null}
192
+ */
193
+ export function activeShim() {
194
+ return activeDir
195
+ }
196
+
197
+ /**
198
+ * What the bin calls at start: under `NERA_MCP_RUNTIME=bundled` it writes the
199
+ * shim folder and activates it; otherwise it does nothing. The env it reads is
200
+ * never changed: the shim reaches every child through `childEnv`, also the
201
+ * ones `createSite` starts in-process (it takes that env).
202
+ *
203
+ * @param {object} [options]
204
+ * @param {Record<string, string|undefined>} [options.env] read for the switch only
205
+ * @param {Parameters<typeof writeShim>[0]} [options.shim] passed to `writeShim` (tests)
206
+ * @returns {ReturnType<typeof writeShim>|null} the shim, whose `remove` the bin calls on exit
207
+ */
208
+ export function setupRuntime({ env = process.env, shim } = {}) {
209
+ if (env[RUNTIME_ENV] !== BUNDLED) return null
210
+ const written = writeShim(shim)
211
+ activateShim(written.dir)
212
+ return written
213
+ }
package/src/server.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
2
+ import { createSite as neraCreateSite } from '@nera-static/nera'
2
3
  import pkg from '../package.json' with { type: 'json' }
3
4
  import { registerCatalogTools } from './catalog.js'
4
5
  import { realRoot } from './paths.js'
@@ -19,6 +20,7 @@ import { registerSiteTools } from './tools/sites.js'
19
20
  * @param {object} options
20
21
  * @param {string} options.root the folder the server may work in; every path a tool takes is checked against it
21
22
  * @param {ReturnType<typeof createRunner>} [options.runner] runs the `nera`, `npm` and `node` commands (injected so tests spawn nothing)
23
+ * @param {typeof neraCreateSite} [options.createSite] writes a new site's files for `create_site` (the CLI's `createSite`; injected so tests need no network for package and GitHub starters)
22
24
  * @param {typeof fetch} [options.fetch] fetches the npm registry catalogs (injected so tests stay offline)
23
25
  * @param {string} [options.docsFile] the bundled `llms-full.txt` (default: the package's `docs/`; injected so tests can point at a missing one)
24
26
  * @param {ReturnType<typeof createProcesses>} [options.processes] tracks the children that outlive a call (`preview`, `publish`); all are stopped when the server closes
@@ -26,8 +28,8 @@ import { registerSiteTools } from './tools/sites.js'
26
28
  * @returns {Promise<McpServer>}
27
29
  * @throws {import('./paths.js').PathError} when `root` does not exist or is not a folder
28
30
  */
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
+ export async function createServer({ root, runner = createRunner(), createSite = neraCreateSite, fetch = globalThis.fetch, docsFile, processes = createProcesses(), timing }) {
32
+ const ctx = { root: await realRoot(root), runner, createSite, fetch, docsFile, processes, timing }
31
33
  const server = new McpServer(
32
34
  { name: pkg.name, version: pkg.version },
33
35
  {