@roxyon/mcp 0.3.0 → 0.5.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.
@@ -0,0 +1,1445 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/server.ts
4
+ import { createRequire } from "module";
5
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
+
7
+ // src/baas-tools.ts
8
+ import { readFile } from "fs/promises";
9
+ import { join, resolve } from "path";
10
+ import { BAAS_MAX_BATCH, BAAS_MAX_PAGE, BaasDataApi, parseEnv } from "@roxyon/api-client";
11
+ import { z } from "zod";
12
+
13
+ // src/context.ts
14
+ import { AsyncLocalStorage } from "async_hooks";
15
+ var storage = new AsyncLocalStorage();
16
+ function runWithContext(ctx, fn) {
17
+ return storage.run(ctx, fn);
18
+ }
19
+ function currentContext() {
20
+ return storage.getStore() ?? {};
21
+ }
22
+
23
+ // src/session.ts
24
+ import { Roxyon, isAuthError } from "@roxyon/api-client";
25
+ import { endpointsFromEnv, loadCredentials, tokenFromEnv } from "@roxyon/deploy-core";
26
+ var NotAuthenticatedError = class extends Error {
27
+ constructor() {
28
+ super(
29
+ "Not signed in to Roxyon. Run `roxyon login` in a terminal, or set ROXYON_TOKEN in this MCP server's environment."
30
+ );
31
+ this.name = "NotAuthenticatedError";
32
+ }
33
+ };
34
+ async function getSession() {
35
+ const { apiUrl, consoleUrl } = endpointsFromEnv();
36
+ const requestToken = currentContext().token;
37
+ if (requestToken) {
38
+ return {
39
+ roxyon: new Roxyon({ sessionToken: requestToken, baseUrl: apiUrl, consoleUrl }),
40
+ source: "oauth"
41
+ };
42
+ }
43
+ const envToken = tokenFromEnv();
44
+ if (envToken) {
45
+ return {
46
+ roxyon: new Roxyon({ sessionToken: envToken, baseUrl: apiUrl, consoleUrl }),
47
+ source: "env-token"
48
+ };
49
+ }
50
+ const creds = await loadCredentials();
51
+ if (!creds?.sessionToken) throw new NotAuthenticatedError();
52
+ return {
53
+ roxyon: new Roxyon({ sessionToken: creds.sessionToken, baseUrl: apiUrl, consoleUrl }),
54
+ preferredSubscription: creds.subscription,
55
+ source: "stored-login"
56
+ };
57
+ }
58
+ function isSessionGone(err) {
59
+ return err instanceof NotAuthenticatedError || isAuthError(err);
60
+ }
61
+
62
+ // src/result.ts
63
+ function text(body, structured) {
64
+ return {
65
+ content: [{ type: "text", text: body }],
66
+ ...structured ? { structuredContent: structured } : {}
67
+ };
68
+ }
69
+ function errorResult(message, structured) {
70
+ return {
71
+ content: [{ type: "text", text: message }],
72
+ ...structured ? { structuredContent: structured } : {},
73
+ isError: true
74
+ };
75
+ }
76
+ async function guard(fn) {
77
+ try {
78
+ return await fn();
79
+ } catch (err) {
80
+ if (isSessionGone(err)) {
81
+ return errorResult(
82
+ err.message || "Roxyon session expired \u2014 run `roxyon login` again, or refresh ROXYON_TOKEN."
83
+ );
84
+ }
85
+ return errorResult(err instanceof Error ? err.message : String(err));
86
+ }
87
+ }
88
+
89
+ // src/baas-tools.ts
90
+ var MAX_TEXT = 4e4;
91
+ var dirArg = z.string().optional().describe("Project directory whose .env holds RX_SECRET_KEY. Defaults to cwd.");
92
+ function remoteBlock() {
93
+ if (!currentContext().remote) return null;
94
+ return errorResult(
95
+ "The roxyon_baas_* tools read your app secret key from your local project .env, so they only run in the local MCP server (`npx -y @roxyon/mcp`). Manage data in the hosted connector via the console's Roxyon Base panel for now."
96
+ );
97
+ }
98
+ async function baasFor(dir) {
99
+ const root = resolve(dir ?? process.cwd());
100
+ let fileEnv = {};
101
+ try {
102
+ fileEnv = parseEnv(await readFile(join(root, ".env"), "utf8"));
103
+ } catch {
104
+ }
105
+ const secretKey = fileEnv.RX_SECRET_KEY || process.env.RX_SECRET_KEY || "";
106
+ if (!secretKey) {
107
+ throw new Error(
108
+ `No BaaS V2 secret key found. Put RX_SECRET_KEY=rxsk_\u2026 in ${join(root, ".env")} (console.roxyon.com \u2192 Roxyon Base \u2192 your project \u2192 API keys). Keep it out of git and out of browser code.`
109
+ );
110
+ }
111
+ return new BaasDataApi({ secretKey });
112
+ }
113
+ function clip(s) {
114
+ return s.length > MAX_TEXT ? `${s.slice(0, MAX_TEXT)}
115
+ \u2026 (truncated \u2014 narrow with fields/where/limit)` : s;
116
+ }
117
+ function dryRun(what) {
118
+ return text(`Would ${what}. Pass confirm:true to do it.`, { dryRun: true });
119
+ }
120
+ var SERVER_SCOPE = "Runs as the app backend (server scope, which passes every class rule). Local MCP only.";
121
+ function registerBaasTools(server) {
122
+ server.registerTool(
123
+ "roxyon_baas_query",
124
+ {
125
+ title: "Roxyon BaaS: query records",
126
+ description: `Read records of a class in the project's own app on BaaS V2. \`where\` is an object like {"Status":"active","Age":{"gt":18}}; for \`in\`, pass a comma-joined string. \`fields\` defaults to "*"; built-in meta columns must be named. Up to ${BAAS_MAX_PAGE} rows a page (use skip to page). ${SERVER_SCOPE}`,
127
+ inputSchema: {
128
+ dir: dirArg,
129
+ class: z.string(),
130
+ where: z.record(z.any()).optional(),
131
+ fields: z.string().optional(),
132
+ order: z.string().optional().describe('e.g. "-createdAt"'),
133
+ limit: z.number().int().min(1).max(BAAS_MAX_PAGE).optional(),
134
+ skip: z.number().int().min(0).optional(),
135
+ count: z.boolean().optional().describe("Also return the total number of matches.")
136
+ }
137
+ },
138
+ (args) => guard(async () => {
139
+ const blocked = remoteBlock();
140
+ if (blocked) return blocked;
141
+ const api = await baasFor(args.dir);
142
+ const { rows, count } = await api.query(args.class, {
143
+ where: args.where,
144
+ fields: args.fields,
145
+ order: args.order,
146
+ limit: args.limit,
147
+ skip: args.skip,
148
+ count: args.count
149
+ });
150
+ const head = `${rows.length} row(s)${count !== void 0 ? ` of ${count}` : ""}`;
151
+ return text(clip(`${head}
152
+ ${JSON.stringify(rows, null, 2)}`), { rows, count });
153
+ })
154
+ );
155
+ server.registerTool(
156
+ "roxyon_baas_get",
157
+ {
158
+ title: "Roxyon BaaS: read one record",
159
+ description: `Read one record by objectId. ${SERVER_SCOPE}`,
160
+ inputSchema: { dir: dirArg, class: z.string(), objectId: z.string() }
161
+ },
162
+ (args) => guard(async () => {
163
+ const blocked = remoteBlock();
164
+ if (blocked) return blocked;
165
+ const api = await baasFor(args.dir);
166
+ const row = await api.get(args.class, args.objectId);
167
+ return text(clip(JSON.stringify(row, null, 2)), { row });
168
+ })
169
+ );
170
+ server.registerTool(
171
+ "roxyon_baas_create",
172
+ {
173
+ title: "Roxyon BaaS: create a record",
174
+ description: `Insert one record into an existing class (V2 has no schema changes with a secret key: add classes and columns in the console). For relations store the other row's objectId in a string column. Needs confirm:true. ${SERVER_SCOPE}`,
175
+ inputSchema: {
176
+ dir: dirArg,
177
+ class: z.string(),
178
+ data: z.record(z.any()),
179
+ confirm: z.boolean().optional()
180
+ }
181
+ },
182
+ (args) => guard(async () => {
183
+ const blocked = remoteBlock();
184
+ if (blocked) return blocked;
185
+ if (!args.confirm) return dryRun(`insert into ${args.class}: ${JSON.stringify(args.data)}`);
186
+ const api = await baasFor(args.dir);
187
+ const row = await api.create(args.class, args.data);
188
+ return text(`\u2713 Created ${args.class} ${String(row.objectId ?? "")}.`, { ok: true, row });
189
+ })
190
+ );
191
+ server.registerTool(
192
+ "roxyon_baas_update",
193
+ {
194
+ title: "Roxyon BaaS: update a record",
195
+ description: `Set fields on one record by objectId. Needs confirm:true. ${SERVER_SCOPE}`,
196
+ inputSchema: {
197
+ dir: dirArg,
198
+ class: z.string(),
199
+ objectId: z.string(),
200
+ data: z.record(z.any()),
201
+ confirm: z.boolean().optional()
202
+ }
203
+ },
204
+ (args) => guard(async () => {
205
+ const blocked = remoteBlock();
206
+ if (blocked) return blocked;
207
+ if (!args.confirm) {
208
+ return dryRun(`update ${args.class} ${args.objectId}: ${JSON.stringify(args.data)}`);
209
+ }
210
+ const api = await baasFor(args.dir);
211
+ const row = await api.update(args.class, args.objectId, args.data);
212
+ return text(`\u2713 Updated ${args.class} ${args.objectId}.`, { ok: true, row });
213
+ })
214
+ );
215
+ server.registerTool(
216
+ "roxyon_baas_delete",
217
+ {
218
+ title: "Roxyon BaaS: delete a record",
219
+ description: `Delete one record by objectId. Needs confirm:true. ${SERVER_SCOPE}`,
220
+ inputSchema: {
221
+ dir: dirArg,
222
+ class: z.string(),
223
+ objectId: z.string(),
224
+ confirm: z.boolean().optional()
225
+ }
226
+ },
227
+ (args) => guard(async () => {
228
+ const blocked = remoteBlock();
229
+ if (blocked) return blocked;
230
+ if (!args.confirm) return dryRun(`delete ${args.class} ${args.objectId}`);
231
+ const api = await baasFor(args.dir);
232
+ await api.delete(args.class, args.objectId);
233
+ return text(`\u2713 Deleted ${args.class} ${args.objectId}.`, { ok: true });
234
+ })
235
+ );
236
+ server.registerTool(
237
+ "roxyon_baas_batch",
238
+ {
239
+ title: "Roxyon BaaS: batch of record requests",
240
+ description: `1 to ${BAAS_MAX_BATCH} record requests in one call, each answered on its own (one failing doesn't stop the others). path is /Class or /Class/<objectId>; for POST/PUT the body is {"data":{...}}; for GET the body holds query options (where, fields, limit\u2026). A batch with any write needs confirm:true. ${SERVER_SCOPE}`,
241
+ inputSchema: {
242
+ dir: dirArg,
243
+ requests: z.array(
244
+ z.object({
245
+ method: z.enum(["GET", "POST", "PUT", "DELETE"]),
246
+ path: z.string(),
247
+ body: z.record(z.any()).optional()
248
+ })
249
+ ).min(1).max(BAAS_MAX_BATCH),
250
+ confirm: z.boolean().optional()
251
+ }
252
+ },
253
+ (args) => guard(async () => {
254
+ const blocked = remoteBlock();
255
+ if (blocked) return blocked;
256
+ const writes = args.requests.filter((r) => r.method !== "GET");
257
+ if (writes.length && !args.confirm) {
258
+ return dryRun(
259
+ `run ${args.requests.length} request(s), ${writes.length} of them writes: ${writes.map((r) => `${r.method} ${r.path}`).join(", ")}`
260
+ );
261
+ }
262
+ const api = await baasFor(args.dir);
263
+ const results = await api.batch(args.requests);
264
+ const failed = results.filter((r) => r.ok === false).length;
265
+ return text(
266
+ clip(
267
+ `${results.length} answer(s), ${failed} failed
268
+ ${JSON.stringify(results, null, 2)}`
269
+ ),
270
+ { results }
271
+ );
272
+ })
273
+ );
274
+ }
275
+
276
+ // src/commerce-tools.ts
277
+ import { BILLING_CYCLES, Roxyon as Roxyon2 } from "@roxyon/api-client";
278
+ import { endpointsFromEnv as endpointsFromEnv2 } from "@roxyon/deploy-core";
279
+ import { z as z2 } from "zod";
280
+ function publicRoxyon() {
281
+ const { apiUrl, consoleUrl } = endpointsFromEnv2();
282
+ return new Roxyon2({ baseUrl: apiUrl, consoleUrl });
283
+ }
284
+ function money(n) {
285
+ return n === void 0 ? "\u2014" : `$${n.toFixed(2)}`;
286
+ }
287
+ function productLine(p) {
288
+ const spec = p.vcpu !== void 0 ? ` \u2014 ${p.vcpu} vCPU (${p.cpuType}), ${p.ramGb} GB RAM, ${p.diskGb} GB disk${p.ipv4Included ? `, ${p.ipv4Included} IPv4` : ""}` : "";
289
+ const prices = BILLING_CYCLES.filter((c) => p.pricesUSD[c] !== void 0).map((c) => `${c} ${money(p.pricesUSD[c])}`).join(", ");
290
+ return `- ${p.sku || p.planId} "${p.name}" [${p.category}]${spec} | USD ${prices}${p.stock === "out" ? " | OUT OF STOCK" : ""} (planId ${p.planId})`;
291
+ }
292
+ function registerCommerceTools(server) {
293
+ server.registerTool(
294
+ "roxyon_catalog",
295
+ {
296
+ title: "Roxyon: product catalog",
297
+ description: 'List what Roxyon sells: cloud servers (cloud.vps.launch / scale / power) and web hosting (cloud.hosting.solo / multiple / isolated). Each product has its planId (what roxyon_quote takes), SKU, specs (vCPU, RAM GB, disk GB, IPv4 included) for servers, list prices in USD per billing cycle BEFORE tax and currency conversion, and stock ("out" = cannot be ordered now). No sign-in needed. Use roxyon_quote for the exact amount a buyer would pay. Read-only.',
298
+ inputSchema: {
299
+ category: z2.string().optional().describe('Filter by category prefix, e.g. "cloud.vps" or "cloud.hosting".'),
300
+ in_stock_only: z2.boolean().optional()
301
+ }
302
+ },
303
+ (args) => guard(async () => {
304
+ let products = await publicRoxyon().billing.catalog();
305
+ if (args.category) products = products.filter((p) => p.category.startsWith(args.category));
306
+ if (args.in_stock_only) products = products.filter((p) => p.stock === "in");
307
+ return text(
308
+ products.length ? products.map(productLine).join("\n") : "(no products match)",
309
+ { products }
310
+ );
311
+ })
312
+ );
313
+ server.registerTool(
314
+ "roxyon_quote",
315
+ {
316
+ title: "Roxyon: price a new subscription",
317
+ description: "The exact amount Roxyon's checkout would charge for a NEW subscription to one plan, computed by the platform itself (same server pricing the console checkout uses, setup fee included): line items, subtotal, tax, total, in the requested currency. Pass the buyer currency and country: without them the quote is in USD with no tax, while checkout uses the account's own currency/country. No sign-in needed. Read-only: creates no order. Domains are not priced by this tool yet.",
318
+ inputSchema: {
319
+ plan: z2.string().describe('planId (or SKU, e.g. "SCALE-S") from roxyon_catalog.'),
320
+ cycle: z2.enum(BILLING_CYCLES),
321
+ currency: z2.string().length(3).optional().describe('ISO 4217, e.g. "USD", "SAR".'),
322
+ country: z2.string().length(2).optional().describe('ISO 3166 alpha-2, decides tax, e.g. "SA".')
323
+ }
324
+ },
325
+ (args) => guard(async () => {
326
+ const roxyon = publicRoxyon();
327
+ const want = args.plan.toLowerCase();
328
+ const product = (await roxyon.billing.catalog()).find(
329
+ (p) => p.planId === args.plan || p.sku.toLowerCase() === want
330
+ );
331
+ if (!product)
332
+ throw new Error(`No product "${args.plan}" in the catalog. See roxyon_catalog.`);
333
+ const q = await roxyon.billing.quote({
334
+ planId: product.planId,
335
+ cycle: args.cycle,
336
+ currency: args.currency,
337
+ country: args.country
338
+ });
339
+ const lines = [
340
+ ...q.lineItems.map((l) => `${l.label}: ${l.amount} ${q.currency}`),
341
+ `Subtotal: ${q.subtotal} ${q.currency}`,
342
+ `${q.taxLabel || "Tax"} (${q.taxRate}%): ${q.taxAmount} ${q.currency}`,
343
+ `Total: ${q.total} ${q.currency}`
344
+ ];
345
+ if (product?.stock === "out") lines.push("Note: this plan is out of stock right now.");
346
+ return text(lines.join("\n"), { quote: q });
347
+ })
348
+ );
349
+ server.registerTool(
350
+ "roxyon_list_subscriptions",
351
+ {
352
+ title: "Roxyon: my subscriptions (billing)",
353
+ description: "The signed-in user's own subscriptions with billing details: plan + SKU, status, billing cycle, recurring price and currency, next billing date, auto-renew, and for servers the state (building / running / stopped\u2026) and public IP. Only subscriptions the user owns. Read-only.",
354
+ inputSchema: {}
355
+ },
356
+ () => guard(async () => {
357
+ const session = await getSession();
358
+ const subs = await session.roxyon.billing.subscriptions();
359
+ const body = subs.length ? subs.map(
360
+ (s) => `- ${s.name || s.id} [${s.status}] ${s.plan}${s.sku ? ` (${s.sku})` : ""} \u2014 ${s.price} ${s.currency}/${s.cycle || "?"}, next billing ${s.nextBillingDate ?? "\u2014"}${s.autoRenew ? ", auto-renew" : ""}${s.serverState ? `, server ${s.serverState}` : ""}${s.publicIp ? ` ${s.publicIp}` : ""}`
361
+ ).join("\n") : "(no subscriptions on this account)";
362
+ return text(body, { subscriptions: subs });
363
+ })
364
+ );
365
+ server.registerTool(
366
+ "roxyon_list_invoices",
367
+ {
368
+ title: "Roxyon: my invoices",
369
+ description: "The signed-in user's own invoices, newest first: number, type, status (pending = unpaid, paid, overdue, void, failed, cancelled), total and currency, due date, and payUrl (the console page where the user pays; null when paid). Read-only: this never pays anything.",
370
+ inputSchema: {
371
+ status: z2.enum(["pending", "paid", "overdue", "void", "failed", "cancelled"]).optional(),
372
+ limit: z2.number().int().min(1).max(100).optional().describe("Default 25.")
373
+ }
374
+ },
375
+ (args) => guard(async () => {
376
+ const session = await getSession();
377
+ const invoices = await session.roxyon.billing.invoices({
378
+ status: args.status,
379
+ limit: args.limit
380
+ });
381
+ const body = invoices.length ? invoices.map(
382
+ (i) => `- #${i.number || i.id} ${i.type} [${i.status}] ${i.total} ${i.currency}, due ${i.dueDate ?? "\u2014"}${i.payUrl ? ` \u2014 pay at ${i.payUrl}` : ""}`
383
+ ).join("\n") : "(no invoices)";
384
+ return text(body, { invoices });
385
+ })
386
+ );
387
+ server.registerTool(
388
+ "roxyon_pay_link",
389
+ {
390
+ title: "Roxyon: where to pay an invoice",
391
+ description: 'The URL where the signed-in user pays one of their own open invoices (status pending, overdue or failed), plus its amount and due date. Give the invoice number (e.g. "INV2610055") or id from roxyon_list_invoices. A human opens the link and pays in the console; this tool never charges anything. Paid or void invoices have no link.',
392
+ inputSchema: {
393
+ invoice: z2.string().min(1).max(40).describe("Invoice number or id.")
394
+ }
395
+ },
396
+ (args) => guard(async () => {
397
+ const session = await getSession();
398
+ const want = args.invoice.replace(/^#/, "").toLowerCase();
399
+ const inv = (await session.roxyon.billing.invoices({ limit: 100 })).find(
400
+ (i) => i.id.toLowerCase() === want || i.number.toLowerCase() === want
401
+ );
402
+ if (!inv) {
403
+ throw new Error(
404
+ `No invoice "${args.invoice}" among your latest 100. See roxyon_list_invoices.`
405
+ );
406
+ }
407
+ if (!inv.payUrl) {
408
+ return text(`Invoice #${inv.number || inv.id} is ${inv.status}: nothing to pay.`, {
409
+ invoice: inv
410
+ });
411
+ }
412
+ return text(
413
+ `Invoice #${inv.number || inv.id}: ${inv.total} ${inv.currency}, due ${inv.dueDate ?? "\u2014"}.
414
+ Pay at ${inv.payUrl} (sign in, open Invoices, choose this invoice).`,
415
+ { invoice: inv, payUrl: inv.payUrl }
416
+ );
417
+ })
418
+ );
419
+ }
420
+
421
+ // src/prompts.ts
422
+ import { z as z3 } from "zod";
423
+ function registerPrompts(server) {
424
+ server.registerPrompt(
425
+ "scaffold-lumen-app",
426
+ {
427
+ title: "Scaffold a LumenJS + Roxyon app",
428
+ description: "Guidance for creating a new LumenJS SPA wired to the Roxyon BaaS and ready to deploy.",
429
+ argsSchema: {
430
+ idea: z3.string().describe("What the app should do."),
431
+ dir: z3.string().optional().describe("Where to create it.")
432
+ }
433
+ },
434
+ ({ idea, dir }) => ({
435
+ messages: [
436
+ {
437
+ role: "user",
438
+ content: {
439
+ type: "text",
440
+ text: `Build a LumenJS single-page app: ${idea}
441
+
442
+ Steps:
443
+ 1. Read the "roxyon://docs/lumenjs" resource \u2014 follow V1 rules exactly (one bind per region, no nested bind, build option lists in JS not :for, check every BaaS write for an error field).
444
+ 2. Read "roxyon://docs/baas" for the data/auth API.
445
+ 3. Scaffold with the LumenJS CLI 2.5.7: \`npx -y -p @lmjs/cli@2.5.7 lm create <name>\`${dir ? ` in ${dir}` : ""}. Put views under src/views/, wire the BaaS in src/index.js via config.json.
446
+ 4. When it runs locally (\`lm serve\`), call roxyon_init then roxyon_deploy (dry run first, then confirm:true).`
447
+ }
448
+ }
449
+ ]
450
+ })
451
+ );
452
+ server.registerPrompt(
453
+ "build-and-ship-site",
454
+ {
455
+ title: "Build a site and host it on Roxyon",
456
+ description: "Generate a static site (or no-build LumenJS SPA) in the conversation and publish it to a Roxyon host \u2014 for the hosted connector, no local files.",
457
+ argsSchema: {
458
+ brief: z3.string().describe("What the site should be."),
459
+ host: z3.string().describe("Where to host it, e.g. promo.mycompany.com")
460
+ }
461
+ },
462
+ ({ brief, host }) => ({
463
+ messages: [
464
+ {
465
+ role: "user",
466
+ content: {
467
+ type: "text",
468
+ text: `Build and publish a website to ${host}.
469
+
470
+ Brief: ${brief}
471
+
472
+ 1. Read "roxyon://docs/recipe" and follow it. (Read "roxyon://docs/lumenjs" too only if the site needs reactivity.)
473
+ 2. If ${host} is not already on the account, roxyon_add_domain { host: "${host}", confirm: true } (add spa:true only for a real single-page app).
474
+ 3. Generate the site \u2014 self-contained static files, relative paths, real .html per page or <page>/index.html, \u226460 files / 2 MB.
475
+ 4. roxyon_deploy_content { host: "${host}", files: [...], clean: true, confirm: true } (dry-run first).
476
+ 5. roxyon_list_files { host: "${host}" } to verify, then give me the URL. Note that HTTPS may take a couple of minutes on a brand-new host.`
477
+ }
478
+ }
479
+ ]
480
+ })
481
+ );
482
+ server.registerPrompt(
483
+ "install-wordpress",
484
+ {
485
+ title: "Install WordPress on Roxyon",
486
+ description: "Provision a host + database and install WordPress core \u2014 local/CLI MCP only.",
487
+ argsSchema: {
488
+ host: z3.string().describe("Where to install it, e.g. blog.mycompany.com")
489
+ }
490
+ },
491
+ ({ host }) => ({
492
+ messages: [
493
+ {
494
+ role: "user",
495
+ content: {
496
+ type: "text",
497
+ text: `Install WordPress on ${host}.
498
+
499
+ 1. Read "roxyon://docs/recipe-wordpress" and follow it.
500
+ 2. Call roxyon_install_wordpress { host: "${host}" } first without confirm to see the plan.
501
+ 3. If it looks right, call it again with confirm:true.
502
+ 4. Report the site URL and the database credentials (shown once \u2014 pass them on to me now), and tell me to visit the URL to finish WordPress's own setup wizard (site title, admin account).`
503
+ }
504
+ }
505
+ ]
506
+ })
507
+ );
508
+ server.registerPrompt(
509
+ "deploy-to-roxyon",
510
+ {
511
+ title: "Deploy this project to Roxyon",
512
+ description: "Walk through deploying the current project to Roxyon infrastructure.",
513
+ argsSchema: { dir: z3.string().describe("Absolute path to the project.") }
514
+ },
515
+ ({ dir }) => ({
516
+ messages: [
517
+ {
518
+ role: "user",
519
+ content: {
520
+ type: "text",
521
+ text: `Deploy the project at ${dir} to Roxyon.
522
+
523
+ 1. If there is no roxyon.json, call roxyon_init (it detects the runtime; ask me which host if there are several).
524
+ 2. Call roxyon_deploy with just the dir first to see the plan.
525
+ 3. If the plan looks right, call roxyon_deploy again with confirm:true.
526
+ 4. For an app runtime, report the final status and, if it failed, the last error from roxyon_app_status.`
527
+ }
528
+ }
529
+ ]
530
+ })
531
+ );
532
+ }
533
+
534
+ // src/resources.ts
535
+ import { readFile as readFile2 } from "fs/promises";
536
+ import { dirname, join as join2 } from "path";
537
+ import { fileURLToPath } from "url";
538
+ var RESOURCE_DIR = join2(dirname(fileURLToPath(import.meta.url)), "..", "resources");
539
+ var DOCS = [
540
+ {
541
+ uri: "roxyon://docs/lumenjs",
542
+ name: "lumenjs-reference",
543
+ file: "lumenjs.md",
544
+ title: "LumenJS \u2014 complete reference",
545
+ description: "Full LumenJS V1 reference for building SPAs with vanilla JS/HTML/CSS (no build step), contrasted with Vue/React. Read before writing .view files."
546
+ },
547
+ {
548
+ uri: "roxyon://docs/baas",
549
+ name: "baas-reference",
550
+ file: "baas.md",
551
+ title: "Roxyon BaaS reference",
552
+ description: "The Roxyon Backend-as-a-Service REST API: endpoints, auth flow, query rules, and the resolve-on-failure write behaviour."
553
+ },
554
+ {
555
+ uri: "roxyon://docs/deploy",
556
+ name: "deploy-reference",
557
+ file: "deploy.md",
558
+ title: "Deploying to Roxyon",
559
+ description: "How roxyon_init / roxyon_deploy work, the roxyon.json schema, static vs app deploys, env vars, and git push-to-deploy."
560
+ },
561
+ {
562
+ uri: "roxyon://docs/recipe",
563
+ name: "web-deploy-recipe",
564
+ file: "recipe-web-deploy.md",
565
+ title: "Recipe \u2014 build a site and host it",
566
+ description: 'The end-to-end flow for "build a landing page and put it on sub.mydomain.com" over the hosted connector: roxyon_add_domain \u2192 roxyon_deploy_content \u2192 roxyon_list_files.'
567
+ },
568
+ {
569
+ uri: "roxyon://docs/recipe-wordpress",
570
+ name: "wordpress-recipe",
571
+ file: "recipe-wordpress.md",
572
+ title: "Recipe \u2014 install WordPress",
573
+ description: 'The end-to-end flow for "put WordPress on sub.mydomain.com": roxyon_install_wordpress (host + database + WordPress core, one call). Local/CLI-backed MCP only.'
574
+ }
575
+ ];
576
+ function registerResources(server) {
577
+ for (const doc of DOCS) {
578
+ server.registerResource(
579
+ doc.name,
580
+ doc.uri,
581
+ { title: doc.title, description: doc.description, mimeType: "text/markdown" },
582
+ async () => {
583
+ const body = await readFile2(join2(RESOURCE_DIR, doc.file), "utf8");
584
+ return { contents: [{ uri: doc.uri, mimeType: "text/markdown", text: body }] };
585
+ }
586
+ );
587
+ }
588
+ }
589
+
590
+ // src/tools.ts
591
+ import { mkdtemp } from "fs/promises";
592
+ import { tmpdir } from "os";
593
+ import { join as join3 } from "path";
594
+ import { formatEnv } from "@roxyon/api-client";
595
+ import {
596
+ buildIgnore,
597
+ buildProjectConfig,
598
+ deployProject,
599
+ detectRuntime,
600
+ installWordPress,
601
+ listFiles,
602
+ loadProjectConfig,
603
+ packDirectory,
604
+ packFiles,
605
+ saveProjectConfig
606
+ } from "@roxyon/deploy-core";
607
+ import { z as z4 } from "zod";
608
+ var MAX_FILES = 60;
609
+ var MAX_FILE_BYTES = 1024 * 1024;
610
+ var MAX_TOTAL_BYTES = 2 * 1024 * 1024;
611
+ function remoteFilesystemBlock(tool) {
612
+ if (!currentContext().remote) return null;
613
+ return errorResult(
614
+ [
615
+ `${tool} needs access to your local project files, which the hosted Roxyon MCP`,
616
+ "server does not have. Either:",
617
+ " \u2022 run the `roxyon` CLI locally (`npm i -g @roxyon/cli`, then `roxyon deploy`), or",
618
+ " \u2022 use `roxyon_link_github` to connect a git repo for push-to-deploy, then",
619
+ " `roxyon_app_status` / `roxyon_logs` to watch it here."
620
+ ].join("\n")
621
+ );
622
+ }
623
+ async function resolveApp(args) {
624
+ if (args.application) return { applicationId: args.application };
625
+ if (args.dir) {
626
+ const cfg = await loadProjectConfig(args.dir);
627
+ if (cfg?.application) return { applicationId: cfg.application, host: cfg.host };
628
+ throw new Error(
629
+ `No application linked in ${args.dir}/roxyon.json. Deploy it once (roxyon_deploy) or pass "application".`
630
+ );
631
+ }
632
+ throw new Error('Pass either "application" (an id) or "dir" (a project directory).');
633
+ }
634
+ function accountContext(session) {
635
+ return session.roxyon.account.context();
636
+ }
637
+ function registerTools(server) {
638
+ server.registerTool(
639
+ "roxyon_whoami",
640
+ {
641
+ title: "Roxyon: who am I",
642
+ description: "Show the signed-in Roxyon user and their subscriptions (which one is active).",
643
+ inputSchema: {}
644
+ },
645
+ () => guard(async () => {
646
+ const session = await getSession();
647
+ const ctx = await accountContext(session);
648
+ const lines = [
649
+ `User: ${ctx.user.email || ctx.user.id} (${ctx.user.id})`,
650
+ `Auth: ${session.source}${ctx.scopes.length ? ` (scopes: ${ctx.scopes.join(", ")})` : ""}`,
651
+ "",
652
+ "Subscriptions:",
653
+ ...ctx.subscriptions.map((s) => ` ${s.name || s.id} \u2014 ${s.status || "?"}`),
654
+ "",
655
+ `Hosts: ${ctx.domains.map((d) => d.name).join(", ") || "(none)"}`
656
+ ];
657
+ return text(lines.join("\n"), {
658
+ user: ctx.user,
659
+ scopes: ctx.scopes,
660
+ subscriptions: ctx.subscriptions,
661
+ hosts: ctx.domains.map((d) => d.name)
662
+ });
663
+ })
664
+ );
665
+ server.registerTool(
666
+ "roxyon_list_domains",
667
+ {
668
+ title: "Roxyon: list hosts",
669
+ description: "List the domains (hosts) on the active subscription \u2014 the possible deploy targets.",
670
+ inputSchema: {}
671
+ },
672
+ () => guard(async () => {
673
+ const session = await getSession();
674
+ const { domains } = await accountContext(session);
675
+ return text(
676
+ domains.length ? domains.map(
677
+ (d) => `- ${d.name}${d.status && d.status !== "active" ? ` (${d.status})` : ""}`
678
+ ).join("\n") : "(no hosts on this account)",
679
+ { hosts: domains }
680
+ );
681
+ })
682
+ );
683
+ server.registerTool(
684
+ "roxyon_list_apps",
685
+ {
686
+ title: "Roxyon: list applications",
687
+ description: "List the applications on the active subscription with their status and revision.",
688
+ inputSchema: {}
689
+ },
690
+ () => guard(async () => {
691
+ const session = await getSession();
692
+ const apps = await session.roxyon.account.apps();
693
+ const body = apps.length ? apps.map(
694
+ (a) => `- ${a.name} [${a.id}] \u2014 ${a.status || "?"} (rev ${a.appliedRevision}/${a.configRevision})${a.repo ? ` \xB7 git:${a.repo.branch}` : ""}`
695
+ ).join("\n") : "(no applications)";
696
+ return text(body, { applications: apps });
697
+ })
698
+ );
699
+ server.registerTool(
700
+ "roxyon_init",
701
+ {
702
+ title: "Roxyon: initialise a project",
703
+ description: "Detect a project's type and write roxyon.json. Run this once per project before roxyon_deploy. Does not create anything on the platform.",
704
+ inputSchema: {
705
+ dir: z4.string().describe("Absolute path to the project directory."),
706
+ runtime: z4.enum(["lumen", "node", "python", "php"]).optional(),
707
+ host: z4.string().optional().describe("Deploy host (a domain on the subscription)."),
708
+ folder: z4.string().optional().describe('Sub-path under the host; "" = site root.'),
709
+ overwrite: z4.boolean().optional().describe("Replace an existing roxyon.json.")
710
+ }
711
+ },
712
+ (args) => guard(async () => {
713
+ const blocked = remoteFilesystemBlock("roxyon_init");
714
+ if (blocked) return blocked;
715
+ const session = await getSession();
716
+ const existing = await loadProjectConfig(args.dir);
717
+ if (existing && !args.overwrite) {
718
+ return errorResult(
719
+ `roxyon.json already exists in ${args.dir}. Pass overwrite:true to replace it.`,
720
+ { config: existing }
721
+ );
722
+ }
723
+ const { domains } = await accountContext(session);
724
+ if (domains.length === 0) {
725
+ return errorResult(
726
+ "This account has no hosts. Add a domain in the Roxyon console first."
727
+ );
728
+ }
729
+ const detected = await detectRuntime(args.dir);
730
+ const runtime = args.runtime ?? detected.runtime;
731
+ const host = args.host ?? domains[0].name;
732
+ if (!domains.some((d) => d.name === host)) {
733
+ return errorResult(
734
+ `Host "${host}" is not on this account (have: ${domains.map((d) => d.name).join(", ")}).`
735
+ );
736
+ }
737
+ const config = buildProjectConfig({
738
+ cwd: args.dir,
739
+ runtime,
740
+ host,
741
+ folder: args.folder,
742
+ start: detected.start
743
+ });
744
+ const path = await saveProjectConfig(config, args.dir);
745
+ return text(
746
+ `Wrote ${path}
747
+ Detected: ${detected.runtime} (${detected.reason})
748
+
749
+ ${JSON.stringify(config, null, 2)}`,
750
+ { path, detected: detected.runtime, config }
751
+ );
752
+ })
753
+ );
754
+ server.registerTool(
755
+ "roxyon_deploy",
756
+ {
757
+ title: "Roxyon: deploy a project",
758
+ description: 'Build (if configured) and deploy the project in "dir" to Roxyon. Without confirm:true this returns a dry-run plan (what would build, where it would go, how many files). With confirm:true it runs the build, uploads, and \u2014 for app runtimes \u2014 waits for it to go live. Requires roxyon.json (run roxyon_init first).',
759
+ inputSchema: {
760
+ dir: z4.string().describe("Absolute path to the project directory (must contain roxyon.json)."),
761
+ confirm: z4.boolean().optional().describe("Actually deploy. Omit for a dry-run plan."),
762
+ build: z4.boolean().optional().describe("Run the configured build command (default true)."),
763
+ follow: z4.boolean().optional().describe("For app runtimes, wait until running/failed (default true).")
764
+ }
765
+ },
766
+ (args) => guard(async () => {
767
+ const blocked = remoteFilesystemBlock("roxyon_deploy");
768
+ if (blocked) return blocked;
769
+ const session = await getSession();
770
+ const config = await loadProjectConfig(args.dir);
771
+ if (!config) {
772
+ return errorResult(`No roxyon.json in ${args.dir}. Run roxyon_init first.`);
773
+ }
774
+ if (!args.confirm) {
775
+ const ig = await buildIgnore(args.dir);
776
+ const packRoot = config.kind === "static" && config.outDir ? `${args.dir}/${config.outDir}` : args.dir;
777
+ let files = [];
778
+ try {
779
+ files = await listFiles(packRoot, ig);
780
+ } catch {
781
+ }
782
+ const plan = [
783
+ "DRY RUN \u2014 pass confirm:true to deploy.",
784
+ "",
785
+ `Project: ${config.name} (${config.runtime}, ${config.kind})`,
786
+ `Target: ${config.host}${config.folder ? `/${config.folder}` : ""}`,
787
+ config.build ? `Build: ${config.build}` : "Build: (none)",
788
+ config.kind === "app" ? `App: ${config.application ?? "(created on first deploy)"}` : "Serve: static files from the host document root",
789
+ files.length ? `Would pack ${files.length} file(s) from ${config.kind === "static" && config.outDir ? config.outDir : "."}` : `Would pack the build output (${config.outDir ?? "dist"}) after building`
790
+ ].join("\n");
791
+ return text(plan, { dryRun: true, config });
792
+ }
793
+ const logLines = [];
794
+ const outcome = await deployProject({
795
+ cwd: args.dir,
796
+ roxyon: session.roxyon,
797
+ preferredSubscription: session.preferredSubscription,
798
+ build: args.build,
799
+ follow: args.follow ?? true,
800
+ timeoutMs: 5 * 60 * 1e3,
801
+ reporter: {
802
+ step: (m) => logLines.push(`\xBB ${m}`),
803
+ log: (l) => logLines.push(` ${l}`)
804
+ }
805
+ });
806
+ const tail = logLines.slice(-60).join("\n");
807
+ if (outcome.kind === "static" && outcome.ok) {
808
+ return text(`${tail}
809
+
810
+ \u2713 Live: ${outcome.url} (${outcome.files} files)`, {
811
+ ok: true,
812
+ kind: "static",
813
+ url: outcome.url
814
+ });
815
+ }
816
+ if (outcome.kind === "app" && outcome.ok) {
817
+ return text(
818
+ `${tail}
819
+
820
+ \u2713 ${outcome.status === "running" ? `Live: ${outcome.url ?? outcome.application}` : `Build queued (revision ${outcome.revision})`}`,
821
+ {
822
+ ok: true,
823
+ kind: "app",
824
+ application: outcome.application,
825
+ status: outcome.status,
826
+ url: outcome.url
827
+ }
828
+ );
829
+ }
830
+ return errorResult(
831
+ `${tail}
832
+
833
+ \u2717 Deploy failed: ${"error" in outcome ? outcome.error : "unknown"}`,
834
+ { ok: false, application: "application" in outcome ? outcome.application : void 0 }
835
+ );
836
+ })
837
+ );
838
+ server.registerTool(
839
+ "roxyon_app_status",
840
+ {
841
+ title: "Roxyon: application status",
842
+ description: "Current status, revisions and last error for an application (by id or project dir).",
843
+ inputSchema: {
844
+ application: z4.string().optional(),
845
+ dir: z4.string().optional().describe("A project directory whose roxyon.json links an application.")
846
+ }
847
+ },
848
+ (args) => guard(async () => {
849
+ const session = await getSession();
850
+ const { applicationId } = await resolveApp(args);
851
+ const app = await session.roxyon.account.getApp(applicationId);
852
+ if (!app) return errorResult(`Application ${applicationId} not found.`);
853
+ const settled = app.configRevision <= app.appliedRevision;
854
+ const body = [
855
+ `${app.name} [${app.id}]`,
856
+ `Status: ${app.status || "?"}${settled ? "" : " (applying)"}`,
857
+ `Revision: ${app.appliedRevision} / ${app.configRevision}`,
858
+ `Runtime: ${app.runtime}`.trim(),
859
+ app.lastError ? `
860
+ Last error:
861
+ ${app.lastError}` : ""
862
+ ].filter(Boolean).join("\n");
863
+ return text(body, {
864
+ id: app.id,
865
+ status: app.status,
866
+ settled,
867
+ configRevision: app.configRevision,
868
+ appliedRevision: app.appliedRevision,
869
+ lastError: app.lastError || void 0
870
+ });
871
+ })
872
+ );
873
+ server.registerTool(
874
+ "roxyon_logs",
875
+ {
876
+ title: "Roxyon: application logs",
877
+ description: "Recent journal lines for an application (by id or project dir).",
878
+ inputSchema: {
879
+ application: z4.string().optional(),
880
+ dir: z4.string().optional(),
881
+ lines: z4.number().int().min(1).max(1e3).optional().describe("How many lines (default 100).")
882
+ }
883
+ },
884
+ (args) => guard(async () => {
885
+ const session = await getSession();
886
+ const { applicationId } = await resolveApp(args);
887
+ const lines = await session.roxyon.applications.logs(applicationId, args.lines ?? 100);
888
+ return text(lines.join("\n") || "(no log lines)", { lines });
889
+ })
890
+ );
891
+ server.registerTool(
892
+ "roxyon_restart",
893
+ {
894
+ title: "Roxyon: restart an application",
895
+ description: "Bounce the application process (no rebuild). Needs confirm:true.",
896
+ inputSchema: {
897
+ application: z4.string().optional(),
898
+ dir: z4.string().optional(),
899
+ confirm: z4.boolean().optional()
900
+ }
901
+ },
902
+ (args) => guard(async () => {
903
+ const session = await getSession();
904
+ const { applicationId } = await resolveApp(args);
905
+ if (!args.confirm)
906
+ return text(`Would restart ${applicationId}. Pass confirm:true.`, { dryRun: true });
907
+ await session.roxyon.applications.restart(applicationId);
908
+ return text(`Restart queued for ${applicationId}.`, { ok: true });
909
+ })
910
+ );
911
+ server.registerTool(
912
+ "roxyon_env_get",
913
+ {
914
+ title: "Roxyon: read environment variables",
915
+ description: "An application's environment variables as KEY=value lines.",
916
+ inputSchema: { application: z4.string().optional(), dir: z4.string().optional() }
917
+ },
918
+ (args) => guard(async () => {
919
+ const session = await getSession();
920
+ const { applicationId } = await resolveApp(args);
921
+ const env = await session.roxyon.applications.getEnv(applicationId);
922
+ return text(formatEnv(env) || "(none set)", { env });
923
+ })
924
+ );
925
+ server.registerTool(
926
+ "roxyon_env_set",
927
+ {
928
+ title: "Roxyon: set environment variables",
929
+ description: "Merge variables into an application's environment and bump its revision. Run roxyon_deploy afterwards to apply. Needs confirm:true. PORT and HOST are platform-managed and ignored.",
930
+ inputSchema: {
931
+ application: z4.string().optional(),
932
+ dir: z4.string().optional(),
933
+ vars: z4.record(z4.string()).describe('{ KEY: "value", ... } to set.'),
934
+ remove: z4.array(z4.string()).optional().describe("Keys to delete."),
935
+ confirm: z4.boolean().optional()
936
+ }
937
+ },
938
+ (args) => guard(async () => {
939
+ const session = await getSession();
940
+ const { applicationId } = await resolveApp(args);
941
+ const set = {};
942
+ for (const [k, v] of Object.entries(args.vars)) {
943
+ if (k === "PORT" || k === "HOST") continue;
944
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) return errorResult(`Invalid env key "${k}".`);
945
+ set[k] = v;
946
+ }
947
+ const planned = [...Object.keys(set), ...(args.remove ?? []).map((k) => `-${k}`)];
948
+ if (!args.confirm) {
949
+ return text(`Would update: ${planned.join(", ") || "(nothing)"}. Pass confirm:true.`, {
950
+ dryRun: true,
951
+ changed: planned
952
+ });
953
+ }
954
+ const r = await session.roxyon.applications.setEnv(applicationId, {
955
+ set,
956
+ remove: args.remove ?? []
957
+ });
958
+ return text(`Updated ${r.changed.join(", ") || "(nothing)"}. Run roxyon_deploy to apply.`, {
959
+ ok: true,
960
+ changed: r.changed
961
+ });
962
+ })
963
+ );
964
+ server.registerTool(
965
+ "roxyon_link_github",
966
+ {
967
+ title: "Roxyon: connect a git remote",
968
+ description: "Connect a git repository to an application for push-to-deploy. Returns the deploy key and webhook URL to add to the repo. Needs confirm:true.",
969
+ inputSchema: {
970
+ application: z4.string().optional(),
971
+ dir: z4.string().optional(),
972
+ repoUrl: z4.string().describe("SSH git URL, e.g. git@github.com:you/app.git"),
973
+ branch: z4.string().optional().describe("Branch to deploy (default main)."),
974
+ confirm: z4.boolean().optional()
975
+ }
976
+ },
977
+ (args) => guard(async () => {
978
+ const session = await getSession();
979
+ const { applicationId } = await resolveApp(args);
980
+ if (!args.confirm) {
981
+ return text(
982
+ `Would connect ${args.repoUrl} (${args.branch ?? "main"}) to ${applicationId}. Pass confirm:true.`,
983
+ { dryRun: true }
984
+ );
985
+ }
986
+ const res = await session.roxyon.applications.repoConnect(
987
+ applicationId,
988
+ args.repoUrl,
989
+ args.branch ?? "main"
990
+ );
991
+ const body = [
992
+ `Connected ${args.repoUrl} (${args.branch ?? "main"}).`,
993
+ res.deployKey ? `
994
+ Deploy key (add to the repo, read-only):
995
+ ${res.deployKey}` : "",
996
+ res.webhookUrl ? `
997
+ Webhook URL: ${res.webhookUrl}` : "",
998
+ res.secret ? `Webhook secret: ${res.secret}` : "",
999
+ res.hint ? `
1000
+ ${res.hint}` : ""
1001
+ ].filter(Boolean).join("\n");
1002
+ return text(body, {
1003
+ ok: true,
1004
+ deployKey: res.deployKey,
1005
+ webhookUrl: res.webhookUrl,
1006
+ secret: res.secret
1007
+ });
1008
+ })
1009
+ );
1010
+ server.registerTool(
1011
+ "roxyon_add_domain",
1012
+ {
1013
+ title: "Roxyon: add a subdomain / host",
1014
+ description: "Provision a host \u2014 DNS + web server + automatic HTTPS. The host must be a subdomain of a domain the account already hosts (or a *.roxyon.com subdomain). Returns while it is still coming up; TLS follows a minute or two later. Needs confirm:true.",
1015
+ inputSchema: {
1016
+ host: z4.string().describe("The full hostname, e.g. promo.mycompany.com"),
1017
+ subscription: z4.string().optional().describe("Which subscription to attach it to (omit if the account has one)."),
1018
+ spa: z4.boolean().optional().describe("Single-page app: unmatched paths serve /index.html."),
1019
+ phpVersion: z4.string().optional().describe(
1020
+ 'PHP version for the vhost, e.g. "8.3" (needed to run PHP apps like WordPress).'
1021
+ ),
1022
+ confirm: z4.boolean().optional()
1023
+ }
1024
+ },
1025
+ (args) => guard(async () => {
1026
+ const session = await getSession();
1027
+ if (!args.confirm) {
1028
+ return text(
1029
+ `Would provision ${args.host}${args.spa ? " (SPA routing)" : ""}. Pass confirm:true.`,
1030
+ { dryRun: true }
1031
+ );
1032
+ }
1033
+ const res = await session.roxyon.domains.create({
1034
+ host: args.host,
1035
+ subscription: args.subscription ?? session.preferredSubscription,
1036
+ siteType: args.spa ? "spa" : void 0,
1037
+ phpVersion: args.phpVersion
1038
+ });
1039
+ const live = res.status === "active";
1040
+ return text(
1041
+ [
1042
+ `${res.host} \u2014 ${res.type}, ${res.status}.`,
1043
+ live ? "The host is up. HTTPS may take another minute to issue." : "DNS + web server are being set up (~1\u20132 min), then HTTPS. Check roxyon_list_domains, or just deploy now \u2014 files are kept and served once it is live."
1044
+ ].join("\n"),
1045
+ { ok: true, host: res.host, type: res.type, status: res.status }
1046
+ );
1047
+ })
1048
+ );
1049
+ server.registerTool(
1050
+ "roxyon_deploy_content",
1051
+ {
1052
+ title: "Roxyon: deploy generated files",
1053
+ description: [
1054
+ "Publish a set of files you generated (HTML/CSS/JS/assets) to a host on the account.",
1055
+ "The host must already exist (roxyon_add_domain, or an existing site). Overlay by",
1056
+ "default \u2014 pass clean:true to replace the whole document root. Needs confirm:true.",
1057
+ `Limits: ${MAX_FILES} files, ${MAX_FILE_BYTES / 1024 | 0} KB per file,`,
1058
+ `${(MAX_TOTAL_BYTES / 1024 / 1024).toFixed(1)} MB total (base64-encode binaries).`
1059
+ ].join(" "),
1060
+ inputSchema: {
1061
+ host: z4.string().describe("Target host, e.g. promo.mycompany.com"),
1062
+ folder: z4.string().optional().describe('Sub-path under the host; "" = site root.'),
1063
+ files: z4.array(
1064
+ z4.object({
1065
+ path: z4.string().describe("Relative path, e.g. index.html, about/index.html"),
1066
+ content: z4.string(),
1067
+ encoding: z4.enum(["utf8", "base64"]).optional()
1068
+ })
1069
+ ).min(1),
1070
+ clean: z4.boolean().optional().describe("Replace the whole docroot (keeps .well-known)."),
1071
+ spa: z4.boolean().optional().describe("Also flip the host to SPA routing."),
1072
+ confirm: z4.boolean().optional()
1073
+ }
1074
+ },
1075
+ (args) => guard(async () => {
1076
+ const session = await getSession();
1077
+ if (args.files.length > MAX_FILES) {
1078
+ return errorResult(`Too many files (${args.files.length}); the limit is ${MAX_FILES}.`);
1079
+ }
1080
+ let total = 0;
1081
+ for (const f of args.files) {
1082
+ const n = Buffer.byteLength(f.content, f.encoding === "base64" ? "base64" : "utf8");
1083
+ if (n > MAX_FILE_BYTES) {
1084
+ return errorResult(
1085
+ `"${f.path}" is ${n / 1024 | 0} KB; the per-file limit is ${MAX_FILE_BYTES / 1024 | 0} KB.`
1086
+ );
1087
+ }
1088
+ total += n;
1089
+ }
1090
+ if (total > MAX_TOTAL_BYTES) {
1091
+ return errorResult(
1092
+ `Total content is ${(total / 1024 / 1024).toFixed(1)} MB; the limit is ${(MAX_TOTAL_BYTES / 1024 / 1024).toFixed(1)} MB. Deploy in parts or use the CLI.`
1093
+ );
1094
+ }
1095
+ const folder = args.folder ?? "";
1096
+ if (!args.confirm) {
1097
+ return text(
1098
+ [
1099
+ "DRY RUN \u2014 pass confirm:true to deploy.",
1100
+ "",
1101
+ `Host: ${args.host}${folder ? `/${folder}` : ""}`,
1102
+ `Files: ${args.files.length} (${total / 1024 | 0} KB)`,
1103
+ `Mode: ${args.clean ? "clean (replaces the document root)" : "overlay"}${args.spa ? " + SPA routing" : ""}`,
1104
+ ...args.files.slice(0, 20).map((f) => ` ${f.path}`),
1105
+ args.files.length > 20 ? ` \u2026 ${args.files.length - 20} more` : ""
1106
+ ].filter(Boolean).join("\n"),
1107
+ { dryRun: true }
1108
+ );
1109
+ }
1110
+ const { buffer, files } = await packFiles(args.files, { maxBytes: MAX_TOTAL_BYTES });
1111
+ const r = await session.roxyon.sites.deploy(args.host, folder, buffer, {
1112
+ clean: args.clean,
1113
+ spa: args.spa
1114
+ });
1115
+ const size = r.bytes ? ` (${r.bytes / 1024 | 0} KB)` : "";
1116
+ const spaNote = args.spa ? "\nSPA routing enabled \u2014 deep links resolve to index.html." : "";
1117
+ return text(
1118
+ `\u2713 Deployed ${files.length} file(s) to https://${args.host}${folder ? `/${folder}` : ""}${size}.${spaNote}`,
1119
+ { ok: true, host: args.host, files: files.length }
1120
+ );
1121
+ })
1122
+ );
1123
+ server.registerTool(
1124
+ "roxyon_list_files",
1125
+ {
1126
+ title: "Roxyon: list a site\u2019s files",
1127
+ description: "The files currently deployed to a host's document root.",
1128
+ inputSchema: {
1129
+ host: z4.string(),
1130
+ folder: z4.string().optional(),
1131
+ path: z4.string().optional().describe("List under this sub-path only.")
1132
+ }
1133
+ },
1134
+ (args) => guard(async () => {
1135
+ const session = await getSession();
1136
+ const files = await session.roxyon.sites.listFiles(
1137
+ args.host,
1138
+ args.folder ?? "",
1139
+ args.path ?? ""
1140
+ );
1141
+ const body = files.length ? files.map(
1142
+ (f) => `${f.type === "dir" ? "d" : "-"} ${String(f.size).padStart(8)} ${f.path}`
1143
+ ).join("\n") : "(empty)";
1144
+ return text(body, { files });
1145
+ })
1146
+ );
1147
+ server.registerTool(
1148
+ "roxyon_read_file",
1149
+ {
1150
+ title: "Roxyon: read a site file",
1151
+ description: "Read one file from a host's document root (to review or edit it).",
1152
+ inputSchema: {
1153
+ host: z4.string(),
1154
+ folder: z4.string().optional(),
1155
+ path: z4.string().describe("Relative path, e.g. index.html")
1156
+ }
1157
+ },
1158
+ (args) => guard(async () => {
1159
+ const session = await getSession();
1160
+ const f = await session.roxyon.sites.readFile(args.host, args.folder ?? "", args.path);
1161
+ if (f.encoding === "base64") {
1162
+ return text(
1163
+ `${f.path} \u2014 ${f.size} bytes, binary (base64):
1164
+
1165
+ ${f.content.slice(0, 4096)}`,
1166
+ { path: f.path, size: f.size, encoding: "base64" }
1167
+ );
1168
+ }
1169
+ return text(f.content, { path: f.path, size: f.size, encoding: "utf8" });
1170
+ })
1171
+ );
1172
+ server.registerTool(
1173
+ "roxyon_database_create",
1174
+ {
1175
+ title: "Roxyon: create a database",
1176
+ description: `Provision a MySQL/MariaDB database + user. The name is prefixed with the account's own username (globally unique across the shared cluster) \u2014 pass just the suffix, e.g. "wordpress". The password is shown once in the result; there is no way to retrieve it later. Needs confirm:true.`,
1177
+ inputSchema: {
1178
+ name: z4.string().describe("DB name suffix: lowercase letters, digits, underscore."),
1179
+ subscription: z4.string().optional(),
1180
+ password: z4.string().optional().describe("Omit to have Roxyon generate one."),
1181
+ confirm: z4.boolean().optional()
1182
+ }
1183
+ },
1184
+ (args) => guard(async () => {
1185
+ const session = await getSession();
1186
+ if (!args.confirm) {
1187
+ return text(`Would create database "${args.name}". Pass confirm:true.`, { dryRun: true });
1188
+ }
1189
+ const r = await session.roxyon.databases.create({
1190
+ name: args.name,
1191
+ subscription: args.subscription ?? session.preferredSubscription,
1192
+ password: args.password
1193
+ });
1194
+ const body = [
1195
+ `${r.status === "active" ? "\u2713" : "\xBB"} Database ${r.name} (user ${r.username}) \u2014 ${r.status}.`,
1196
+ r.password ? `
1197
+ Password (save this now \u2014 shown once):
1198
+ ${r.password}` : "",
1199
+ r.host ? `Host: ${r.host}` : ""
1200
+ ].filter(Boolean).join("\n");
1201
+ return text(body, {
1202
+ ok: true,
1203
+ objectId: r.objectId,
1204
+ name: r.name,
1205
+ username: r.username,
1206
+ host: r.host,
1207
+ status: r.status
1208
+ });
1209
+ })
1210
+ );
1211
+ server.registerTool(
1212
+ "roxyon_list_databases",
1213
+ {
1214
+ title: "Roxyon: list databases",
1215
+ description: "Databases on the active subscription.",
1216
+ inputSchema: { subscription: z4.string().optional() }
1217
+ },
1218
+ (args) => guard(async () => {
1219
+ const session = await getSession();
1220
+ const subscription = args.subscription ?? session.preferredSubscription;
1221
+ if (!subscription) return errorResult('No subscription \u2014 pass "subscription".');
1222
+ const rows = await session.roxyon.databases.list(subscription);
1223
+ const body = rows.length ? rows.map((d) => `- ${d.Name} [${d.objectId}] \u2014 ${d.Status} (user ${d.Username})`).join("\n") : "(no databases)";
1224
+ return text(body, { databases: rows });
1225
+ })
1226
+ );
1227
+ server.registerTool(
1228
+ "roxyon_database_delete",
1229
+ {
1230
+ title: "Roxyon: delete a database",
1231
+ description: "Delete a database by its objectId (from roxyon_database_create/roxyon_list_databases). Needs confirm:true.",
1232
+ inputSchema: { database: z4.string(), confirm: z4.boolean().optional() }
1233
+ },
1234
+ (args) => guard(async () => {
1235
+ const session = await getSession();
1236
+ if (!args.confirm) {
1237
+ return text(`Would delete database ${args.database}. Pass confirm:true.`, {
1238
+ dryRun: true
1239
+ });
1240
+ }
1241
+ const r = await session.roxyon.databases.delete(args.database);
1242
+ return text(`Database ${args.database} \u2014 ${r.status}.`, { ok: true, status: r.status });
1243
+ })
1244
+ );
1245
+ server.registerTool(
1246
+ "roxyon_email_create",
1247
+ {
1248
+ title: "Roxyon: create a mailbox",
1249
+ description: "Provision a mailbox on a host already on the account. The password is shown once in the result; there is no way to retrieve it later. Needs confirm:true.",
1250
+ inputSchema: {
1251
+ localPart: z4.string().describe('The part before @, e.g. "info".'),
1252
+ domain: z4.string().describe("A hostname already on the account."),
1253
+ password: z4.string().optional().describe("Omit to have Roxyon generate one."),
1254
+ quota: z4.number().int().positive().optional().describe("Quota in MB (default 1024)."),
1255
+ forwardTo: z4.string().optional(),
1256
+ saveCopy: z4.boolean().optional(),
1257
+ confirm: z4.boolean().optional()
1258
+ }
1259
+ },
1260
+ (args) => guard(async () => {
1261
+ const session = await getSession();
1262
+ const email = `${args.localPart}@${args.domain}`;
1263
+ if (!args.confirm) {
1264
+ return text(`Would create mailbox ${email}. Pass confirm:true.`, { dryRun: true });
1265
+ }
1266
+ const r = await session.roxyon.email.create({
1267
+ localPart: args.localPart,
1268
+ domain: args.domain,
1269
+ password: args.password,
1270
+ quota: args.quota,
1271
+ forwardTo: args.forwardTo,
1272
+ saveCopy: args.saveCopy
1273
+ });
1274
+ const body = [
1275
+ `${r.status === "active" ? "\u2713" : "\xBB"} Mailbox ${r.email} \u2014 ${r.status}.`,
1276
+ r.password ? `
1277
+ Password (save this now \u2014 shown once):
1278
+ ${r.password}` : ""
1279
+ ].filter(Boolean).join("\n");
1280
+ return text(body, { ok: true, objectId: r.objectId, email: r.email, status: r.status });
1281
+ })
1282
+ );
1283
+ server.registerTool(
1284
+ "roxyon_list_emails",
1285
+ {
1286
+ title: "Roxyon: list mailboxes",
1287
+ description: "Mailboxes on the active subscription.",
1288
+ inputSchema: { subscription: z4.string().optional() }
1289
+ },
1290
+ (args) => guard(async () => {
1291
+ const session = await getSession();
1292
+ const subscription = args.subscription ?? session.preferredSubscription;
1293
+ if (!subscription) return errorResult('No subscription \u2014 pass "subscription".');
1294
+ const rows = await session.roxyon.email.list(subscription);
1295
+ const body = rows.length ? rows.map((e) => `- ${e.Email} [${e.objectId}] \u2014 ${e.Status}`).join("\n") : "(no mailboxes)";
1296
+ return text(body, { emails: rows });
1297
+ })
1298
+ );
1299
+ server.registerTool(
1300
+ "roxyon_email_delete",
1301
+ {
1302
+ title: "Roxyon: delete a mailbox",
1303
+ description: "Delete a mailbox by its objectId (from roxyon_email_create/roxyon_list_emails). Needs confirm:true.",
1304
+ inputSchema: { email: z4.string(), confirm: z4.boolean().optional() }
1305
+ },
1306
+ (args) => guard(async () => {
1307
+ const session = await getSession();
1308
+ if (!args.confirm) {
1309
+ return text(`Would delete mailbox ${args.email}. Pass confirm:true.`, { dryRun: true });
1310
+ }
1311
+ const r = await session.roxyon.email.delete(args.email);
1312
+ return text(`Mailbox ${args.email} \u2014 ${r.status}.`, { ok: true, status: r.status });
1313
+ })
1314
+ );
1315
+ server.registerTool(
1316
+ "roxyon_ssh_reset_password",
1317
+ {
1318
+ title: "Roxyon: reset the SSH/SFTP password",
1319
+ description: "Reset a subscription's shell password \u2014 used for SSH, SFTP, and the file manager. Changing it signs out anything using the old one. The password is shown once in the result; the platform never stores or re-shows it. Needs confirm:true.",
1320
+ inputSchema: {
1321
+ subscription: z4.string().optional(),
1322
+ password: z4.string().optional().describe("Omit to have Roxyon generate one (12+ chars, mixed case, number, symbol)."),
1323
+ confirm: z4.boolean().optional()
1324
+ }
1325
+ },
1326
+ (args) => guard(async () => {
1327
+ const session = await getSession();
1328
+ if (!args.confirm) {
1329
+ return text("Would reset the SSH/SFTP password. Pass confirm:true.", { dryRun: true });
1330
+ }
1331
+ const r = await session.roxyon.ssh.resetPassword({
1332
+ subscription: args.subscription ?? session.preferredSubscription,
1333
+ password: args.password
1334
+ });
1335
+ return text(
1336
+ `${r.status === "active" ? "\u2713" : "\xBB"} SSH/SFTP password ${r.status === "active" ? "changed" : "change queued"}.
1337
+
1338
+ Password (save this now \u2014 shown once):
1339
+ ${r.password}`,
1340
+ { ok: true, subscription: r.subscription, status: r.status }
1341
+ );
1342
+ })
1343
+ );
1344
+ server.registerTool(
1345
+ "roxyon_install_wordpress",
1346
+ {
1347
+ title: "Roxyon: install WordPress",
1348
+ description: [
1349
+ "One-shot recipe: create a subdomain (if it does not already exist), provision a database",
1350
+ "for it, download WordPress core, and deploy it. v1 scope \u2014 core only, no plugin/theme",
1351
+ "selection, single site. Local-only (needs your filesystem to unpack WordPress into) \u2014 run",
1352
+ "this from the CLI-backed MCP, not the hosted mcp.roxyon.com connector. Needs confirm:true."
1353
+ ].join(" "),
1354
+ inputSchema: {
1355
+ host: z4.string().describe("The site host, e.g. blog.mycompany.com \u2014 created if it does not exist."),
1356
+ folder: z4.string().optional().describe('Sub-path under the host; "" = site root (recommended).'),
1357
+ subscription: z4.string().optional(),
1358
+ dbName: z4.string().optional().describe(
1359
+ "Database name suffix (default derived from the host). See roxyon_database_create."
1360
+ ),
1361
+ phpVersion: z4.string().optional().describe('Default "8.3".'),
1362
+ confirm: z4.boolean().optional()
1363
+ }
1364
+ },
1365
+ (args) => guard(async () => {
1366
+ const blocked = remoteFilesystemBlock("roxyon_install_wordpress");
1367
+ if (blocked) return blocked;
1368
+ const session = await getSession();
1369
+ const folder = args.folder ?? "";
1370
+ const dbSuffix = (args.dbName ?? args.host.split(".")[0] ?? "wordpress").toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/^[^a-z]+/, "").slice(0, 20) || "wordpress";
1371
+ if (!args.confirm) {
1372
+ return text(
1373
+ [
1374
+ "DRY RUN \u2014 pass confirm:true to install.",
1375
+ "",
1376
+ `Host: ${args.host}${folder ? `/${folder}` : ""} (created if missing)`,
1377
+ `Database: ${dbSuffix} (prefixed with your account username)`,
1378
+ "Steps: add domain -> create database -> download WordPress core -> upload"
1379
+ ].join("\n"),
1380
+ { dryRun: true }
1381
+ );
1382
+ }
1383
+ const subscription = args.subscription ?? session.preferredSubscription;
1384
+ const domain = await session.roxyon.domains.create({
1385
+ host: args.host,
1386
+ subscription,
1387
+ phpVersion: args.phpVersion ?? "8.3"
1388
+ });
1389
+ if (domain.status === "failed") {
1390
+ return errorResult(
1391
+ `Could not provision ${args.host}: ${domain.error ?? "unknown error"}`
1392
+ );
1393
+ }
1394
+ const db = await session.roxyon.databases.create({ name: dbSuffix, subscription });
1395
+ if (db.status === "failed" || !db.password || !db.host) {
1396
+ return errorResult(`Could not provision the database: ${db.error ?? "unknown error"}`);
1397
+ }
1398
+ const scratchDir = await mkdtemp(join3(tmpdir(), "roxyon-wp-"));
1399
+ await installWordPress({
1400
+ dir: scratchDir,
1401
+ db: { name: db.name, username: db.username, password: db.password, host: db.host }
1402
+ });
1403
+ const pack = await packDirectory(scratchDir);
1404
+ const deployRes = await session.roxyon.sites.deploy(args.host, folder, pack.buffer);
1405
+ const url = `https://${deployRes.host}${deployRes.path && deployRes.path !== "/" ? deployRes.path : ""}`;
1406
+ return text(
1407
+ [
1408
+ `\u2713 WordPress installed at ${url} (${pack.files.length} files).`,
1409
+ "Visit the site to finish setup (site title, admin account) \u2014 WordPress asks for these",
1410
+ "on first load.",
1411
+ "",
1412
+ `Database: ${db.name} / ${db.username} \u2014 password shown once, save it now:`,
1413
+ db.password
1414
+ ].join("\n"),
1415
+ { ok: true, url, database: { name: db.name, username: db.username } }
1416
+ );
1417
+ })
1418
+ );
1419
+ }
1420
+
1421
+ // src/server.ts
1422
+ var SERVER_NAME = "roxyon";
1423
+ var SERVER_VERSION = createRequire(import.meta.url)("../package.json").version;
1424
+ function createServer() {
1425
+ const server = new McpServer(
1426
+ { name: SERVER_NAME, version: SERVER_VERSION },
1427
+ {
1428
+ instructions: "Roxyon lets you build LumenJS SPAs, use the Roxyon BaaS, and deploy apps and web projects to Roxyon infrastructure. Read the roxyon://docs/* resources before writing LumenJS or calling the BaaS. To deploy: roxyon_init once per project, then roxyon_deploy (dry run, then confirm:true). Side-effecting tools require confirm:true."
1429
+ }
1430
+ );
1431
+ registerResources(server);
1432
+ registerPrompts(server);
1433
+ registerTools(server);
1434
+ registerBaasTools(server);
1435
+ registerCommerceTools(server);
1436
+ return server;
1437
+ }
1438
+
1439
+ export {
1440
+ runWithContext,
1441
+ SERVER_NAME,
1442
+ SERVER_VERSION,
1443
+ createServer
1444
+ };
1445
+ //# sourceMappingURL=chunk-KU3LB5HH.js.map