@machinal/mcp 0.4.2 → 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.
@@ -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('Independent local mode: your OpenRouter key and local disk/compute. No Machinal account, subscription, credits or PocketBase.');
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 saved = await saveConfiguration(plan);
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 (client === 'codex') log(scope === 'global'
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 === 'claude') log('Claude Code: approve project MCP settings if asked. Check with claude mcp get machinal or /mcp.');
108
- log('Use connection_status to see Login required, Connection unavailable, or Connected. Client-owned MCP badges cannot be renamed by an API-key adapter.');
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 ? 'Open the client normally. The adapter reads the generated local device token; no Machinal login is used.'
114
- : 'Open the client normally. Saved Windows keys are loaded by the adapter; otherwise provide MACHINAL_API_KEY in its environment or use machinal-mcp launch.');
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
  }
@@ -2,6 +2,7 @@ import { lookup } from 'node:dns/promises';
2
2
  import http from 'node:http';
3
3
  import https from 'node:https';
4
4
  import { BlockList, isIP } from 'node:net';
5
+ import { pipeline } from 'node:stream/promises';
5
6
 
6
7
  export class TransferError extends Error {}
7
8
 
@@ -58,15 +59,30 @@ export function requestTransfer(value, { trustedOrigin, signal, method = 'GET',
58
59
  const url = transferURL(value, trustedOrigin);
59
60
  const transport = url.protocol === 'https:' ? https : http;
60
61
  return new Promise((resolve, reject) => {
62
+ let responded = false;
61
63
  const request = transport.request(url, {
62
64
  method, headers, signal, agent: false,
63
65
  ...(url.origin === trustedOrigin ? {} : { lookup: publicLookup() }),
64
- }, (response) => { clearTimeout(deadline); resolve(response); });
65
- const deadline = setTimeout(() => request.destroy(new TransferError('The download server did not respond within 15 seconds.')), 15_000);
66
- deadline.unref?.();
66
+ }, (response) => { responded = true; clearTimeout(deadline); resolve(response); });
67
+ let deadline;
68
+ const armDeadline = () => {
69
+ clearTimeout(deadline);
70
+ if (responded) return;
71
+ deadline = setTimeout(() => request.destroy(new TransferError('The transfer server did not respond within 15 seconds.')), 15_000);
72
+ deadline.unref?.();
73
+ };
74
+ armDeadline();
75
+ const streaming = body && typeof body[Symbol.asyncIterator] === 'function';
76
+ if (streaming) {
77
+ request.once('socket', socket => {
78
+ socket.once(url.protocol === 'https:' ? 'secureConnect' : 'connect', () => clearTimeout(deadline));
79
+ });
80
+ request.once('finish', armDeadline);
81
+ }
67
82
  request.setTimeout(30_000, () => request.destroy(new TransferError('The download connection stalled for 30 seconds.')));
68
83
  request.once('error', (error) => { clearTimeout(deadline); reject(error); });
69
- if (body) request.end(body);
84
+ if (streaming) void pipeline(body, request, { signal }).catch(error => request.destroy(error));
85
+ else if (body) request.end(body);
70
86
  else request.end();
71
87
  });
72
88
  }
