@mindbricks/genesis-set 0.0.0-stage → 0.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.
- package/CHANGELOG.md +44 -0
- package/LICENSE +202 -0
- package/README.md +148 -2
- package/bin/genesis-set.mjs +153 -0
- package/corpus/README.md +25 -0
- package/corpus/genesis/compile-results.md +246 -0
- package/corpus/genesis/compiler-api.md +265 -0
- package/corpus/genesis/custom-code.md +519 -0
- package/corpus/genesis/deploy.md +190 -0
- package/corpus/genesis/pitfalls.md +231 -0
- package/corpus/genesis/procedures/README.md +17 -0
- package/corpus/genesis/procedures/agent-hub-blueprint.md +13 -0
- package/corpus/genesis/procedures/auth-blueprint.md +14 -0
- package/corpus/genesis/procedures/bff-blueprint.md +16 -0
- package/corpus/genesis/procedures/blueprint-authoring.md +16 -0
- package/corpus/genesis/procedures/howto-mail-to-tasks.md +26 -0
- package/corpus/genesis/procedures/howto-payment-flow.md +112 -0
- package/corpus/genesis/procedures/howto-subscription.md +33 -0
- package/corpus/genesis/procedures/notifications-blueprint.md +13 -0
- package/corpus/genesis/procedures/patterns-catalog.md +12 -0
- package/corpus/genesis/procedures/project-lifecycle.md +27 -0
- package/corpus/genesis/run-locally.md +310 -0
- package/corpus/genesis/testing.md +532 -0
- package/lib/config-cli.mjs +179 -0
- package/lib/install.mjs +639 -0
- package/lib/mcp-config.mjs +222 -0
- package/lib/semver.mjs +94 -0
- package/mcp/blueprint.mjs +64 -0
- package/mcp/client.mjs +141 -0
- package/mcp/config.mjs +166 -0
- package/mcp/key-page-html.mjs +275 -0
- package/mcp/key-page.mjs +217 -0
- package/mcp/key-store.mjs +204 -0
- package/mcp/key-tools.mjs +225 -0
- package/mcp/server.mjs +164 -0
- package/mcp/tools.mjs +270 -0
- package/package.json +44 -4
- package/skills/genesis-compiler-api/SKILL.md +56 -0
- package/skills/genesis-deploy/SKILL.md +36 -0
- package/skills/genesis-generated-code/SKILL.md +48 -0
- package/skills/genesis-run-and-test/SKILL.md +43 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// The local key store of genesis-set (#9352): the keys a coding agent needs (the
|
|
2
|
+
// Genesis API key, provider keys for the generated services), kept in the
|
|
3
|
+
// genesis config file (<data>/config.json, mode 0600) next to the API key.
|
|
4
|
+
//
|
|
5
|
+
// apiKey the Genesis API key; shown as the built-in key
|
|
6
|
+
// "genesis-api-key"
|
|
7
|
+
// keys.<name> { label, description, value?, createdAt, updatedAt }
|
|
8
|
+
//
|
|
9
|
+
// The agent registers a key by name with a readable label and a description;
|
|
10
|
+
// the user enters the value on the local key page (./key-page.mjs). Nothing in
|
|
11
|
+
// this module returns a value to the agent: `listKeys` answers set / empty and
|
|
12
|
+
// the last four characters for the page, and `keyValue` is for the code that
|
|
13
|
+
// uses a key (writing a gitignored env file), never for a tool answer.
|
|
14
|
+
|
|
15
|
+
import { API_KEY_ENV, configPathOf, readConfigFile, writeConfigFile } from './config.mjs';
|
|
16
|
+
|
|
17
|
+
export const BUILTIN_KEY = 'genesis-api-key';
|
|
18
|
+
const BUILTIN_LABEL = 'Genesis API key';
|
|
19
|
+
const BUILTIN_DESCRIPTION =
|
|
20
|
+
'Authenticates the genesis_* tools with the Genesis Compiler API. Create it on the Genesis portal (API keys page); it is shown once.';
|
|
21
|
+
|
|
22
|
+
/** A key name: lowercase kebab-case, 2 to 64 characters, starting with a letter. */
|
|
23
|
+
export const KEY_NAME_PATTERN = /^[a-z][a-z0-9-]{1,63}$/;
|
|
24
|
+
const MAX_LABEL = 80;
|
|
25
|
+
const MAX_DESCRIPTION = 500;
|
|
26
|
+
const MAX_VALUE = 16 * 1024;
|
|
27
|
+
|
|
28
|
+
/** A refusal the tools and the page turn into a Genesis error. */
|
|
29
|
+
export class KeyStoreError extends Error {
|
|
30
|
+
constructor(code, message, status = 400) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.status = status;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function now() {
|
|
38
|
+
return new Date().toISOString();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function load(env) {
|
|
42
|
+
const file = configPathOf(env);
|
|
43
|
+
const cfg = readConfigFile(file);
|
|
44
|
+
if (cfg.__error) throw new KeyStoreError('GENESIS_KEY_STORE_UNREADABLE', `${cfg.__error}; fix or delete it first`, 500);
|
|
45
|
+
const keys = cfg.keys && typeof cfg.keys === 'object' && !Array.isArray(cfg.keys) ? { ...cfg.keys } : {};
|
|
46
|
+
return { file, cfg, keys };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function save({ file, cfg, keys }) {
|
|
50
|
+
const next = { ...cfg, keys };
|
|
51
|
+
if (Object.keys(keys).length === 0) delete next.keys;
|
|
52
|
+
for (const [k, v] of Object.entries(next)) if (v === undefined) delete next[k];
|
|
53
|
+
writeConfigFile(file, next);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function cleanText(v, max, what) {
|
|
57
|
+
if (v === undefined || v === null) return undefined;
|
|
58
|
+
if (typeof v !== 'string') throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', `${what} must be a string`);
|
|
59
|
+
const t = v.replace(/\s+/g, ' ').trim();
|
|
60
|
+
if (t.length > max) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', `${what} is longer than ${max} characters`);
|
|
61
|
+
return t;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function checkKeyName(name) {
|
|
65
|
+
if (typeof name !== 'string' || !KEY_NAME_PATTERN.test(name)) {
|
|
66
|
+
throw new KeyStoreError(
|
|
67
|
+
'GENESIS_KEY_NAME_INVALID',
|
|
68
|
+
`"${String(name).slice(0, 80)}" is not a key name: lowercase letters, digits and dashes, 2 to 64 characters, starting with a letter (for example "stripe-secret-key")`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return name;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function checkValue(value) {
|
|
75
|
+
if (typeof value !== 'string') throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the value must be a string');
|
|
76
|
+
const v = value.trim();
|
|
77
|
+
if (!v) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the value is empty');
|
|
78
|
+
if (v.length > MAX_VALUE) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', `the value is longer than ${MAX_VALUE} characters`);
|
|
79
|
+
if (/[\u0000\r\n]/.test(v)) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the value must be one line');
|
|
80
|
+
return v;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The last four characters, for a long value only (a short one would give most of it away). */
|
|
84
|
+
function tailOf(value) {
|
|
85
|
+
return typeof value === 'string' && value.length >= 12 ? value.slice(-4) : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function row(name, entry, { builtin = false, envOverride = false } = {}) {
|
|
89
|
+
const value = typeof entry.value === 'string' && entry.value ? entry.value : null;
|
|
90
|
+
return {
|
|
91
|
+
name,
|
|
92
|
+
label: entry.label || name,
|
|
93
|
+
description: entry.description || '',
|
|
94
|
+
builtin,
|
|
95
|
+
status: value || envOverride ? 'set' : 'empty',
|
|
96
|
+
...(envOverride ? { source: API_KEY_ENV } : {}),
|
|
97
|
+
tail: tailOf(value),
|
|
98
|
+
updatedAt: entry.updatedAt ?? null,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Every key, the built-in Genesis API key first. `tail` (the last four
|
|
104
|
+
* characters) is for the page; the tools drop it.
|
|
105
|
+
*/
|
|
106
|
+
export function listKeys(env = process.env) {
|
|
107
|
+
const { cfg, keys } = load(env);
|
|
108
|
+
const envKey = typeof env[API_KEY_ENV] === 'string' && env[API_KEY_ENV].trim() !== '';
|
|
109
|
+
const rows = [
|
|
110
|
+
row(
|
|
111
|
+
BUILTIN_KEY,
|
|
112
|
+
{ label: BUILTIN_LABEL, description: BUILTIN_DESCRIPTION, value: cfg.apiKey, updatedAt: cfg.apiKeyUpdatedAt },
|
|
113
|
+
{ builtin: true, envOverride: envKey },
|
|
114
|
+
),
|
|
115
|
+
];
|
|
116
|
+
for (const name of Object.keys(keys).sort()) {
|
|
117
|
+
if (!KEY_NAME_PATTERN.test(name) || name === BUILTIN_KEY) continue;
|
|
118
|
+
const e = keys[name];
|
|
119
|
+
if (e && typeof e === 'object') rows.push(row(name, e));
|
|
120
|
+
}
|
|
121
|
+
return rows;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function findKey(env, name) {
|
|
125
|
+
return listKeys(env).find((k) => k.name === name) ?? null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Registers a key (or updates its label and description); an existing value is
|
|
130
|
+
* kept. The built-in key is only reported.
|
|
131
|
+
*/
|
|
132
|
+
export function requestKey(env, { name, label, description }) {
|
|
133
|
+
checkKeyName(name);
|
|
134
|
+
if (name === BUILTIN_KEY) return findKey(env, name);
|
|
135
|
+
const l = cleanText(label, MAX_LABEL, 'label');
|
|
136
|
+
const d = cleanText(description, MAX_DESCRIPTION, 'description');
|
|
137
|
+
const store = load(env);
|
|
138
|
+
const prev = store.keys[name] && typeof store.keys[name] === 'object' ? store.keys[name] : null;
|
|
139
|
+
const at = now();
|
|
140
|
+
store.keys[name] = {
|
|
141
|
+
label: l || prev?.label || name,
|
|
142
|
+
description: d ?? prev?.description ?? '',
|
|
143
|
+
...(prev?.value ? { value: prev.value } : {}),
|
|
144
|
+
createdAt: prev?.createdAt ?? at,
|
|
145
|
+
updatedAt: prev ? prev.updatedAt ?? at : at,
|
|
146
|
+
};
|
|
147
|
+
save(store);
|
|
148
|
+
return findKey(env, name);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function setKeyValue(env, name, value) {
|
|
152
|
+
checkKeyName(name);
|
|
153
|
+
const v = checkValue(value);
|
|
154
|
+
const store = load(env);
|
|
155
|
+
const at = now();
|
|
156
|
+
if (name === BUILTIN_KEY) {
|
|
157
|
+
if (/\s/.test(v)) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', 'the Genesis API key must not contain whitespace');
|
|
158
|
+
store.cfg = { ...store.cfg, apiKey: v, apiKeyUpdatedAt: at };
|
|
159
|
+
} else {
|
|
160
|
+
const prev = store.keys[name];
|
|
161
|
+
if (!prev || typeof prev !== 'object') throw new KeyStoreError('GENESIS_KEY_NOT_FOUND', `no key named "${name}"`, 404);
|
|
162
|
+
store.keys[name] = { ...prev, value: v, updatedAt: at };
|
|
163
|
+
}
|
|
164
|
+
save(store);
|
|
165
|
+
return findKey(env, name);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function clearKeyValue(env, name) {
|
|
169
|
+
checkKeyName(name);
|
|
170
|
+
const store = load(env);
|
|
171
|
+
if (name === BUILTIN_KEY) {
|
|
172
|
+
store.cfg = { ...store.cfg, apiKey: undefined, apiKeyUpdatedAt: undefined };
|
|
173
|
+
} else {
|
|
174
|
+
const prev = store.keys[name];
|
|
175
|
+
if (!prev || typeof prev !== 'object') throw new KeyStoreError('GENESIS_KEY_NOT_FOUND', `no key named "${name}"`, 404);
|
|
176
|
+
const { value: _dropped, ...rest } = prev;
|
|
177
|
+
store.keys[name] = { ...rest, updatedAt: now() };
|
|
178
|
+
}
|
|
179
|
+
save(store);
|
|
180
|
+
return findKey(env, name);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function deleteKey(env, name) {
|
|
184
|
+
checkKeyName(name);
|
|
185
|
+
if (name === BUILTIN_KEY) {
|
|
186
|
+
throw new KeyStoreError('GENESIS_KEY_BUILTIN', 'the Genesis API key cannot be deleted; clear its value instead');
|
|
187
|
+
}
|
|
188
|
+
const store = load(env);
|
|
189
|
+
if (!(name in store.keys)) throw new KeyStoreError('GENESIS_KEY_NOT_FOUND', `no key named "${name}"`, 404);
|
|
190
|
+
delete store.keys[name];
|
|
191
|
+
save(store);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A stored value, for the code that uses the key. Never put it in a tool answer. */
|
|
195
|
+
export function keyValue(env, name) {
|
|
196
|
+
checkKeyName(name);
|
|
197
|
+
const { cfg, keys } = load(env);
|
|
198
|
+
if (name === BUILTIN_KEY) {
|
|
199
|
+
const fromEnv = typeof env[API_KEY_ENV] === 'string' ? env[API_KEY_ENV].trim() : '';
|
|
200
|
+
return fromEnv || (typeof cfg.apiKey === 'string' && cfg.apiKey.trim()) || null;
|
|
201
|
+
}
|
|
202
|
+
const e = keys[name];
|
|
203
|
+
return e && typeof e === 'object' && typeof e.value === 'string' && e.value ? e.value : null;
|
|
204
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// The key tools of the genesis-set MCP server (#9352). They manage the local
|
|
2
|
+
// key store (./key-store.mjs) through the local key page (./key-page.mjs) and
|
|
3
|
+
// never put a key's value into an answer: the agent asks for a key, hands the
|
|
4
|
+
// user the page link, and sees only whether the key is set.
|
|
5
|
+
//
|
|
6
|
+
// genesis_requestKey register a key (empty) and answer the page link
|
|
7
|
+
// genesis_listKeys every key: name, label, description, set / empty
|
|
8
|
+
// genesis_openKeyManager the page link, to manage every key
|
|
9
|
+
// genesis_writeKeyToEnvFile copy a stored value into a gitignored env file
|
|
10
|
+
//
|
|
11
|
+
// They work without a Genesis API key: the first one is how the user sets it.
|
|
12
|
+
|
|
13
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
|
|
17
|
+
import { genesisError } from './client.mjs';
|
|
18
|
+
import { ensureKeyPage } from './key-page.mjs';
|
|
19
|
+
import { BUILTIN_KEY, KeyStoreError, checkKeyName, findKey, keyValue, listKeys, requestKey } from './key-store.mjs';
|
|
20
|
+
|
|
21
|
+
const KEY_NAME = {
|
|
22
|
+
type: 'string',
|
|
23
|
+
description: `The key's name: lowercase kebab-case, for example "stripe-secret-key". "${BUILTIN_KEY}" is the Genesis API key itself.`,
|
|
24
|
+
};
|
|
25
|
+
const OPEN = {
|
|
26
|
+
type: 'boolean',
|
|
27
|
+
description: "Also open the page in the user's default browser on this machine (default false). Only when the user agreed.",
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const KEY_TOOLS = [
|
|
31
|
+
{
|
|
32
|
+
name: 'genesis_requestKey',
|
|
33
|
+
title: 'Ask the user for a key on the local key page',
|
|
34
|
+
description:
|
|
35
|
+
'Register a key the work needs (a provider secret, the Genesis API key) as an empty entry with a readable label and a description, ' +
|
|
36
|
+
'and get the link of the local key page where the user enters it. Give the user the link and ask them to save the key there, then check with genesis_listKeys. ' +
|
|
37
|
+
'Never ask for a key value in the chat. An entry that already exists keeps its value.',
|
|
38
|
+
inputSchema: {
|
|
39
|
+
type: 'object',
|
|
40
|
+
properties: {
|
|
41
|
+
name: KEY_NAME,
|
|
42
|
+
label: { type: 'string', description: 'A human-readable name shown on the page, for example "Stripe secret key (test mode)".' },
|
|
43
|
+
description: {
|
|
44
|
+
type: 'string',
|
|
45
|
+
description: 'What the key is for and where the user gets it, shown on the page (for example "Stripe dashboard, Developers > API keys; a test-mode key starting sk_test_").',
|
|
46
|
+
},
|
|
47
|
+
open: OPEN,
|
|
48
|
+
},
|
|
49
|
+
required: ['name', 'label'],
|
|
50
|
+
additionalProperties: false,
|
|
51
|
+
},
|
|
52
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
name: 'genesis_listKeys',
|
|
56
|
+
title: 'List the keys of the local key store',
|
|
57
|
+
description: 'Every key of the local key store with its label, description and status (set or empty). Values are never answered.',
|
|
58
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
59
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: 'genesis_openKeyManager',
|
|
63
|
+
title: 'Open the local key page',
|
|
64
|
+
description: 'The link of the local key page, where the user adds, changes and deletes keys. The link works on this machine only and expires when idle.',
|
|
65
|
+
inputSchema: { type: 'object', properties: { open: OPEN }, additionalProperties: false },
|
|
66
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: 'genesis_writeKeyToEnvFile',
|
|
70
|
+
title: 'Write a stored key into a gitignored env file',
|
|
71
|
+
description:
|
|
72
|
+
'Copy a stored key into an env file of a generated service (for example its .dev.secrets.env) as VARIABLE=value, without the value passing through the agent. ' +
|
|
73
|
+
'Only a file named .env, .env.local or *.secrets.env is accepted, and inside a git repository only one that git ignores and does not track. The answer never carries the value.',
|
|
74
|
+
inputSchema: {
|
|
75
|
+
type: 'object',
|
|
76
|
+
properties: {
|
|
77
|
+
name: KEY_NAME,
|
|
78
|
+
file: { type: 'string', description: 'The env file (absolute, or relative to the folder the agent was started in).' },
|
|
79
|
+
variable: { type: 'string', description: 'The variable name in the file, for example STRIPE_SECRET_KEY.' },
|
|
80
|
+
},
|
|
81
|
+
required: ['name', 'file', 'variable'],
|
|
82
|
+
additionalProperties: false,
|
|
83
|
+
},
|
|
84
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
85
|
+
},
|
|
86
|
+
];
|
|
87
|
+
|
|
88
|
+
const KEY_TOOL_NAMES = new Set(KEY_TOOLS.map((t) => t.name));
|
|
89
|
+
|
|
90
|
+
export function isKeyTool(name) {
|
|
91
|
+
return KEY_TOOL_NAMES.has(name);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A row for the agent: the page's row without the value's tail. */
|
|
95
|
+
function forAgent(row) {
|
|
96
|
+
if (!row) return row;
|
|
97
|
+
const { tail: _tail, ...rest } = row;
|
|
98
|
+
return rest;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function openInBrowser(url) {
|
|
102
|
+
const [cmd, args] =
|
|
103
|
+
process.platform === 'darwin' ? ['open', [url]]
|
|
104
|
+
: process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]]
|
|
105
|
+
: ['xdg-open', [url]];
|
|
106
|
+
try {
|
|
107
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
|
|
108
|
+
child.on('error', () => {});
|
|
109
|
+
child.unref();
|
|
110
|
+
return true;
|
|
111
|
+
} catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const ENV_FILE_NAME = /^(\.env|\.env\.local|\.[A-Za-z0-9._-]*secrets\.env|[A-Za-z0-9._-]+\.secrets\.env)$/;
|
|
117
|
+
const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
118
|
+
|
|
119
|
+
function git(dir, args) {
|
|
120
|
+
const r = spawnSync('git', ['-C', dir, ...args], { encoding: 'utf8', windowsHide: true });
|
|
121
|
+
return r.error ? null : r;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Why a file may not receive a key, or null. Inside a git work tree it must be ignored and untracked. */
|
|
125
|
+
function envFileRefusal(file) {
|
|
126
|
+
if (!ENV_FILE_NAME.test(path.basename(file))) {
|
|
127
|
+
return `${path.basename(file)} is not an env file genesis-set writes keys into (.env, .env.local or *.secrets.env)`;
|
|
128
|
+
}
|
|
129
|
+
const dir = path.dirname(file);
|
|
130
|
+
if (!fs.existsSync(dir)) return `the folder ${dir} does not exist`;
|
|
131
|
+
const inside = git(dir, ['rev-parse', '--is-inside-work-tree']);
|
|
132
|
+
if (!inside || inside.status !== 0 || inside.stdout.trim() !== 'true') return null; // not a repository: nothing to commit it into
|
|
133
|
+
const tracked = git(dir, ['ls-files', '--error-unmatch', '--', path.basename(file)]);
|
|
134
|
+
if (tracked && tracked.status === 0) return `${file} is tracked by git; a key never goes into a committed file`;
|
|
135
|
+
const ignored = git(dir, ['check-ignore', '-q', '--', path.basename(file)]);
|
|
136
|
+
if (!ignored || ignored.status !== 0) return `${file} is not ignored by git; add it to .gitignore first so the key cannot be committed`;
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** VALUE as an env-file value: bare when it is plain, else double-quoted with \ and " escaped. */
|
|
141
|
+
function envValue(v) {
|
|
142
|
+
return /^[A-Za-z0-9_./:@+=,-]*$/.test(v) ? v : `"${v.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function writeEnvVariable(file, variable, value) {
|
|
146
|
+
let text = '';
|
|
147
|
+
let created = false;
|
|
148
|
+
try {
|
|
149
|
+
text = fs.readFileSync(file, 'utf8');
|
|
150
|
+
} catch (e) {
|
|
151
|
+
if (e.code !== 'ENOENT') throw e;
|
|
152
|
+
created = true;
|
|
153
|
+
}
|
|
154
|
+
const line = `${variable}=${envValue(value)}`;
|
|
155
|
+
const lines = text === '' ? [] : text.replace(/\r?\n$/, '').split(/\r?\n/);
|
|
156
|
+
const at = lines.findIndex((l) => new RegExp(`^\\s*(export\\s+)?${variable}\\s*=`).test(l));
|
|
157
|
+
const replaced = at >= 0;
|
|
158
|
+
if (replaced) lines[at] = line;
|
|
159
|
+
else lines.push(line);
|
|
160
|
+
const tmp = `${file}.genesis-set.${process.pid}.tmp`;
|
|
161
|
+
let mode = 0o600;
|
|
162
|
+
if (!created) {
|
|
163
|
+
try {
|
|
164
|
+
mode = fs.statSync(file).mode & 0o777;
|
|
165
|
+
} catch {
|
|
166
|
+
// keep 0600
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
fs.writeFileSync(tmp, `${lines.join('\n')}\n`, { mode });
|
|
170
|
+
fs.renameSync(tmp, file);
|
|
171
|
+
return { created, replaced };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function pageLink(settings, open) {
|
|
175
|
+
const link = await ensureKeyPage({ env: settings.env ?? process.env });
|
|
176
|
+
const opened = open === true ? openInBrowser(link.url) : false;
|
|
177
|
+
return { ...link, opened };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const HANDLERS = {
|
|
181
|
+
async genesis_requestKey(args, settings) {
|
|
182
|
+
const env = settings.env ?? process.env;
|
|
183
|
+
const key = forAgent(requestKey(env, { name: args.name, label: args.label, description: args.description }));
|
|
184
|
+
const link = await pageLink(settings, args.open);
|
|
185
|
+
return {
|
|
186
|
+
key,
|
|
187
|
+
keyPage: link,
|
|
188
|
+
next:
|
|
189
|
+
key.status === 'set'
|
|
190
|
+
? `"${key.label}" is already set. Use it; the user can change it on the key page.`
|
|
191
|
+
: `Ask the user to open ${link.url} on this machine and save "${key.label}" there, then call genesis_listKeys to see it set. ` +
|
|
192
|
+
'Never ask for the value in the chat. Later the user can open the page themselves with "genesis keys" in a terminal.',
|
|
193
|
+
};
|
|
194
|
+
},
|
|
195
|
+
async genesis_listKeys(_args, settings) {
|
|
196
|
+
return { keys: listKeys(settings.env ?? process.env).map(forAgent) };
|
|
197
|
+
},
|
|
198
|
+
async genesis_openKeyManager(args, settings) {
|
|
199
|
+
return { keyPage: await pageLink(settings, args.open) };
|
|
200
|
+
},
|
|
201
|
+
async genesis_writeKeyToEnvFile(args, settings) {
|
|
202
|
+
const env = settings.env ?? process.env;
|
|
203
|
+
checkKeyName(args.name);
|
|
204
|
+
if (!VARIABLE.test(args.variable)) throw new KeyStoreError('GENESIS_KEY_BAD_INPUT', `"${args.variable}" is not an env variable name`);
|
|
205
|
+
const row = findKey(env, args.name);
|
|
206
|
+
if (!row) throw new KeyStoreError('GENESIS_KEY_NOT_FOUND', `no key named "${args.name}"; register it with genesis_requestKey`, 404);
|
|
207
|
+
const value = keyValue(env, args.name);
|
|
208
|
+
if (!value) throw new KeyStoreError('GENESIS_KEY_NOT_SET', `"${row.label}" has no value yet; ask the user to save it on the key page (genesis_openKeyManager)`, 409);
|
|
209
|
+
const file = path.resolve(settings.cwd ?? process.cwd(), args.file);
|
|
210
|
+
const refusal = envFileRefusal(file);
|
|
211
|
+
if (refusal) throw new KeyStoreError('GENESIS_ENV_FILE_REFUSED', refusal, 422);
|
|
212
|
+
const { created, replaced } = writeEnvVariable(file, args.variable, value);
|
|
213
|
+
return { written: true, key: args.name, file, variable: args.variable, created, replaced };
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
/** Runs a key tool; answers `{ ok, body }` like an API call. Never throws. */
|
|
218
|
+
export async function runKeyTool(name, args, settings) {
|
|
219
|
+
try {
|
|
220
|
+
return { ok: true, httpStatus: null, body: await HANDLERS[name](args, settings) };
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (err instanceof KeyStoreError) return { ok: false, httpStatus: null, body: genesisError(err.code, err.message) };
|
|
223
|
+
return { ok: false, httpStatus: null, body: genesisError('GENESIS_TOOL_FAILED', `${name} failed: ${err?.message ?? String(err)}`) };
|
|
224
|
+
}
|
|
225
|
+
}
|
package/mcp/server.mjs
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The genesis-set MCP server: the Genesis Compiler API as genesis_* tools for a
|
|
3
|
+
// coding agent (Claude Code, Codex). MCP over stdio: one JSON-RPC 2.0 message
|
|
4
|
+
// per line on stdin / stdout, logs on stderr only. No dependencies besides
|
|
5
|
+
// Node >= 18.
|
|
6
|
+
//
|
|
7
|
+
// `genesis install` copies this folder to ~/.genesis-set/mcp/ and registers
|
|
8
|
+
// it with each installed agent; `genesis mcp` runs it from the package.
|
|
9
|
+
// The API key and the API base are resolved on every call (./config.mjs), so a
|
|
10
|
+
// key stored with `genesis config set-key` works without a restart.
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
15
|
+
|
|
16
|
+
import { resolveSettings } from './config.mjs';
|
|
17
|
+
import { closeKeyPage } from './key-page.mjs';
|
|
18
|
+
import { TOOLS, hasTool, runTool } from './tools.mjs';
|
|
19
|
+
|
|
20
|
+
export const SUPPORTED_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
21
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
|
|
23
|
+
function serverVersion() {
|
|
24
|
+
for (const p of [path.join(HERE, 'version.json'), path.join(HERE, '..', 'package.json')]) {
|
|
25
|
+
try {
|
|
26
|
+
const v = JSON.parse(fs.readFileSync(p, 'utf8')).version;
|
|
27
|
+
if (typeof v === 'string') return v;
|
|
28
|
+
} catch {
|
|
29
|
+
// next candidate
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return '0.0.0';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const INSTRUCTIONS =
|
|
36
|
+
'Tools for the Genesis Compiler API (builds are dry runs for now; when a call answers GENESIS_UNREACHABLE, the API could not be reached: say so and stop, never report a validation or build that did not happen). ' +
|
|
37
|
+
'Validate the whole blueprint with genesis_validateApplication before any build; compile one service at a time with genesis_buildService and follow its jobId with genesis_getServiceBuild until a final status. ' +
|
|
38
|
+
'Blueprint paths are read on this machine and sent inline. Every failure is a Genesis error { error: { code, message, details } }: report the code. ' +
|
|
39
|
+
'Keys (the Genesis API key, provider secrets): never ask for a value in the chat. Register the key with genesis_requestKey, give the user the local key page link it answers, and check genesis_listKeys; ' +
|
|
40
|
+
'genesis_writeKeyToEnvFile puts a stored key into a gitignored env file without you seeing it. ' +
|
|
41
|
+
'The genesis-compiler-api skill has the full procedure.';
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Serves MCP on `input` / `output` (streams) until `input` ends. Resolves when
|
|
45
|
+
* every pending call has answered. `env` and `cwd` are for tests.
|
|
46
|
+
*/
|
|
47
|
+
export function serve({ input = process.stdin, output = process.stdout, log = (l) => process.stderr.write(`${l}\n`), env = process.env, cwd = process.cwd() } = {}) {
|
|
48
|
+
const version = serverVersion();
|
|
49
|
+
const inflight = new Map();
|
|
50
|
+
let buffer = '';
|
|
51
|
+
let ended = false;
|
|
52
|
+
let resolveDone;
|
|
53
|
+
const done = new Promise((r) => {
|
|
54
|
+
resolveDone = r;
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const send = (msg) => output.write(`${JSON.stringify(msg)}\n`);
|
|
58
|
+
const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
|
|
59
|
+
const fail = (id, code, message, data) => send({ jsonrpc: '2.0', id, error: { code, message, ...(data === undefined ? {} : { data }) } });
|
|
60
|
+
const maybeFinish = () => {
|
|
61
|
+
if (ended && inflight.size === 0) resolveDone();
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
async function handle(msg) {
|
|
65
|
+
if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
|
|
66
|
+
if (msg && typeof msg === 'object' && ('result' in msg || 'error' in msg)) return; // a response to nothing we sent
|
|
67
|
+
fail(msg?.id ?? null, -32600, 'Invalid Request');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const isRequest = msg.id !== undefined && msg.id !== null;
|
|
71
|
+
const params = msg.params ?? {};
|
|
72
|
+
switch (msg.method) {
|
|
73
|
+
case 'initialize': {
|
|
74
|
+
const asked = params.protocolVersion;
|
|
75
|
+
const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(asked) ? asked : SUPPORTED_PROTOCOL_VERSIONS[0];
|
|
76
|
+
reply(msg.id, {
|
|
77
|
+
protocolVersion,
|
|
78
|
+
capabilities: { tools: { listChanged: false } },
|
|
79
|
+
serverInfo: { name: 'genesis-set', title: 'Genesis Compiler API (genesis-set)', version },
|
|
80
|
+
instructions: INSTRUCTIONS,
|
|
81
|
+
});
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
case 'notifications/initialized':
|
|
85
|
+
return;
|
|
86
|
+
case 'notifications/cancelled': {
|
|
87
|
+
inflight.get(params.requestId)?.abort();
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
case 'ping':
|
|
91
|
+
if (isRequest) reply(msg.id, {});
|
|
92
|
+
return;
|
|
93
|
+
case 'tools/list':
|
|
94
|
+
reply(msg.id, { tools: TOOLS });
|
|
95
|
+
return;
|
|
96
|
+
case 'tools/call': {
|
|
97
|
+
const name = params.name;
|
|
98
|
+
if (!hasTool(name)) {
|
|
99
|
+
fail(msg.id, -32602, `Unknown tool: ${name}`);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const ctl = new AbortController();
|
|
103
|
+
inflight.set(msg.id, ctl);
|
|
104
|
+
try {
|
|
105
|
+
const settings = { ...resolveSettings(env), env, cwd, userAgent: `genesis-set/${version} (mcp)` };
|
|
106
|
+
for (const p of settings.problems) log(`genesis mcp: ${p}`);
|
|
107
|
+
const result = await runTool(name, params.arguments, settings, ctl.signal);
|
|
108
|
+
if (!ctl.signal.aborted) reply(msg.id, result);
|
|
109
|
+
} finally {
|
|
110
|
+
inflight.delete(msg.id);
|
|
111
|
+
maybeFinish();
|
|
112
|
+
}
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
default:
|
|
116
|
+
if (isRequest) fail(msg.id, -32601, `Method not found: ${msg.method}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const dispatch = (msg) => {
|
|
121
|
+
handle(msg).catch((err) => {
|
|
122
|
+
log(`genesis mcp: ${err?.stack ?? err}`);
|
|
123
|
+
if (msg?.id !== undefined && msg?.id !== null) fail(msg.id, -32603, 'Internal error');
|
|
124
|
+
});
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
input.setEncoding?.('utf8');
|
|
128
|
+
input.on('data', (chunk) => {
|
|
129
|
+
buffer += chunk;
|
|
130
|
+
let nl;
|
|
131
|
+
while ((nl = buffer.indexOf('\n')) >= 0) {
|
|
132
|
+
const line = buffer.slice(0, nl).replace(/\r$/, '');
|
|
133
|
+
buffer = buffer.slice(nl + 1);
|
|
134
|
+
if (!line.trim()) continue;
|
|
135
|
+
let msg;
|
|
136
|
+
try {
|
|
137
|
+
msg = JSON.parse(line);
|
|
138
|
+
} catch {
|
|
139
|
+
fail(null, -32700, 'Parse error');
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (Array.isArray(msg)) msg.forEach(dispatch);
|
|
143
|
+
else dispatch(msg);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
input.on('end', () => {
|
|
147
|
+
ended = true;
|
|
148
|
+
maybeFinish();
|
|
149
|
+
});
|
|
150
|
+
// The key page lives only as long as this server.
|
|
151
|
+
return done.then(() => closeKeyPage());
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function isMain() {
|
|
155
|
+
if (!process.argv[1]) return false;
|
|
156
|
+
try {
|
|
157
|
+
return pathToFileURL(fs.realpathSync(process.argv[1])).href === pathToFileURL(fs.realpathSync(fileURLToPath(import.meta.url))).href;
|
|
158
|
+
} catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Exit only once stdout is flushed: on a pipe, process.exit drops what is not
|
|
163
|
+
// written yet, and the last answer before stdin closed would be cut.
|
|
164
|
+
if (isMain()) serve().then(() => process.stdout.write('', () => process.exit(0)));
|