@machinal/mcp 0.4.3 → 0.4.4
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/README.md +52 -21
- package/package.json +3 -2
- package/skills/machinal-recipes/SKILL.md +1 -1
- package/skills/machinal-recipes/references/yaml.md +2 -0
- package/skills/machinal-support/SKILL.md +6 -2
- package/src/bridge.mjs +7 -2
- package/src/cli.mjs +49 -18
- package/src/commands.mjs +89 -0
- package/src/configuration.mjs +15 -5
- package/src/credential-store.mjs +22 -0
- package/src/formats.mjs +6 -1
- package/src/keys.mjs +27 -20
- package/src/local-setup.mjs +13 -4
- package/src/opencode-auth.mjs +36 -14
- package/src/opencode-configuration.mjs +83 -20
- package/src/opencode-media.mjs +5 -3
- package/src/opencode-upgrade.mjs +40 -0
- package/src/paths.mjs +8 -0
- package/src/presentation.mjs +1 -1
- package/src/private-json.mjs +86 -0
- package/src/prompts.mjs +3 -5
- package/src/runtime.mjs +11 -5
- package/src/settings.mjs +26 -0
- package/src/setup-stdio.mjs +27 -9
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { chmod, lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
import { InstallerError } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const MAX_BYTES = 64 * 1024;
|
|
8
|
+
|
|
9
|
+
function owned(info) {
|
|
10
|
+
return !process.getuid || info.uid === process.getuid();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function directory(file, create) {
|
|
14
|
+
const path = dirname(file);
|
|
15
|
+
if (create) await mkdir(path, { recursive: true, mode: 0o700 });
|
|
16
|
+
const info = await lstat(path);
|
|
17
|
+
if (!info.isDirectory() || info.isSymbolicLink() || !owned(info)) throw new Error('Unsafe directory');
|
|
18
|
+
if (process.platform !== 'win32' && (info.mode & 0o077)) {
|
|
19
|
+
if (!create) throw new Error('Directory permissions');
|
|
20
|
+
await chmod(path, 0o700);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function inspect(file) {
|
|
25
|
+
const info = await lstat(file);
|
|
26
|
+
if (!info.isFile() || info.isSymbolicLink() || !owned(info) || info.size > MAX_BYTES
|
|
27
|
+
|| (process.platform !== 'win32' && (info.mode & 0o077))) throw new Error('Unsafe file');
|
|
28
|
+
return info;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function readPrivateJSON(file) {
|
|
32
|
+
let handle;
|
|
33
|
+
try {
|
|
34
|
+
await directory(file, false);
|
|
35
|
+
const before = await inspect(file);
|
|
36
|
+
handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
37
|
+
const info = await handle.stat();
|
|
38
|
+
if (info.ino !== before.ino || info.dev !== before.dev || info.size > MAX_BYTES) throw new Error('File changed');
|
|
39
|
+
const buffer = Buffer.alloc(MAX_BYTES + 1);
|
|
40
|
+
let size = 0;
|
|
41
|
+
while (size < buffer.length) {
|
|
42
|
+
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
|
|
43
|
+
if (!bytesRead) break;
|
|
44
|
+
size += bytesRead;
|
|
45
|
+
}
|
|
46
|
+
if (size > MAX_BYTES) throw new Error('File too large');
|
|
47
|
+
return JSON.parse(buffer.subarray(0, size).toString('utf8'));
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.code === 'ENOENT') return null;
|
|
50
|
+
throw new InstallerError('Could not read the private Machinal file. Check ownership, directory mode 0700 and file mode 0600; symlinks are not supported. Nothing was deleted.');
|
|
51
|
+
} finally { await handle?.close(); }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function writePrivateJSON(file, value) {
|
|
55
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
56
|
+
let handle;
|
|
57
|
+
try {
|
|
58
|
+
await directory(file, true);
|
|
59
|
+
try { await inspect(file); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
60
|
+
const text = `${JSON.stringify(value, null, 2)}\n`;
|
|
61
|
+
if (Buffer.byteLength(text) > MAX_BYTES) throw new Error('File too large');
|
|
62
|
+
handle = await open(temporary, 'wx', 0o600);
|
|
63
|
+
await handle.writeFile(text, 'utf8');
|
|
64
|
+
await handle.sync();
|
|
65
|
+
await handle.close();
|
|
66
|
+
handle = null;
|
|
67
|
+
await rename(temporary, file);
|
|
68
|
+
} catch {
|
|
69
|
+
throw new InstallerError('Could not save the private Machinal file. Check ownership, permissions and free disk space. No plaintext backup or alternate location was created.');
|
|
70
|
+
} finally {
|
|
71
|
+
await handle?.close();
|
|
72
|
+
await unlink(temporary).catch(() => {});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function deletePrivateJSON(file) {
|
|
77
|
+
try {
|
|
78
|
+
await directory(file, false);
|
|
79
|
+
await inspect(file);
|
|
80
|
+
await unlink(file);
|
|
81
|
+
return true;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error.code === 'ENOENT') return false;
|
|
84
|
+
throw new InstallerError('Could not delete the private Machinal file. Check ownership and permissions; nothing else was removed.');
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/prompts.mjs
CHANGED
|
@@ -4,13 +4,13 @@ export function createPromptUI(prompts, options = {}) {
|
|
|
4
4
|
const style = terminalStyle(options);
|
|
5
5
|
const stream = options.stream ?? process.stdout;
|
|
6
6
|
const theme = {
|
|
7
|
-
prefix: { idle: '?', done: '-' },
|
|
7
|
+
prefix: { idle: style('magenta', '?'), done: style('magenta', '-') },
|
|
8
8
|
spinner: { interval: 120, frames: ['-', '\\', '|', '/'] },
|
|
9
9
|
icon: { cursor: '>' },
|
|
10
10
|
style: {
|
|
11
11
|
message: (text, status) => status === 'done' ? text : style('bold', text),
|
|
12
12
|
answer: (text) => text,
|
|
13
|
-
highlight: (text) => style('
|
|
13
|
+
highlight: (text) => style('magenta', text),
|
|
14
14
|
description: (text) => text,
|
|
15
15
|
help: (text) => text,
|
|
16
16
|
disabled: (text) => text,
|
|
@@ -18,9 +18,7 @@ export function createPromptUI(prompts, options = {}) {
|
|
|
18
18
|
confirmDefault: (text) => text.toUpperCase(),
|
|
19
19
|
key: (text) => `<${text}>`,
|
|
20
20
|
error: (text) => `${style('red', 'Error:')} ${text}`,
|
|
21
|
-
keysHelpTip: () =>
|
|
22
|
-
? ' Up/down · Enter · Ctrl+C cancels'
|
|
23
|
-
: ' Up/down to move · Enter to select · Ctrl+C to cancel',
|
|
21
|
+
keysHelpTip: () => ' Up/down · Enter · Ctrl+C cancels',
|
|
24
22
|
},
|
|
25
23
|
};
|
|
26
24
|
return Object.fromEntries(Object.entries(prompts).map(([name, prompt]) => [name, (config, context) => prompt({
|
package/src/runtime.mjs
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { cp, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
-
import {
|
|
4
|
-
import { join } from 'node:path';
|
|
3
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
5
4
|
import { fileURLToPath } from 'node:url';
|
|
6
5
|
import { VERSION } from './version.mjs';
|
|
6
|
+
import { stateDirectory } from './paths.mjs';
|
|
7
|
+
|
|
8
|
+
export { stateDirectory } from './paths.mjs';
|
|
7
9
|
|
|
8
10
|
const ROOT = fileURLToPath(new URL('../', import.meta.url));
|
|
9
11
|
const FILES = ['bin/machinal-stdio.mjs', 'src/bridge.mjs', 'src/connection.mjs', 'src/credential-store.mjs',
|
|
10
|
-
'src/credits.mjs', 'src/endpoints.mjs', 'src/errors.mjs', 'src/presentation.mjs', 'src/
|
|
12
|
+
'src/credits.mjs', 'src/endpoints.mjs', 'src/errors.mjs', 'src/presentation.mjs', 'src/paths.mjs',
|
|
13
|
+
'src/private-json.mjs', 'src/version.mjs', 'package.json'];
|
|
11
14
|
|
|
12
|
-
export function
|
|
13
|
-
|
|
15
|
+
export function isManagedRuntimeCommand(command, context = {}) {
|
|
16
|
+
if (!Array.isArray(command) || !isAbsolute(command[1] ?? '')) return false;
|
|
17
|
+
const parts = relative(join(stateDirectory(context), 'runtime'), command[1]).split(sep);
|
|
18
|
+
return parts.length === 3 && /^\d+\.\d+\.\d+(?:-[\w.-]+)?-(?:win32|linux|darwin)-[\w]+-[a-f\d]{16}$/.test(parts[0])
|
|
19
|
+
&& parts[1] === 'bin' && parts[2] === 'machinal-stdio.mjs' && command[2] === 'serve';
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
export function endpointFiles(url, context) {
|
package/src/settings.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { normalizeEndpoint } from './connection.mjs';
|
|
3
|
+
import { InstallerError } from './errors.mjs';
|
|
4
|
+
import { stateDirectory } from './paths.mjs';
|
|
5
|
+
import { readPrivateJSON, writePrivateJSON } from './private-json.mjs';
|
|
6
|
+
|
|
7
|
+
export function settingsFile(context) {
|
|
8
|
+
return join(stateDirectory(context), 'config.json');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function readSettings(context) {
|
|
12
|
+
const value = await readPrivateJSON(settingsFile(context));
|
|
13
|
+
if (value === null) return { version: 1 };
|
|
14
|
+
if (value.version !== 1 || (value.connection && (!['server', 'custom', 'local'].includes(value.connection.mode)
|
|
15
|
+
|| normalizeEndpoint(value.connection.url) !== value.connection.url))) {
|
|
16
|
+
throw new InstallerError('The Machinal settings file is invalid. Check machinal place; existing settings were not replaced.');
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function saveSettings(patch, context) {
|
|
22
|
+
const current = await readSettings(context);
|
|
23
|
+
const next = { ...current, ...patch, version: 1 };
|
|
24
|
+
if (JSON.stringify(current) !== JSON.stringify(next)) await writePrivateJSON(settingsFile(context), next);
|
|
25
|
+
return next;
|
|
26
|
+
}
|
package/src/setup-stdio.mjs
CHANGED
|
@@ -8,8 +8,11 @@ import { cacheCatalog, MCPBridge } from './bridge.mjs';
|
|
|
8
8
|
import { endpointFiles, installRuntime } from './runtime.mjs';
|
|
9
9
|
import { prepareIndependentLocal } from './local-setup.mjs';
|
|
10
10
|
import { backupSummary } from './presentation.mjs';
|
|
11
|
-
import { compactCreditSummaryLines } from './credits.mjs';
|
|
11
|
+
import { compactCreditSummaryLines, creditSummaryLines } from './credits.mjs';
|
|
12
12
|
import { InstallerError } from './errors.mjs';
|
|
13
|
+
import { planOpenCodeUpgrade, saveOpenCodeUpgrade } from './opencode-upgrade.mjs';
|
|
14
|
+
import { VERSION } from './version.mjs';
|
|
15
|
+
import { saveSettings } from './settings.mjs';
|
|
13
16
|
|
|
14
17
|
async function approveConflict(conflict, allowed, message, context) {
|
|
15
18
|
if (!conflict || allowed) return;
|
|
@@ -34,6 +37,7 @@ async function serverCredentials(values, context) {
|
|
|
34
37
|
|
|
35
38
|
export async function setupStdio(values, context) {
|
|
36
39
|
const { cwd, home, env, interactive, ui, log } = context;
|
|
40
|
+
log('Machinal', 'heading');
|
|
37
41
|
const client = await chooseClient(values.client, context);
|
|
38
42
|
const defaultScope = client === 'codex' ? 'global' : 'project';
|
|
39
43
|
const scope = values.scope ?? (interactive ? await ui.select({ message: 'Available in', default: defaultScope, choices: [
|
|
@@ -51,6 +55,11 @@ export async function setupStdio(values, context) {
|
|
|
51
55
|
const options = { client, scope, cwd, home, env, url: endpoint.url, name: values.name ?? 'machinal', transport: 'stdio', script,
|
|
52
56
|
catalogFile: files.catalogFile, ...(local ? { localConfig: files.localConfig } : {}) };
|
|
53
57
|
const plan = await planConfiguration(options);
|
|
58
|
+
const related = client === 'opencode' && plan.automaticAuth ? await planOpenCodeUpgrade(plan, options) : [];
|
|
59
|
+
if (related.length) {
|
|
60
|
+
log(`Synchronizing Machinal companion/runtime ${VERSION} in ${related.length + 1} applicable OpenCode configurations (global/project/ancestors).`);
|
|
61
|
+
if (context.verbose) for (const entry of related) log(`Will synchronize: ${entry.file}`);
|
|
62
|
+
}
|
|
54
63
|
if (client === 'codex' && scope === 'global') {
|
|
55
64
|
try {
|
|
56
65
|
const project = await planConfiguration({ ...options, scope: 'project' });
|
|
@@ -67,7 +76,7 @@ export async function setupStdio(values, context) {
|
|
|
67
76
|
let result;
|
|
68
77
|
let connection;
|
|
69
78
|
if (local) {
|
|
70
|
-
log('
|
|
79
|
+
log('Local: your hardware and OpenRouter key. No Machinal credits.');
|
|
71
80
|
const profile = await prepareIndependentLocal(values, endpoint.url, files.localConfig, context);
|
|
72
81
|
credentials = { key: profile.key, source: 'local' };
|
|
73
82
|
const verify = () => (context.checkConnection ?? checkConnection)(endpoint.url, profile.key, { local: true });
|
|
@@ -91,26 +100,35 @@ export async function setupStdio(values, context) {
|
|
|
91
100
|
if (result?.tools) {
|
|
92
101
|
await cacheCatalog(files.catalogFile, { url: endpoint.url, tools: result.tools, instructions: result.instructions });
|
|
93
102
|
}
|
|
94
|
-
const
|
|
103
|
+
const upgrades = related.length ? await saveOpenCodeUpgrade(plan, related) : [];
|
|
104
|
+
const saved = upgrades.at(-1) ?? await saveConfiguration(plan);
|
|
105
|
+
for (const upgraded of upgrades.slice(0, -1)) {
|
|
106
|
+
if (upgraded.backup) log(`Backup: ${upgraded.backup}`);
|
|
107
|
+
}
|
|
95
108
|
const installed = skills ? await saveSkills(skills) : null;
|
|
109
|
+
await saveSettings({ connection: { mode: endpoint.mode, url: endpoint.url, ...(local ? { localConfig: files.localConfig } : {}) } }, context);
|
|
96
110
|
const backups = backupSummary(saved, installed, skills?.root);
|
|
97
111
|
if (backups) log(backups);
|
|
98
112
|
if (!local && result && credentials) await offerKeyStorage(credentials, context, { sessionOnly: values['session-key'] });
|
|
113
|
+
log('Setup ready', 'heading');
|
|
99
114
|
log(`MCP adapter configured for ${client}: ${plan.file}`);
|
|
100
115
|
log(result ? `Service verified: ${result.toolCount} tools. A running client connection has not been checked.`
|
|
101
116
|
: `Service status: ${connection?.status ?? 'login_required'}. The adapter is installed, not a verified service connection.`);
|
|
102
|
-
if (result?.credits) for (const line of compactCreditSummaryLines(result.credits)) log(line);
|
|
117
|
+
if (result?.credits) for (const line of (context.verbose ? creditSummaryLines : compactCreditSummaryLines)(result.credits)) log(line);
|
|
103
118
|
if (result?.creditsWarning) log(result.creditsWarning);
|
|
104
|
-
if (
|
|
119
|
+
if (result?.mediaWarning) log(context.verbose ? result.mediaWarning : 'Warning: some media tools are unavailable. Update the API before media work.');
|
|
120
|
+
if (result?.referenceWarning) log(context.verbose ? result.referenceWarning : 'Warning: live editing reference unavailable. Update the API.');
|
|
121
|
+
if (context.verbose && client === 'codex') log(scope === 'global'
|
|
105
122
|
? 'Codex: global config is visible from every project (CODEX_HOME is respected). Check with codex mcp list, then /mcp in a new session.'
|
|
106
123
|
: 'Codex loads .codex/config.toml only in trusted projects. Trust the project yourself or rerun with --scope global.');
|
|
107
|
-
if (client === '
|
|
108
|
-
|
|
124
|
+
if (client === 'codex' && scope === 'project') log('Codex: trust this project to load its MCP configuration.');
|
|
125
|
+
if (client === 'claude' && scope === 'project') log('Claude Code: approve project MCP settings if asked.');
|
|
126
|
+
if (context.verbose) log('Use connection_status to see Login required, Connection unavailable, or Connected. Client-owned MCP badges cannot be renamed by an API-key adapter.');
|
|
109
127
|
if (!values['no-launch'] && interactive && result && credentials && await ui.confirm({ message: `Start ${client} now?`, default: true })) {
|
|
110
128
|
if (local) return context.launch(client, undefined, { cwd, env, unkeyed: true });
|
|
111
129
|
return context.launch(client, credentials.key, { cwd, env });
|
|
112
130
|
}
|
|
113
|
-
log(local ? '
|
|
114
|
-
: '
|
|
131
|
+
log(local ? 'Next: open your agent. The local device token is loaded automatically.'
|
|
132
|
+
: 'Next: open your agent. Saved keys load automatically; use machinal set-key if login is required.');
|
|
115
133
|
return 0;
|
|
116
134
|
}
|