package/src/upload.mjs ADDED
@@ -0,0 +1,96 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { lstat, open, realpath } from 'node:fs/promises';
4
+ import { basename, extname, isAbsolute, relative, resolve } from 'node:path';
5
+ import { downloadFilename } from './download.mjs';
6
+ import { readTransferJSON, requestTransfer, TransferError } from './transfer-http.mjs';
7
+
8
+ export const MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024;
9
+ const extensions = new Set('mp4 mov mkv webm avi m4v png jpg jpeg webp gif bmp mp3 wav m4a aac ogg flac glb'.split(' '));
10
+
11
+ export function validateUpload(input) {
12
+ if (input.userApproved !== true) throw new TransferError('Ask for approval to upload the exact named local files to this project first. Listing consent is insufficient.');
13
+ if (!/^[a-z\d_-]{1,64}$/i.test(input.projectId ?? '')) throw new TransferError('Use a projectId returned by list_projects or create_project.');
14
+ if (!Array.isArray(input.files) || !input.files.length || input.files.length > 100) throw new TransferError('Choose 1–100 exact local media files, not a folder or glob.');
15
+ for (const path of input.files) {
16
+ if (typeof path !== 'string' || !isAbsolute(path) || /[\x00-\x1f\x7f]/.test(path)
17
+ || !extensions.has(extname(path).slice(1).toLowerCase())) {
18
+ throw new TransferError('Use absolute client-local paths to supported images, video, audio or GLB files; no URLs, directories, secrets or recipes.');
19
+ }
20
+ downloadFilename(basename(path));
21
+ }
22
+ if (new Set(input.files.map(path => resolve(path))).size !== input.files.length) throw new TransferError('Select each local file only once.');
23
+ }
24
+
25
+ function sameFile(a, b) {
26
+ return a.isFile() && b.isFile() && a.ino === b.ino && a.dev === b.dev
27
+ && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
28
+ }
29
+
30
+ export async function inspectUpload(path) {
31
+ const info = await lstat(path);
32
+ if (!info.isFile() || info.isSymbolicLink() || relative(resolve(path), await realpath(path))) {
33
+ throw new TransferError('Upload only regular files at their real approved paths, not symbolic links, linked folders or directories.');
34
+ }
35
+ const extension = extname(path).toLowerCase();
36
+ const limit = extension === '.glb' ? 4 * 1024 * 1024 : MAX_UPLOAD_BYTES;
37
+ if (!Number.isSafeInteger(info.size) || info.size < 1 || info.size > limit) {
38
+ throw new TransferError(extension === '.glb' ? 'GLB uploads must be nonempty and at most 4 MiB.' : 'Uploads must be nonempty and at most 2 GiB.');
39
+ }
40
+ return { path, info, file: `upload-${randomUUID()}${extension}` };
41
+ }
42
+
43
+ async function* multipart(source, handle, header, footer, hash, signal, progress, state) {
44
+ yield header;
45
+ let bytes = 0;
46
+ let lastProgress = Date.now();
47
+ for await (const chunk of handle.createReadStream({ autoClose: false, start: 0, end: source.info.size - 1, signal })) {
48
+ signal?.throwIfAborted();
49
+ bytes += chunk.length;
50
+ hash.update(chunk);
51
+ if (Date.now() - lastProgress >= 1000) {
52
+ lastProgress = Date.now();
53
+ await progress({ status: 'Uploading', bytes, totalBytes: source.info.size });
54
+ }
55
+ yield chunk;
56
+ }
57
+ if (bytes !== source.info.size || !sameFile(source.info, await handle.stat())) throw new TransferError('The local source changed during upload. Recover the attempted remote filename before retrying.');
58
+ yield footer;
59
+ state.completed = true;
60
+ }
61
+
62
+ export async function uploadFile(source, { connection, projectId, signal, progress = async () => {}, request = requestTransfer }) {
63
+ const controller = new AbortController();
64
+ const combined = AbortSignal.any([signal, controller.signal].filter(Boolean));
65
+ const handle = await open(source.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
66
+ let response;
67
+ let body;
68
+ try {
69
+ if (!sameFile(source.info, await handle.stat()) || relative(resolve(source.path), await realpath(source.path))) throw new TransferError('The local source changed after approval. No file was uploaded.');
70
+ const boundary = `machinal-${randomUUID()}`;
71
+ const header = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${source.file}"\r\nContent-Type: application/octet-stream\r\n\r\n`);
72
+ const footer = Buffer.from(`\r\n--${boundary}--\r\n`);
73
+ const hash = createHash('sha256');
74
+ const state = { completed: false };
75
+ body = multipart(source, handle, header, footer, hash, combined, progress, state);
76
+ const origin = new URL(connection.endpoint).origin;
77
+ response = await request(new URL(`/v1/projects/${projectId}/upload`, origin), {
78
+ trustedOrigin: origin, signal: combined, method: 'POST', body,
79
+ headers: { Authorization: `Bearer ${connection.key}`, Accept: 'application/json',
80
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`, 'Content-Length': header.length + source.info.size + footer.length },
81
+ });
82
+ if (response.statusCode < 200 || response.statusCode >= 300) {
83
+ throw new TransferError(`Upload failed (HTTP ${response.statusCode}). Redirects are refused; no credentials were forwarded. Do not automatically retry uploads.`);
84
+ }
85
+ const receipt = await readTransferJSON(response);
86
+ if (!state.completed || receipt.file !== source.file || receipt.bytes !== source.info.size || receipt.storage !== 'volume') {
87
+ throw new TransferError('The API returned an invalid upload receipt. Recover the attempted remote filename before retrying.');
88
+ }
89
+ return { path: source.path, file: source.file, bytes: receipt.bytes, storage: 'volume', sha256: hash.digest('hex') };
90
+ } finally {
91
+ controller.abort();
92
+ response?.destroy();
93
+ await body?.return();
94
+ await handle.close();
95
+ }
96
+ }