@nera-static/mcp 1.3.0 → 1.4.1
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 +42 -0
- package/README.md +58 -1
- package/bin/nera-mcp.js +211 -63
- package/docs/llms-full.txt +2336 -179
- package/package.json +31 -18
- package/skills/nera/SKILL.md +3 -0
- package/skills/nera/recipes/blog.md +9 -5
- package/src/catalog.js +1 -1
- package/src/hosted/app.js +131 -0
- package/src/hosted/checkout.js +417 -0
- package/src/hosted/config.js +93 -0
- package/src/hosted/consent.js +146 -0
- package/src/hosted/crypto.js +91 -0
- package/src/hosted/github.js +160 -0
- package/src/hosted/mcp.js +62 -0
- package/src/hosted/provider.js +376 -0
- package/src/hosted/repo.js +489 -0
- package/src/hosted/store.js +490 -0
- package/src/hosted/tools/publish.js +192 -0
- package/src/hosted/tools/read.js +351 -0
- package/src/hosted/tools/validate.js +51 -0
- package/src/hosted/tools/write.js +201 -0
- package/src/pages.js +171 -0
- package/src/paths.js +11 -18
- package/src/prompts.js +80 -10
- package/src/resources.js +22 -6
- package/src/runner.js +27 -17
- package/src/server-info.js +11 -0
- package/src/server.js +14 -4
- package/src/tools/cli.js +47 -23
- package/src/tools/files.js +19 -111
- package/src/tools/long-running.js +14 -33
- package/src/tools/sites.js +39 -13
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// The hosted mode's secrets (L7b): our own tokens are random and stored only as
|
|
2
|
+
// SHA-256 hashes, so a leaked database cannot be replayed; GitHub's user tokens
|
|
3
|
+
// must be read back to call the API, so they are encrypted with AES-256-GCM
|
|
4
|
+
// under the operator's key (`NERA_MCP_TOKEN_KEY`). Nothing here logs a value.
|
|
5
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
|
|
6
|
+
|
|
7
|
+
const ALGORITHM = 'aes-256-gcm'
|
|
8
|
+
const KEY_BYTES = 32
|
|
9
|
+
const IV_BYTES = 12
|
|
10
|
+
const TAG_BYTES = 16
|
|
11
|
+
/** The prefix of every encrypted value, so a later format can be told apart. */
|
|
12
|
+
const VERSION = 'v1'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Turns the operator's key into the 32 bytes AES-256 needs. Accepted: 64 hex
|
|
16
|
+
* characters or the base64 of 32 bytes (`openssl rand -base64 32`).
|
|
17
|
+
*
|
|
18
|
+
* @param {string|Buffer} input
|
|
19
|
+
* @returns {Buffer}
|
|
20
|
+
*/
|
|
21
|
+
export function parseKey(input) {
|
|
22
|
+
if (Buffer.isBuffer(input)) {
|
|
23
|
+
if (input.length === KEY_BYTES) return Buffer.from(input)
|
|
24
|
+
} else if (typeof input === 'string') {
|
|
25
|
+
const text = input.trim()
|
|
26
|
+
if (/^[0-9a-fA-F]{64}$/.test(text)) return Buffer.from(text, 'hex')
|
|
27
|
+
if (/^[A-Za-z0-9+/_-]{43}=?$/.test(text)) {
|
|
28
|
+
const bytes = Buffer.from(text, 'base64')
|
|
29
|
+
if (bytes.length === KEY_BYTES) return bytes
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
throw new Error(`The token key must be ${KEY_BYTES} bytes, written as 64 hex characters or base64 (create one ` +
|
|
33
|
+
'with `openssl rand -base64 32`).')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Encrypts a string with a fresh random IV per call.
|
|
38
|
+
*
|
|
39
|
+
* @param {Buffer} key 32 bytes, from `parseKey`
|
|
40
|
+
* @param {string} plaintext
|
|
41
|
+
* @returns {string} `v1.<iv>.<tag>.<ciphertext>`, each part base64url
|
|
42
|
+
*/
|
|
43
|
+
export function encrypt(key, plaintext) {
|
|
44
|
+
const iv = randomBytes(IV_BYTES)
|
|
45
|
+
const cipher = createCipheriv(ALGORITHM, key, iv)
|
|
46
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
|
|
47
|
+
const tag = cipher.getAuthTag()
|
|
48
|
+
return [VERSION, iv, tag, ciphertext].map((part) => (typeof part === 'string' ? part : part.toString('base64url'))).join('.')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Decrypts what `encrypt` wrote. Throws when the key is wrong or the value was
|
|
53
|
+
* altered (the GCM auth tag does not match), never returns garbage.
|
|
54
|
+
*
|
|
55
|
+
* @param {Buffer} key
|
|
56
|
+
* @param {string} blob
|
|
57
|
+
* @returns {string}
|
|
58
|
+
*/
|
|
59
|
+
export function decrypt(key, blob) {
|
|
60
|
+
const parts = String(blob).split('.')
|
|
61
|
+
if (parts.length !== 4 || parts[0] !== VERSION) throw new Error('Not an encrypted value of a known format.')
|
|
62
|
+
const [iv, tag, ciphertext] = parts.slice(1).map((part) => Buffer.from(part, 'base64url'))
|
|
63
|
+
if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) throw new Error('Not an encrypted value of a known format.')
|
|
64
|
+
const decipher = createDecipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES })
|
|
65
|
+
decipher.setAuthTag(tag)
|
|
66
|
+
try {
|
|
67
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8')
|
|
68
|
+
} catch {
|
|
69
|
+
throw new Error('Cannot decrypt a stored token: the token key differs from the one it was written with, or the value was altered.')
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The SHA-256 of a token, hex: how our tokens are stored and looked up.
|
|
75
|
+
*
|
|
76
|
+
* @param {string} token
|
|
77
|
+
* @returns {string}
|
|
78
|
+
*/
|
|
79
|
+
export function hashToken(token) {
|
|
80
|
+
return createHash('sha256').update(String(token), 'utf8').digest('hex')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A random, URL-safe token.
|
|
85
|
+
*
|
|
86
|
+
* @param {number} [bytes] entropy in bytes (default 32 = 256 bits)
|
|
87
|
+
* @returns {string}
|
|
88
|
+
*/
|
|
89
|
+
export function randomToken(bytes = 32) {
|
|
90
|
+
return randomBytes(bytes).toString('base64url')
|
|
91
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// The GitHub side of the hosted mode's login (L7b): the web flow of
|
|
2
|
+
// the GitHub App "Nera Static". Our `/authorize` sends the user to GitHub,
|
|
3
|
+
// GitHub sends them back to our callback with a code, and this client turns
|
|
4
|
+
// that code into a user token and reads who the user is. GitHub App user tokens
|
|
5
|
+
// expire (8 h) and come with a refresh token (6 months) that GitHub rotates on
|
|
6
|
+
// every use. Every call goes through the injected `fetch`, so tests never touch
|
|
7
|
+
// the network; no token ever appears in an error message.
|
|
8
|
+
|
|
9
|
+
const USER_AGENT = 'nera-mcp'
|
|
10
|
+
const API_VERSION = '2022-11-28'
|
|
11
|
+
|
|
12
|
+
/** A failed call to GitHub; `code` is GitHub's own error code when it sent one. */
|
|
13
|
+
export class GitHubError extends Error {
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} message
|
|
16
|
+
* @param {{code?: string, status?: number}} [details]
|
|
17
|
+
*/
|
|
18
|
+
constructor(message, { code, status } = {}) {
|
|
19
|
+
super(message)
|
|
20
|
+
this.name = 'GitHubError'
|
|
21
|
+
this.code = code
|
|
22
|
+
this.status = status
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {object} GitHubTokens a user token as we keep it; times in seconds since the epoch
|
|
28
|
+
* @property {string} accessToken
|
|
29
|
+
* @property {number} [accessTokenExpiresAt] absent when the App issues non-expiring tokens
|
|
30
|
+
* @property {string} [refreshToken]
|
|
31
|
+
* @property {number} [refreshTokenExpiresAt]
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Creates the GitHub web-flow client.
|
|
36
|
+
*
|
|
37
|
+
* @param {object} options
|
|
38
|
+
* @param {string} options.clientId the GitHub App's client ID
|
|
39
|
+
* @param {string} options.clientSecret the GitHub App's client secret
|
|
40
|
+
* @param {string} options.redirectUri our callback, as registered in the App
|
|
41
|
+
* @param {typeof fetch} [options.fetch]
|
|
42
|
+
* @param {string} [options.webUrl] `https://github.com`, overridable for tests
|
|
43
|
+
* @param {string} [options.apiUrl] `https://api.github.com`, overridable for tests
|
|
44
|
+
* @param {() => number} [options.now] the clock in milliseconds
|
|
45
|
+
*/
|
|
46
|
+
export function createGitHubClient({
|
|
47
|
+
clientId,
|
|
48
|
+
clientSecret,
|
|
49
|
+
redirectUri,
|
|
50
|
+
fetch = globalThis.fetch,
|
|
51
|
+
webUrl = 'https://github.com',
|
|
52
|
+
apiUrl = 'https://api.github.com',
|
|
53
|
+
now = Date.now,
|
|
54
|
+
}) {
|
|
55
|
+
if (!clientId || !clientSecret || !redirectUri) {
|
|
56
|
+
throw new Error('The GitHub client needs the App\'s client ID, its client secret and our callback URL.')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const seconds = () => Math.floor(now() / 1000)
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* POSTs to GitHub's token endpoint. GitHub answers errors there with
|
|
63
|
+
* HTTP 200 and an `error` field, so both cases are checked.
|
|
64
|
+
*
|
|
65
|
+
* @param {Record<string, string>} fields
|
|
66
|
+
* @returns {Promise<GitHubTokens>}
|
|
67
|
+
*/
|
|
68
|
+
async function tokenRequest(fields) {
|
|
69
|
+
const issuedAt = seconds()
|
|
70
|
+
let response
|
|
71
|
+
try {
|
|
72
|
+
response = await fetch(new URL('/login/oauth/access_token', webUrl), {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': USER_AGENT },
|
|
75
|
+
body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, ...fields }),
|
|
76
|
+
})
|
|
77
|
+
} catch (error) {
|
|
78
|
+
throw new GitHubError(`Cannot reach GitHub: ${error.message}`)
|
|
79
|
+
}
|
|
80
|
+
const body = await response.json().catch(() => ({}))
|
|
81
|
+
if (!response.ok || body.error || !body.access_token) {
|
|
82
|
+
const code = body.error || undefined
|
|
83
|
+
const reason = body.error_description || code || `HTTP ${response.status}`
|
|
84
|
+
throw new GitHubError(`GitHub refused the token request: ${reason}`, { code, status: response.status })
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
accessToken: body.access_token,
|
|
88
|
+
accessTokenExpiresAt: body.expires_in ? issuedAt + Number(body.expires_in) : undefined,
|
|
89
|
+
refreshToken: body.refresh_token || undefined,
|
|
90
|
+
refreshTokenExpiresAt: body.refresh_token_expires_in
|
|
91
|
+
? issuedAt + Number(body.refresh_token_expires_in)
|
|
92
|
+
: undefined,
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
/**
|
|
98
|
+
* Where to send the user to sign in.
|
|
99
|
+
*
|
|
100
|
+
* @param {string} state our own state, which GitHub hands back to the callback
|
|
101
|
+
* @returns {string}
|
|
102
|
+
*/
|
|
103
|
+
authorizeUrl(state) {
|
|
104
|
+
const url = new URL('/login/oauth/authorize', webUrl)
|
|
105
|
+
url.searchParams.set('client_id', clientId)
|
|
106
|
+
url.searchParams.set('redirect_uri', redirectUri)
|
|
107
|
+
url.searchParams.set('state', state)
|
|
108
|
+
return url.href
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Exchanges the code GitHub sent to our callback for a user token.
|
|
113
|
+
*
|
|
114
|
+
* @param {string} code
|
|
115
|
+
* @returns {Promise<GitHubTokens>}
|
|
116
|
+
*/
|
|
117
|
+
exchangeCode(code) {
|
|
118
|
+
return tokenRequest({ code, redirect_uri: redirectUri })
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Trades a refresh token for a new user token (and a new refresh token:
|
|
123
|
+
* GitHub invalidates the old one).
|
|
124
|
+
*
|
|
125
|
+
* @param {string} refreshToken
|
|
126
|
+
* @returns {Promise<GitHubTokens>}
|
|
127
|
+
*/
|
|
128
|
+
refresh(refreshToken) {
|
|
129
|
+
return tokenRequest({ grant_type: 'refresh_token', refresh_token: refreshToken })
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Reads the signed-in user.
|
|
134
|
+
*
|
|
135
|
+
* @param {string} accessToken
|
|
136
|
+
* @returns {Promise<{id: string, login: string}>}
|
|
137
|
+
*/
|
|
138
|
+
async getUser(accessToken) {
|
|
139
|
+
let response
|
|
140
|
+
try {
|
|
141
|
+
response = await fetch(new URL('/user', apiUrl), {
|
|
142
|
+
headers: {
|
|
143
|
+
Accept: 'application/vnd.github+json',
|
|
144
|
+
Authorization: `Bearer ${accessToken}`,
|
|
145
|
+
'User-Agent': USER_AGENT,
|
|
146
|
+
'X-GitHub-Api-Version': API_VERSION,
|
|
147
|
+
},
|
|
148
|
+
})
|
|
149
|
+
} catch (error) {
|
|
150
|
+
throw new GitHubError(`Cannot reach GitHub: ${error.message}`)
|
|
151
|
+
}
|
|
152
|
+
const body = await response.json().catch(() => ({}))
|
|
153
|
+
if (!response.ok || body.id === undefined || !body.login) {
|
|
154
|
+
throw new GitHubError('GitHub did not return the signed-in user ' +
|
|
155
|
+
`(HTTP ${response.status}).`, { status: response.status })
|
|
156
|
+
}
|
|
157
|
+
return { id: String(body.id), login: body.login }
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// The MCP server of the hosted mode (L7b). It has no folder to
|
|
2
|
+
// work in: the catalogs of starters, themes and plugins and the docs
|
|
3
|
+
// resource need none, and the site tools work on the signed-in user's GitHub
|
|
4
|
+
// repositories through the repository client (src/hosted/repo.js). The app
|
|
5
|
+
// (src/hosted/app.js) builds one per `/mcp` request, bound to the user its
|
|
6
|
+
// bearer token belongs to.
|
|
7
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
|
8
|
+
import { registerCatalogTools } from '../catalog.js'
|
|
9
|
+
import { registerHostedPrompts } from '../prompts.js'
|
|
10
|
+
import { registerDocsResources } from '../resources.js'
|
|
11
|
+
import { SERVER_INFO } from '../server-info.js'
|
|
12
|
+
import { sharedCheckouts } from './checkout.js'
|
|
13
|
+
import { createRepoClient } from './repo.js'
|
|
14
|
+
import { registerHostedPublishTools } from './tools/publish.js'
|
|
15
|
+
import { registerHostedReadTools } from './tools/read.js'
|
|
16
|
+
import { registerHostedValidateTool } from './tools/validate.js'
|
|
17
|
+
import { registerHostedWriteTools } from './tools/write.js'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Builds the hosted MCP server, with no transport attached. Without a user
|
|
21
|
+
* (`userId` and `githubToken`) it offers the catalog tools and the docs and
|
|
22
|
+
* catalog resources only; with one also the site tools and the hosted prompts.
|
|
23
|
+
*
|
|
24
|
+
* @param {object} [options]
|
|
25
|
+
* @param {typeof fetch} [options.fetch] fetches the npm registry catalogs (injected so tests stay offline)
|
|
26
|
+
* @param {string} [options.userId] the signed-in user, from the bearer token's `extra`
|
|
27
|
+
* @param {(userId: string) => Promise<string>} [options.githubToken] the user's GitHub token (`provider.githubToken`); throws `SignInRequiredError` when the sign-in is gone
|
|
28
|
+
* @param {(token: string) => ReturnType<typeof createRepoClient>} [options.createRepo] builds the repository client (injected so tests talk to a fake GitHub)
|
|
29
|
+
* @param {ReturnType<typeof import('./checkout.js').createCheckouts>} [options.checkouts] the temporary checkouts of `validate`; the process-wide ones by default, since this server lives for one request only
|
|
30
|
+
* @param {(ms: number) => Promise<void>} [options.sleep] the pause between `publish`'s lookups of the deploy run (injected so tests do not wait)
|
|
31
|
+
* @param {string} [options.docsFile] the docs the `nera://docs/llms-full.txt` resource serves; the bundled file by default
|
|
32
|
+
* @returns {McpServer}
|
|
33
|
+
*/
|
|
34
|
+
export function createHostedServer({
|
|
35
|
+
fetch = globalThis.fetch,
|
|
36
|
+
userId,
|
|
37
|
+
githubToken,
|
|
38
|
+
createRepo = (token) => createRepoClient({ token }),
|
|
39
|
+
checkouts = sharedCheckouts,
|
|
40
|
+
sleep,
|
|
41
|
+
docsFile,
|
|
42
|
+
} = {}) {
|
|
43
|
+
const server = new McpServer(
|
|
44
|
+
{ ...SERVER_INFO },
|
|
45
|
+
{
|
|
46
|
+
instructions: 'Tools for Nera, a static site generator: a site is Markdown pages rendered through Pug layouts into plain HTML. This hosted server works on your Nera sites in GitHub repositories: list_sites finds them, get_site describes one, read_page and read_file read its files, write_page, write_file and delete_page change them as one commit each on the draft branch nera-draft, which goes live only with publish, validate checks the draft, publish merges the draft into main so the site\'s GitHub Actions workflow builds and deploys it once, and preview shows the live address and how the last deploy went. It also lists the Nera starter kits, themes and plugins. The full documentation is the resource nera://docs/llms-full.txt (online at https://nera.js.org/llms-full.txt).',
|
|
47
|
+
},
|
|
48
|
+
)
|
|
49
|
+
registerCatalogTools(server, { fetch })
|
|
50
|
+
registerDocsResources(server, { fetch, docsFile })
|
|
51
|
+
if (userId && githubToken) {
|
|
52
|
+
// The token is fetched per tool call, so a refreshed one is used and a
|
|
53
|
+
// lost sign-in becomes that call's error, not the request's.
|
|
54
|
+
const repos = async () => createRepo(await githubToken(userId))
|
|
55
|
+
registerHostedReadTools(server, { repos })
|
|
56
|
+
registerHostedWriteTools(server, { repos })
|
|
57
|
+
registerHostedValidateTool(server, { repos, userId, checkouts })
|
|
58
|
+
registerHostedPublishTools(server, { repos, sleep })
|
|
59
|
+
registerHostedPrompts(server)
|
|
60
|
+
}
|
|
61
|
+
return server
|
|
62
|
+
}
|