@awesomate/hosting-mcp
Version:
Awesomate MCP server — lets Claude manage your Awesomate WordPress hosting, plan, limits, n8n automations, and build Node/static apps + databases
235 lines (221 loc) • 10.9 kB
JavaScript
/**
* Which coding agent runs the Awesomate connect, and where each one reads its
* MCP registration and skills. Node 18 built-ins only: this file is copied
* into the user's skills folder beside bootstrap.mjs.
*
* Facts (31 Oct 2026, OpenAI's Codex docs and openai/codex source):
* - Codex registers MCP servers in $CODEX_HOME/config.toml (default
* ~/.codex/config.toml) as [mcp_servers.<name>] with command/args/env;
* startup_timeout_sec defaults to 10 s, too short for a first npx download.
* - Codex reads skills from ~/.agents/skills ($CODEX_HOME/skills is the
* deprecated location) and picks up new skills without a restart; a
* config.toml change needs one.
* - Codex sets CODEX_THREAD_ID, CODEX_SESSION_ID and CODEX_VERSION for shell
* commands, but an MCP server gets only HOME, PATH, USER and a few more plus
* its entry's own env, so the entry carries AWESOMATE_CLIENT=codex.
*/
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
export const SERVER_NAME = 'awesomate-hosting';
export function clientLabel(client) {
return client === 'codex' ? 'Codex' : 'Claude Code';
}
/** --client codex|claude|both (or --client=codex) wins; then the agent's own env markers; else Claude Code, as before. */
export function detectClients(argv, env) {
let flag = null;
const i = argv.indexOf('--client');
if (i >= 0) flag = String(argv[i + 1] ?? '');
const eq = argv.find((a) => typeof a === 'string' && a.startsWith('--client='));
if (eq) flag = eq.slice('--client='.length);
if (flag !== null) {
flag = flag.toLowerCase();
if (flag === 'codex') return { clients: ['codex'], source: 'flag' };
if (flag === 'claude' || flag === 'claude-code') return { clients: ['claude'], source: 'flag' };
if (flag === 'both') return { clients: ['claude', 'codex'], source: 'flag' };
throw new Error(`--client must be codex, claude or both (got "${flag}")`);
}
const codex = Boolean(env.CODEX_THREAD_ID || env.CODEX_SESSION_ID || env.CODEX_VERSION);
const claude = Boolean(env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT);
if (codex && claude) return { clients: ['claude', 'codex'], source: 'env' };
if (codex) return { clients: ['codex'], source: 'env' };
return { clients: ['claude'], source: claude ? 'env' : 'default' };
}
export function codexHome(env, home) {
return env.CODEX_HOME || join(home, '.codex');
}
export function skillsDirFor(client, home) {
return client === 'codex' ? join(home, '.agents', 'skills') : join(home, '.claude', 'skills');
}
/** The one file a Codex copy must not rewrite: it holds the rewrite itself. */
export const NOT_REWRITTEN = 'agent-clients.mjs';
/** Skill text names ~/.claude/skills paths; a Codex copy names its own folder. */
export function rewriteForCodex(text) {
return text
.replaceAll('~/.claude/skills', '~/.agents/skills')
.replaceAll('$HOME/.claude/skills', '$HOME/.agents/skills')
.replaceAll("join(homedir(), '.claude', 'skills'", "join(homedir(), '.agents', 'skills'")
.replaceAll("join(HOME, '.claude', 'skills'", "join(HOME, '.agents', 'skills'");
}
const tomlString = (s) => JSON.stringify(String(s));
/**
* Our entry. keptMain: the owner's other keys on the entry (enabled,
* tool_timeout_sec, ...); keptEnv: their own env keys; keptTables: sub-tables
* such as [mcp_servers.awesomate-hosting.tools.x], all kept as written.
*/
export function codexEntryToml(entry, { keptMain = [], keptEnvLead = [], keptEnv = [], keptTables = [] } = {}) {
const hasTimeout = keptMain.some((l) => /^\s*startup_timeout_sec\s*=/.test(l));
return [
`[mcp_servers.${SERVER_NAME}]`,
`command = ${tomlString(entry.command)}`,
`args = [${entry.args.map(tomlString).join(', ')}]`,
...(hasTimeout ? [] : ['startup_timeout_sec = 60']),
...keptMain,
'',
...keptEnvLead,
`[mcp_servers.${SERVER_NAME}.env]`,
'AWESOMATE_CLIENT = "codex"',
...keptEnv,
'',
...(keptTables.length ? [...keptTables, ''] : []),
].join('\n');
}
const NAME = `(?:"${SERVER_NAME}"|'${SERVER_NAME}'|${SERVER_NAME})`;
const OUR_HEADER = new RegExp(`^\\s*\\[\\s*mcp_servers\\s*\\.\\s*${NAME}\\s*(\\.[^\\]]*)?\\]\\s*(#.*)?$`);
const OUR_MAIN_HEADER = new RegExp(`^\\s*\\[\\s*mcp_servers\\s*\\.\\s*${NAME}\\s*\\]\\s*(#.*)?$`);
const OUR_ENV_HEADER = new RegExp(`^\\s*\\[\\s*mcp_servers\\s*\\.\\s*${NAME}\\s*\\.\\s*env\\s*\\]\\s*(#.*)?$`);
const ANY_HEADER = /^\s*\[/;
const KEY = /^\s*(["']?)([A-Za-z0-9_-]+)\1\s*=/;
// Keys this script owns on the entry; the owner's own value for any other key stays.
const OURS_IN_MAIN = new Set(['command', 'args']);
/**
* Put exactly one Awesomate entry (no token in it) into config.toml text.
* command and args become ours; AWESOMATE_PAT is dropped; everything else the
* owner set on the entry, and everything else in the file, is kept. A form this
* cannot edit safely (an inline table, dotted keys, an inline env) is refused
* rather than duplicated.
*/
export function upsertCodexEntry(text, entry) {
const lines = text.split(/\r?\n/);
const kept = [];
const keptMain = [];
const keptEnv = [];
const keptEnvLead = [];
const keptTables = [];
let section = 'root'; // root | mcp_servers | main | env | sub | other
let found = false;
let hadToken = false;
let skippingArray = false;
// Comment lines inside our entry that touch the next table's header belong to that table.
let pendingComments = [];
const flushComments = () => {
for (const c of pendingComments) {
if (section === 'main') keptMain.push(c.trim());
else if (section === 'env') keptEnv.push(c.trim());
else if (section === 'sub') keptTables.push(c);
}
pendingComments = [];
};
const refuse = () => {
throw new Error(`config.toml defines ${SERVER_NAME} in a form this script will not rewrite`);
};
for (const line of lines) {
if (skippingArray) {
if (line.includes(']')) skippingArray = false;
continue;
}
if (ANY_HEADER.test(line)) {
// A comment touching a header goes with that header: ours (re-written below it) or the next table's.
if (OUR_ENV_HEADER.test(line)) { keptEnvLead.push(...pendingComments); pendingComments = []; }
else if (OUR_HEADER.test(line) && !OUR_MAIN_HEADER.test(line)) { keptTables.push(...pendingComments); pendingComments = []; }
else if (OUR_MAIN_HEADER.test(line)) flushComments();
else { kept.push(...pendingComments); pendingComments = []; }
if (OUR_MAIN_HEADER.test(line)) { section = 'main'; found = true; continue; }
if (OUR_ENV_HEADER.test(line)) { section = 'env'; found = true; continue; }
if (OUR_HEADER.test(line)) { section = 'sub'; found = true; keptTables.push(line); continue; }
section = /^\s*\[\s*mcp_servers\s*\]/.test(line) ? 'mcp_servers' : 'other';
kept.push(line);
continue;
}
if ((section === 'main' || section === 'env' || section === 'sub') && /^\s*#/.test(line)) {
pendingComments.push(line);
continue;
}
if (section === 'main' || section === 'env' || section === 'sub') flushComments();
// Dotted or inline forms of our entry, only where they would define it.
if (
(section === 'root' && new RegExp(`^\\s*mcp_servers\\s*(\\.\\s*${NAME}\\s*[.=]|=.*${SERVER_NAME})`).test(line)) ||
(section === 'mcp_servers' && new RegExp(`^\\s*${NAME}\\s*[.=]`).test(line))
) {
refuse();
}
if (section === 'main') {
const key = KEY.exec(line)?.[2];
if (key === 'env') {
if (/AWESOMATE_PAT/.test(line)) { hadToken = true; continue; }
refuse();
}
if (key && OURS_IN_MAIN.has(key)) {
// A multi-line array: skip its continuation lines too.
const value = line.slice(line.indexOf('=') + 1);
if (value.includes('[') && !value.includes(']')) skippingArray = true;
continue;
}
if (line.trim()) keptMain.push(line.trim());
continue;
}
if (section === 'env') {
if (/AWESOMATE_PAT/.test(line)) { hadToken = true; continue; }
const key = KEY.exec(line)?.[2];
if (key && key !== 'AWESOMATE_CLIENT') keptEnv.push(line.trim());
continue;
}
if (section === 'sub') {
if (line.trim()) keptTables.push(line);
continue;
}
kept.push(line);
}
flushComments();
while (kept.length && kept[kept.length - 1].trim() === '') kept.pop();
const body = kept.length ? `${kept.join('\n')}\n\n` : '';
return { text: `${body}${codexEntryToml(entry, { keptMain, keptEnvLead, keptEnv, keptTables })}`, found, hadToken };
}
/** Write the Codex registration, read it back, and say what happened. */
export function ensureCodexRegistration({ env, home, entry, log = console.log }) {
const path = join(codexHome(env, home), 'config.toml');
const exists = existsSync(path);
const before = exists ? readFileSync(path, 'utf8') : '';
const upserted = upsertCodexEntry(before, entry);
const { found, hadToken } = upserted;
// Keep the file's own line endings: a CRLF file stays CRLF.
const crlf = (before.match(/\r\n/g) ?? []).length > (before.match(/(?<!\r)\n/g) ?? []).length;
const text = crlf ? upserted.text.replace(/\r?\n/g, '\r\n') : upserted.text;
if (text === before) {
log(`✓ MCP server already registered for Codex in ${path}.`);
return { path, changed: false };
}
// Refuse before touching the file: our own output must read back as our entry and change nothing.
const selfCheck = (candidate) => {
const again = upsertCodexEntry(candidate, entry);
return again.found && (crlf ? again.text.replace(/\r?\n/g, '\r\n') : again.text) === candidate;
};
if (!selfCheck(text)) throw new Error(`the ${SERVER_NAME} entry for ${path} did not check out before writing; nothing was changed`);
mkdirSync(dirname(path), { recursive: true });
// Keep the file's own mode: config.toml can hold other servers' keys.
const mode = exists ? statSync(path).mode & 0o777 : 0o600;
const tmp = `${path}.tmp-${process.pid}`;
writeFileSync(tmp, text, { mode });
chmodSync(tmp, mode);
renameSync(tmp, path);
// Read-back: the file on disk is exactly what was written; if not, put the original back.
if (readFileSync(path, 'utf8') !== text) {
try { if (exists) writeFileSync(path, before, { mode }); else rmSync(path, { force: true }); } catch { /* best effort */ }
throw new Error(`wrote ${path} but the ${SERVER_NAME} entry did not verify on read-back; the original was put back`);
}
log(
hadToken
? `✓ Replaced the Codex registration in ${path} (it had a token in its env) with one that has none.`
: `✓ ${found ? 'Updated' : 'Registered'} the Awesomate MCP server for Codex in ${path} (no token in it: the folder pin picks the account).`,
);
return { path, changed: true };
}