@taghost/mcp 0.0.0-stage → 1.0.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,2557 @@
1
+ // src/server.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import dotenv from "dotenv";
5
+
6
+ // src/client/auth.ts
7
+ import fs from "fs";
8
+ import os from "os";
9
+ import path from "path";
10
+ var DEFAULT_API_URL = "https://api.taghost.io";
11
+ function getApiUrl() {
12
+ return (process.env.TAGHOST_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
13
+ }
14
+ function credentialsPath(homeDir = process.env.TAGHOST_HOME || os.homedir()) {
15
+ return path.join(homeDir, ".taghost", "credentials.json");
16
+ }
17
+ function resolveAuthToken() {
18
+ if (process.env.TAGHOST_API_TOKEN && process.env.TAGHOST_API_TOKEN.trim()) {
19
+ return process.env.TAGHOST_API_TOKEN.trim();
20
+ }
21
+ if (process.env.TAGHOST_TOKEN && process.env.TAGHOST_TOKEN.trim()) {
22
+ return process.env.TAGHOST_TOKEN.trim();
23
+ }
24
+ const credsPath = credentialsPath();
25
+ if (fs.existsSync(credsPath)) {
26
+ try {
27
+ const data = JSON.parse(fs.readFileSync(credsPath, "utf8"));
28
+ if (data && typeof data.token === "string" && data.token.trim()) {
29
+ return data.token.trim();
30
+ }
31
+ } catch {
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+
37
+ // src/client/project-context.ts
38
+ import fs2 from "fs";
39
+ import path2 from "path";
40
+ function findProjectBinding(startDir = process.cwd()) {
41
+ if (process.env.TAGHOST_PROJECT_ID && process.env.TAGHOST_PROJECT_ID.trim()) {
42
+ return { projectId: process.env.TAGHOST_PROJECT_ID.trim() };
43
+ }
44
+ let curr = path2.resolve(startDir);
45
+ while (true) {
46
+ const bindingFile = path2.join(curr, ".taghost", "project.json");
47
+ if (fs2.existsSync(bindingFile)) {
48
+ try {
49
+ const data = JSON.parse(fs2.readFileSync(bindingFile, "utf8"));
50
+ if (data && typeof data.projectId === "string" && data.projectId.trim()) {
51
+ return {
52
+ projectId: data.projectId.trim(),
53
+ slug: data.slug || data.name
54
+ };
55
+ }
56
+ } catch {
57
+ }
58
+ }
59
+ const parent = path2.dirname(curr);
60
+ if (parent === curr) break;
61
+ curr = parent;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ // src/client/taghost-client.ts
67
+ var TagHostClient = class {
68
+ apiUrl;
69
+ token;
70
+ constructor(options = {}) {
71
+ this.apiUrl = (options.apiUrl || getApiUrl()).replace(/\/+$/, "");
72
+ this.token = options.token || resolveAuthToken();
73
+ }
74
+ async request(endpoint, options = {}) {
75
+ const url = endpoint.startsWith("http") ? endpoint : `${this.apiUrl}${endpoint.startsWith("/") ? "" : "/"}${endpoint}`;
76
+ const headers = new Headers(options.headers || {});
77
+ if (this.token && !headers.has("Authorization")) {
78
+ headers.set("Authorization", `Bearer ${this.token}`);
79
+ }
80
+ const response = await fetch(url, {
81
+ ...options,
82
+ headers
83
+ });
84
+ const contentType = response.headers.get("content-type") || "";
85
+ let body = null;
86
+ if (contentType.includes("application/json")) {
87
+ try {
88
+ body = await response.json();
89
+ } catch {
90
+ body = null;
91
+ }
92
+ } else {
93
+ body = await response.text();
94
+ }
95
+ if (!response.ok) {
96
+ const errorMessage = body && typeof body === "object" && (body.error || body.message) ? body.error || body.message : `HTTP ${response.status}: ${typeof body === "string" ? body : response.statusText}`;
97
+ const error = new Error(errorMessage);
98
+ error.status = response.status;
99
+ error.data = body;
100
+ throw error;
101
+ }
102
+ return body;
103
+ }
104
+ async resolveProjectId(explicitId) {
105
+ if (explicitId && explicitId.trim()) {
106
+ return explicitId.trim();
107
+ }
108
+ const local = findProjectBinding();
109
+ if (local && local.projectId) {
110
+ return local.projectId;
111
+ }
112
+ const projects = await this.listProjects();
113
+ const list = Array.isArray(projects) ? projects : projects?.projects || [];
114
+ if (list.length > 0 && list[0].id) {
115
+ return list[0].id;
116
+ }
117
+ throw new Error(
118
+ 'No project ID provided or found. Specify projectId or link a project with "tag login" / .taghost/project.json.'
119
+ );
120
+ }
121
+ // ── Authentication & Workspaces ─────────────────────────────────────────────
122
+ async getMe() {
123
+ return this.request("/auth/me");
124
+ }
125
+ // ── Projects ───────────────────────────────────────────────────────────────
126
+ async listProjects() {
127
+ return this.request("/projects");
128
+ }
129
+ async getProject(projectId) {
130
+ return this.request(`/projects/${projectId}`);
131
+ }
132
+ async createProject(data) {
133
+ return this.request("/projects", {
134
+ method: "POST",
135
+ headers: { "Content-Type": "application/json" },
136
+ body: JSON.stringify(data)
137
+ });
138
+ }
139
+ async getProjectEnv(projectId) {
140
+ return this.request(`/projects/${projectId}/env`);
141
+ }
142
+ async setProjectEnv(projectId, key, value, target = "all") {
143
+ return this.request(`/projects/${projectId}/env`, {
144
+ method: "POST",
145
+ headers: { "Content-Type": "application/json" },
146
+ body: JSON.stringify({ key, value, target })
147
+ });
148
+ }
149
+ async deleteProjectEnv(projectId, key) {
150
+ return this.request(`/projects/${projectId}/env/${encodeURIComponent(key)}`, {
151
+ method: "DELETE"
152
+ });
153
+ }
154
+ // ── Deployments & Files ───────────────────────────────────────────────────
155
+ async deployBundle(projectId, zipBytes, options = {}) {
156
+ const params = new URLSearchParams();
157
+ if (options.branch) params.set("branch", options.branch);
158
+ if (options.preview) params.set("preview", "true");
159
+ if (options.commitMessage) params.set("commitMessage", options.commitMessage);
160
+ const query = params.toString() ? `?${params.toString()}` : "";
161
+ return this.request(`/projects/${projectId}/deployments/bundle${query}`, {
162
+ method: "POST",
163
+ headers: {
164
+ "Content-Type": "application/zip"
165
+ },
166
+ body: zipBytes
167
+ });
168
+ }
169
+ async getProjectFiles(projectId) {
170
+ return this.request(`/projects/${projectId}/files`);
171
+ }
172
+ async publishProjectFiles(projectId, data) {
173
+ return this.request(`/projects/${projectId}/files`, {
174
+ method: "POST",
175
+ headers: { "Content-Type": "application/json" },
176
+ body: JSON.stringify(data)
177
+ });
178
+ }
179
+ async listDeployments(projectId) {
180
+ return this.request(`/projects/${projectId}/deployments`);
181
+ }
182
+ async rollbackDeployment(projectId, deploymentId) {
183
+ return this.request(`/projects/${projectId}/deployments/${deploymentId}/rollback`, {
184
+ method: "POST"
185
+ });
186
+ }
187
+ async setDeploymentExpiry(projectId, deploymentId, ttlSeconds, neverExpire) {
188
+ return this.request(`/projects/${projectId}/deployments/${deploymentId}/expiry`, {
189
+ method: "PATCH",
190
+ headers: { "Content-Type": "application/json" },
191
+ body: JSON.stringify({ ttlSeconds, neverExpire })
192
+ });
193
+ }
194
+ // ── Domains & DNS ──────────────────────────────────────────────────────────
195
+ async checkDomainAvailability(domain) {
196
+ return this.request(`/domains/check?domain=${encodeURIComponent(domain)}`);
197
+ }
198
+ async searchDomains(query) {
199
+ return this.request(`/domains/search?query=${encodeURIComponent(query)}`);
200
+ }
201
+ async checkoutDomain(projectId, data) {
202
+ return this.request(`/projects/${projectId}/domains/checkout`, {
203
+ method: "POST",
204
+ headers: { "Content-Type": "application/json" },
205
+ body: JSON.stringify(data)
206
+ });
207
+ }
208
+ async attachDomain(projectId, domain) {
209
+ return this.request(`/projects/${projectId}/domains`, {
210
+ method: "POST",
211
+ headers: { "Content-Type": "application/json" },
212
+ body: JSON.stringify({ domain })
213
+ });
214
+ }
215
+ async verifyDomain(projectId, domain) {
216
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/verify`, {
217
+ method: "POST"
218
+ });
219
+ }
220
+ async listDnsRecords(projectId, domain) {
221
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns`);
222
+ }
223
+ async createDnsRecord(projectId, domain, record) {
224
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns`, {
225
+ method: "POST",
226
+ headers: { "Content-Type": "application/json" },
227
+ body: JSON.stringify(record)
228
+ });
229
+ }
230
+ async updateDnsRecord(projectId, domain, recordId, record) {
231
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns/${recordId}`, {
232
+ method: "PATCH",
233
+ headers: { "Content-Type": "application/json" },
234
+ body: JSON.stringify(record)
235
+ });
236
+ }
237
+ async deleteDnsRecord(projectId, domain, recordId) {
238
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns/${recordId}`, {
239
+ method: "DELETE"
240
+ });
241
+ }
242
+ // ── TagMail (Corporate Inbox & Sending) ───────────────────────────────────
243
+ async listMailThreads(projectId, options = {}) {
244
+ const params = new URLSearchParams();
245
+ if (options.mailboxId) params.set("mailboxId", options.mailboxId);
246
+ if (options.query) params.set("q", options.query);
247
+ if (options.limit) params.set("limit", String(options.limit));
248
+ const query = params.toString() ? `?${params.toString()}` : "";
249
+ return this.request(`/projects/${projectId}/email/threads${query}`);
250
+ }
251
+ async getMailThread(projectId, threadId) {
252
+ return this.request(`/projects/${projectId}/email/threads/${threadId}`);
253
+ }
254
+ async sendMail(projectId, data) {
255
+ return this.request(`/projects/${projectId}/email/send`, {
256
+ method: "POST",
257
+ headers: { "Content-Type": "application/json" },
258
+ body: JSON.stringify(data)
259
+ });
260
+ }
261
+ async listMailboxes(projectId) {
262
+ return this.request(`/projects/${projectId}/email/mailboxes`);
263
+ }
264
+ async createMailbox(projectId, data) {
265
+ return this.request(`/projects/${projectId}/email/mailboxes`, {
266
+ method: "POST",
267
+ headers: { "Content-Type": "application/json" },
268
+ body: JSON.stringify(data)
269
+ });
270
+ }
271
+ async getMailDomainVerification(projectId, domain) {
272
+ return this.request(`/projects/${projectId}/email/domains/${encodeURIComponent(domain)}/verification`);
273
+ }
274
+ // ── Commerce, Themes & Gateways ───────────────────────────────────────────
275
+ async getCommerceTheme(projectId) {
276
+ return this.request(`/projects/${projectId}/commerce/theme`);
277
+ }
278
+ async updateCommerceTheme(projectId, theme) {
279
+ return this.request(`/projects/${projectId}/commerce/theme`, {
280
+ method: "PUT",
281
+ headers: { "Content-Type": "application/json" },
282
+ body: JSON.stringify(theme)
283
+ });
284
+ }
285
+ async getCommerceGateways(projectId) {
286
+ return this.request(`/projects/${projectId}/commerce/gateways`);
287
+ }
288
+ async updateCommerceGateway(projectId, provider, config) {
289
+ return this.request(`/projects/${projectId}/commerce/gateways/${provider}`, {
290
+ method: "PUT",
291
+ headers: { "Content-Type": "application/json" },
292
+ body: JSON.stringify(config)
293
+ });
294
+ }
295
+ async listOrders(projectId, options = {}) {
296
+ const params = new URLSearchParams();
297
+ if (options.status) params.set("status", options.status);
298
+ if (options.limit) params.set("limit", String(options.limit));
299
+ const query = params.toString() ? `?${params.toString()}` : "";
300
+ return this.request(`/projects/${projectId}/orders${query}`);
301
+ }
302
+ async getOrder(projectId, orderId) {
303
+ return this.request(`/projects/${projectId}/orders/${orderId}`);
304
+ }
305
+ async updateOrder(projectId, orderId, data) {
306
+ return this.request(`/projects/${projectId}/orders/${orderId}`, {
307
+ method: "PATCH",
308
+ headers: { "Content-Type": "application/json" },
309
+ body: JSON.stringify(data)
310
+ });
311
+ }
312
+ async listCoupons(projectId) {
313
+ return this.request(`/projects/${projectId}/commerce/coupons`);
314
+ }
315
+ async createCoupon(projectId, coupon) {
316
+ return this.request(`/projects/${projectId}/commerce/coupons`, {
317
+ method: "POST",
318
+ headers: { "Content-Type": "application/json" },
319
+ body: JSON.stringify(coupon)
320
+ });
321
+ }
322
+ async deleteCoupon(projectId, couponId) {
323
+ return this.request(`/projects/${projectId}/commerce/coupons/${couponId}`, {
324
+ method: "DELETE"
325
+ });
326
+ }
327
+ // ── CMS & Edge Collections ────────────────────────────────────────────────
328
+ async listCollections(projectId) {
329
+ return this.request(`/projects/${projectId}/collections`);
330
+ }
331
+ async createCollection(projectId, data) {
332
+ return this.request(`/projects/${projectId}/collections`, {
333
+ method: "POST",
334
+ headers: { "Content-Type": "application/json" },
335
+ body: JSON.stringify(data)
336
+ });
337
+ }
338
+ async listCollectionItems(projectId, collectionId) {
339
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items`);
340
+ }
341
+ async upsertCollectionItem(projectId, collectionId, data, itemId) {
342
+ if (itemId) {
343
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items/${itemId}`, {
344
+ method: "PATCH",
345
+ headers: { "Content-Type": "application/json" },
346
+ body: JSON.stringify({ data })
347
+ });
348
+ }
349
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items`, {
350
+ method: "POST",
351
+ headers: { "Content-Type": "application/json" },
352
+ body: JSON.stringify({ data })
353
+ });
354
+ }
355
+ async publishCollectionItem(projectId, collectionId, itemId, publish = true) {
356
+ const action = publish ? "publish" : "unpublish";
357
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items/${itemId}/${action}`, {
358
+ method: "POST"
359
+ });
360
+ }
361
+ // ── Edge Content (data-tag <1ms dictionary) ───────────────────────────────
362
+ async getContent(projectId) {
363
+ return this.request(`/projects/${projectId}/content`);
364
+ }
365
+ async patchContent(projectId, patches) {
366
+ return this.request(`/projects/${projectId}/content`, {
367
+ method: "POST",
368
+ headers: { "Content-Type": "application/json" },
369
+ body: JSON.stringify({ content: patches })
370
+ });
371
+ }
372
+ // ── Native Forms, CRM & Webhooks ──────────────────────────────────────────
373
+ async getFormSubmissions(projectId, options = {}) {
374
+ const params = new URLSearchParams();
375
+ if (options.formName) params.set("formName", options.formName);
376
+ if (options.limit) params.set("limit", String(options.limit));
377
+ const query = params.toString() ? `?${params.toString()}` : "";
378
+ return this.request(`/projects/${projectId}/forms/submissions${query}`);
379
+ }
380
+ async listSequences(projectId) {
381
+ return this.request(`/projects/${projectId}/sequences`);
382
+ }
383
+ async createSequence(projectId, data) {
384
+ return this.request(`/projects/${projectId}/sequences`, {
385
+ method: "POST",
386
+ headers: { "Content-Type": "application/json" },
387
+ body: JSON.stringify(data)
388
+ });
389
+ }
390
+ async enrollSequenceLead(projectId, sequenceId, data) {
391
+ return this.request(`/projects/${projectId}/sequences/${sequenceId}/enroll`, {
392
+ method: "POST",
393
+ headers: { "Content-Type": "application/json" },
394
+ body: JSON.stringify(data)
395
+ });
396
+ }
397
+ async listWebhooks(projectId) {
398
+ return this.request(`/projects/${projectId}/webhooks`);
399
+ }
400
+ async createWebhook(projectId, data) {
401
+ return this.request(`/projects/${projectId}/webhooks`, {
402
+ method: "POST",
403
+ headers: { "Content-Type": "application/json" },
404
+ body: JSON.stringify(data)
405
+ });
406
+ }
407
+ async deleteWebhook(projectId, webhookId) {
408
+ return this.request(`/projects/${projectId}/webhooks/${webhookId}`, {
409
+ method: "DELETE"
410
+ });
411
+ }
412
+ // ── Serverless D1 SQL Explorer ────────────────────────────────────────────
413
+ async listSqlTables(projectId) {
414
+ return this.request(`/projects/${projectId}/sql/tables`);
415
+ }
416
+ async executeSqlQuery(projectId, query, params = []) {
417
+ return this.request(`/projects/${projectId}/sql/query`, {
418
+ method: "POST",
419
+ headers: { "Content-Type": "application/json" },
420
+ body: JSON.stringify({ query, params })
421
+ });
422
+ }
423
+ // ── Observability & Quota ─────────────────────────────────────────────────
424
+ async getWorkspaceUsage() {
425
+ const me = await this.getMe();
426
+ const workspaceId = me?.workspace?.id || me?.user?.workspaceId;
427
+ if (!workspaceId) {
428
+ throw new Error("Unable to resolve workspace ID from session.");
429
+ }
430
+ return this.request(`/workspaces/${workspaceId}/usage`);
431
+ }
432
+ };
433
+
434
+ // src/tools/projects.ts
435
+ import { z } from "zod";
436
+ function registerProjectTools(server, client) {
437
+ server.tool(
438
+ "taghost_project_create",
439
+ "Create a new project on TagHost edge platform.",
440
+ {
441
+ name: z.string().describe('Human readable name of the project (e.g. "Acme Storefront")'),
442
+ slug: z.string().optional().describe('URL slug for the project (e.g. "acme-storefront")'),
443
+ framework: z.string().optional().describe('Framework template (e.g. "html", "react", "nextjs", "vue")')
444
+ },
445
+ async ({ name, slug, framework }) => {
446
+ try {
447
+ const result = await client.createProject({ name, slug, framework });
448
+ return {
449
+ content: [
450
+ {
451
+ type: "text",
452
+ text: JSON.stringify(
453
+ {
454
+ success: true,
455
+ message: `Project "${name}" created successfully.`,
456
+ project: result.project || result
457
+ },
458
+ null,
459
+ 2
460
+ )
461
+ }
462
+ ]
463
+ };
464
+ } catch (err) {
465
+ return {
466
+ isError: true,
467
+ content: [{ type: "text", text: `Failed to create project: ${err.message}` }]
468
+ };
469
+ }
470
+ }
471
+ );
472
+ server.tool(
473
+ "taghost_project_list",
474
+ "List all projects accessible within the current TagHost workspace.",
475
+ {
476
+ limit: z.number().optional().describe("Maximum number of projects to return (default: 50)")
477
+ },
478
+ async ({ limit }) => {
479
+ try {
480
+ const result = await client.listProjects();
481
+ const list = Array.isArray(result) ? result : result.projects || [];
482
+ const items = limit ? list.slice(0, limit) : list;
483
+ return {
484
+ content: [
485
+ {
486
+ type: "text",
487
+ text: JSON.stringify({ success: true, count: items.length, projects: items }, null, 2)
488
+ }
489
+ ]
490
+ };
491
+ } catch (err) {
492
+ return {
493
+ isError: true,
494
+ content: [{ type: "text", text: `Failed to list projects: ${err.message}` }]
495
+ };
496
+ }
497
+ }
498
+ );
499
+ server.tool(
500
+ "taghost_project_get",
501
+ "Get detailed information about a specific TagHost project, including active deployment and domains.",
502
+ {
503
+ projectId: z.string().optional().describe('Project ID (e.g. "proj_..."). Defaults to active project.')
504
+ },
505
+ async ({ projectId }) => {
506
+ try {
507
+ const id = await client.resolveProjectId(projectId);
508
+ const result = await client.getProject(id);
509
+ return {
510
+ content: [
511
+ {
512
+ type: "text",
513
+ text: JSON.stringify({ success: true, project: result.project || result }, null, 2)
514
+ }
515
+ ]
516
+ };
517
+ } catch (err) {
518
+ return {
519
+ isError: true,
520
+ content: [{ type: "text", text: `Failed to get project: ${err.message}` }]
521
+ };
522
+ }
523
+ }
524
+ );
525
+ server.tool(
526
+ "taghost_env_manage",
527
+ "Manage environment variables for a TagHost project.",
528
+ {
529
+ projectId: z.string().optional().describe("Project ID. Defaults to active project."),
530
+ action: z.enum(["list", "set", "delete"]).describe("Action to perform"),
531
+ key: z.string().optional().describe("Environment variable key"),
532
+ value: z.string().optional().describe("Environment variable value (for set action)"),
533
+ target: z.enum(["production", "preview", "all"]).optional().describe("Deployment target")
534
+ },
535
+ async ({ projectId, action, key, value, target }) => {
536
+ try {
537
+ const id = await client.resolveProjectId(projectId);
538
+ if (action === "list") {
539
+ const res = await client.getProjectEnv(id);
540
+ return {
541
+ content: [{ type: "text", text: JSON.stringify({ success: true, envVars: res }, null, 2) }]
542
+ };
543
+ }
544
+ if (action === "set") {
545
+ if (!key || value === void 0) {
546
+ return {
547
+ isError: true,
548
+ content: [{ type: "text", text: 'Both key and value are required for "set" action.' }]
549
+ };
550
+ }
551
+ const res = await client.setProjectEnv(id, key, value, target || "all");
552
+ return {
553
+ content: [
554
+ {
555
+ type: "text",
556
+ text: JSON.stringify({ success: true, message: `Environment variable "${key}" set.`, result: res }, null, 2)
557
+ }
558
+ ]
559
+ };
560
+ }
561
+ if (action === "delete") {
562
+ if (!key) {
563
+ return { isError: true, content: [{ type: "text", text: 'Key is required for "delete" action.' }] };
564
+ }
565
+ await client.deleteProjectEnv(id, key);
566
+ return {
567
+ content: [
568
+ {
569
+ type: "text",
570
+ text: JSON.stringify({ success: true, message: `Environment variable "${key}" deleted.` }, null, 2)
571
+ }
572
+ ]
573
+ };
574
+ }
575
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
576
+ } catch (err) {
577
+ return {
578
+ isError: true,
579
+ content: [{ type: "text", text: `Failed to manage env vars: ${err.message}` }]
580
+ };
581
+ }
582
+ }
583
+ );
584
+ }
585
+
586
+ // src/tools/deployments.ts
587
+ import path4 from "path";
588
+ import { z as z2 } from "zod";
589
+
590
+ // src/utils/bundle.ts
591
+ import fs3 from "fs";
592
+ import path3 from "path";
593
+ import { zipSync } from "fflate";
594
+ var IGNORED_ENTRIES = /* @__PURE__ */ new Set([
595
+ ".DS_Store",
596
+ "Thumbs.db",
597
+ "desktop.ini",
598
+ "__MACOSX",
599
+ "node_modules",
600
+ ".git",
601
+ ".turbo",
602
+ ".next",
603
+ ".taghost"
604
+ ]);
605
+ function bundleDirectory(dirPath) {
606
+ const resolved = path3.resolve(dirPath);
607
+ if (!fs3.existsSync(resolved) || !fs3.statSync(resolved).isDirectory()) {
608
+ throw new Error(`Directory does not exist or is not a directory: ${resolved}`);
609
+ }
610
+ const filesRecord = {};
611
+ const fileList = [];
612
+ let totalBytes = 0;
613
+ function walk(currentDir, relativePrefix = "") {
614
+ const items = fs3.readdirSync(currentDir);
615
+ for (const item of items) {
616
+ if (IGNORED_ENTRIES.has(item)) continue;
617
+ const fullPath = path3.join(currentDir, item);
618
+ const relativePath = relativePrefix ? `${relativePrefix}/${item}` : item;
619
+ const stat = fs3.statSync(fullPath);
620
+ if (stat.isDirectory()) {
621
+ walk(fullPath, relativePath);
622
+ } else if (stat.isFile()) {
623
+ const content = fs3.readFileSync(fullPath);
624
+ filesRecord[relativePath] = content;
625
+ fileList.push(relativePath);
626
+ totalBytes += content.byteLength;
627
+ }
628
+ }
629
+ }
630
+ walk(resolved);
631
+ if (fileList.length === 0) {
632
+ throw new Error(`Directory is empty: ${resolved}`);
633
+ }
634
+ const zipBuffer = zipSync(filesRecord, { level: 6 });
635
+ return {
636
+ zipBuffer,
637
+ fileCount: fileList.length,
638
+ totalBytes,
639
+ fileList
640
+ };
641
+ }
642
+ function bundleVirtualFiles(files) {
643
+ const filesRecord = {};
644
+ const fileList = [];
645
+ let totalBytes = 0;
646
+ for (const [filePath, content] of Object.entries(files)) {
647
+ const normalized = filePath.replace(/^[/\\]+/, "");
648
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
649
+ filesRecord[normalized] = bytes;
650
+ fileList.push(normalized);
651
+ totalBytes += bytes.byteLength;
652
+ }
653
+ if (fileList.length === 0) {
654
+ throw new Error("No files provided in bundle");
655
+ }
656
+ const zipBuffer = zipSync(filesRecord, { level: 6 });
657
+ return {
658
+ zipBuffer,
659
+ fileCount: fileList.length,
660
+ totalBytes,
661
+ fileList
662
+ };
663
+ }
664
+
665
+ // src/tools/deployments.ts
666
+ function registerDeploymentTools(server, client) {
667
+ server.tool(
668
+ "taghost_deploy_bundle",
669
+ "Deploy a local directory of static web assets to TagHost edge CDN via direct ZIP archive ingestion.",
670
+ {
671
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
672
+ directoryPath: z2.string().describe('Absolute or relative path to the build directory (e.g. "./dist", "./out", "./public")'),
673
+ branch: z2.string().optional().describe('Git branch reference (default: "main")'),
674
+ preview: z2.boolean().optional().describe("Whether to deploy as an ephemeral preview instead of production (default: false)"),
675
+ commitMessage: z2.string().optional().describe("Deployment description or commit message")
676
+ },
677
+ async ({ projectId, directoryPath, branch, preview, commitMessage }) => {
678
+ try {
679
+ const id = await client.resolveProjectId(projectId);
680
+ const resolvedDir = path4.resolve(process.cwd(), directoryPath);
681
+ const bundle = bundleDirectory(resolvedDir);
682
+ const result = await client.deployBundle(id, bundle.zipBuffer, {
683
+ branch: branch || "main",
684
+ preview: preview || false,
685
+ commitMessage: commitMessage || `MCP deploy: ${bundle.fileCount} assets (${Math.round(bundle.totalBytes / 1024)} KB)`
686
+ });
687
+ return {
688
+ content: [
689
+ {
690
+ type: "text",
691
+ text: JSON.stringify(
692
+ {
693
+ success: true,
694
+ deploymentId: result.deploymentId || result.id,
695
+ previewUrl: result.previewUrl,
696
+ liveUrl: result.liveUrl,
697
+ fileCount: bundle.fileCount,
698
+ totalBytes: bundle.totalBytes,
699
+ message: "Bundle uploaded and deployed to edge successfully."
700
+ },
701
+ null,
702
+ 2
703
+ )
704
+ }
705
+ ]
706
+ };
707
+ } catch (err) {
708
+ return {
709
+ isError: true,
710
+ content: [{ type: "text", text: `Failed to deploy bundle: ${err.message}` }]
711
+ };
712
+ }
713
+ }
714
+ );
715
+ server.tool(
716
+ "taghost_publish_files",
717
+ "Publish or update specific static files (HTML, CSS, JS) non-destructively. Automatically carries forward all other existing files from the active deployment without clobbering them.",
718
+ {
719
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
720
+ files: z2.record(z2.string()).describe('Map of file paths to their string content (e.g. { "store.html": "...", "products.html": "..." })'),
721
+ deletedPaths: z2.array(z2.string()).optional().describe("Optional list of paths to delete"),
722
+ message: z2.string().optional().describe("Commit or publish description")
723
+ },
724
+ async ({ projectId, files, deletedPaths, message }) => {
725
+ try {
726
+ const id = await client.resolveProjectId(projectId);
727
+ const result = await client.publishProjectFiles(id, {
728
+ files,
729
+ deletedPaths,
730
+ message: message || "MCP non-destructive file publish"
731
+ });
732
+ return {
733
+ content: [
734
+ {
735
+ type: "text",
736
+ text: JSON.stringify(
737
+ {
738
+ success: true,
739
+ deploymentId: result.deploymentId,
740
+ previewUrl: result.previewUrl,
741
+ liveUrl: result.liveUrl,
742
+ updatedFiles: Object.keys(files),
743
+ deletedFiles: deletedPaths || [],
744
+ message: "Files published non-destructively; existing website assets preserved."
745
+ },
746
+ null,
747
+ 2
748
+ )
749
+ }
750
+ ]
751
+ };
752
+ } catch (err) {
753
+ return {
754
+ isError: true,
755
+ content: [{ type: "text", text: `Failed to publish files: ${err.message}` }]
756
+ };
757
+ }
758
+ }
759
+ );
760
+ server.tool(
761
+ "taghost_deployment_status",
762
+ "Check deployment status, preview and live edge URLs for a project.",
763
+ {
764
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project.")
765
+ },
766
+ async ({ projectId }) => {
767
+ try {
768
+ const id = await client.resolveProjectId(projectId);
769
+ const project = await client.getProject(id);
770
+ const deployments = await client.listDeployments(id);
771
+ return {
772
+ content: [
773
+ {
774
+ type: "text",
775
+ text: JSON.stringify(
776
+ {
777
+ success: true,
778
+ projectId: id,
779
+ name: project.name,
780
+ activeDeploymentId: project.activeDeploymentId,
781
+ slug: project.slug,
782
+ customDomain: project.customDomain,
783
+ liveUrl: project.customDomain ? `https://${project.customDomain}` : `https://${project.slug}.taghost.site`,
784
+ recentDeployments: Array.isArray(deployments) ? deployments.slice(0, 5) : deployments?.deployments?.slice(0, 5) || []
785
+ },
786
+ null,
787
+ 2
788
+ )
789
+ }
790
+ ]
791
+ };
792
+ } catch (err) {
793
+ return {
794
+ isError: true,
795
+ content: [{ type: "text", text: `Failed to fetch deployment status: ${err.message}` }]
796
+ };
797
+ }
798
+ }
799
+ );
800
+ server.tool(
801
+ "taghost_deployment_rollback",
802
+ "Perform an instant atomic rollback to a previous deployment.",
803
+ {
804
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
805
+ deploymentId: z2.string().describe('The deployment ID to roll back to (e.g. "dep_...")')
806
+ },
807
+ async ({ projectId, deploymentId }) => {
808
+ try {
809
+ const id = await client.resolveProjectId(projectId);
810
+ const result = await client.rollbackDeployment(id, deploymentId);
811
+ return {
812
+ content: [
813
+ {
814
+ type: "text",
815
+ text: JSON.stringify(
816
+ {
817
+ success: true,
818
+ message: `Project rolled back successfully to ${deploymentId}.`,
819
+ result
820
+ },
821
+ null,
822
+ 2
823
+ )
824
+ }
825
+ ]
826
+ };
827
+ } catch (err) {
828
+ return {
829
+ isError: true,
830
+ content: [{ type: "text", text: `Failed to rollback deployment: ${err.message}` }]
831
+ };
832
+ }
833
+ }
834
+ );
835
+ server.tool(
836
+ "taghost_deployment_set_expiry",
837
+ "Configure ephemeral preview auto-expiry TTL or disable expiry for a deployment.",
838
+ {
839
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
840
+ deploymentId: z2.string().describe('Deployment ID (e.g. "dep_...")'),
841
+ ttlSeconds: z2.number().optional().describe("Time to live in seconds (e.g. 7200 for 2 hours)"),
842
+ neverExpire: z2.boolean().optional().describe("Set to true to retain deployment indefinitely")
843
+ },
844
+ async ({ projectId, deploymentId, ttlSeconds, neverExpire }) => {
845
+ try {
846
+ const id = await client.resolveProjectId(projectId);
847
+ const result = await client.setDeploymentExpiry(id, deploymentId, ttlSeconds, neverExpire);
848
+ return {
849
+ content: [
850
+ {
851
+ type: "text",
852
+ text: JSON.stringify(
853
+ {
854
+ success: true,
855
+ deploymentId,
856
+ neverExpire: Boolean(neverExpire),
857
+ ttlSeconds,
858
+ result
859
+ },
860
+ null,
861
+ 2
862
+ )
863
+ }
864
+ ]
865
+ };
866
+ } catch (err) {
867
+ return {
868
+ isError: true,
869
+ content: [{ type: "text", text: `Failed to set deployment expiry: ${err.message}` }]
870
+ };
871
+ }
872
+ }
873
+ );
874
+ }
875
+
876
+ // src/tools/mail.ts
877
+ import { z as z3 } from "zod";
878
+ function registerMailTools(server, client) {
879
+ server.tool(
880
+ "taghost_mail_threads_list",
881
+ "Check mail: list email threads and messages in the TagMail inbox with search and mailbox filters.",
882
+ {
883
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
884
+ mailboxId: z3.string().optional().describe("Filter by specific mailbox ID"),
885
+ query: z3.string().optional().describe("Search query for sender, subject or body text"),
886
+ limit: z3.number().optional().describe("Maximum number of threads to return (default: 25)")
887
+ },
888
+ async ({ projectId, mailboxId, query, limit }) => {
889
+ try {
890
+ const id = await client.resolveProjectId(projectId);
891
+ const result = await client.listMailThreads(id, { mailboxId, query, limit: limit || 25 });
892
+ const threads = Array.isArray(result) ? result : result.threads || [];
893
+ return {
894
+ content: [
895
+ {
896
+ type: "text",
897
+ text: JSON.stringify(
898
+ {
899
+ success: true,
900
+ count: threads.length,
901
+ threads: threads.map((t) => ({
902
+ id: t.id,
903
+ subject: t.subject || "(no subject)",
904
+ from: t.fromAddress || t.snippetSender,
905
+ snippet: t.snippet,
906
+ unread: Boolean(t.unread),
907
+ messageCount: t.messageCount || 1,
908
+ receivedAt: t.lastMessageAt || t.receivedAt || t.createdAt
909
+ }))
910
+ },
911
+ null,
912
+ 2
913
+ )
914
+ }
915
+ ]
916
+ };
917
+ } catch (err) {
918
+ return {
919
+ isError: true,
920
+ content: [{ type: "text", text: `Failed to check mail: ${err.message}` }]
921
+ };
922
+ }
923
+ }
924
+ );
925
+ server.tool(
926
+ "taghost_mail_thread_get",
927
+ "Read the full contents of an email thread, including all inbound and outbound messages and attachment metadata.",
928
+ {
929
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
930
+ threadId: z3.string().describe("The email thread ID to retrieve")
931
+ },
932
+ async ({ projectId, threadId }) => {
933
+ try {
934
+ const id = await client.resolveProjectId(projectId);
935
+ const result = await client.getMailThread(id, threadId);
936
+ return {
937
+ content: [
938
+ {
939
+ type: "text",
940
+ text: JSON.stringify({ success: true, thread: result.thread || result }, null, 2)
941
+ }
942
+ ]
943
+ };
944
+ } catch (err) {
945
+ return {
946
+ isError: true,
947
+ content: [{ type: "text", text: `Failed to read mail thread: ${err.message}` }]
948
+ };
949
+ }
950
+ }
951
+ );
952
+ server.tool(
953
+ "taghost_mail_send",
954
+ "Send an email from a TagMail mailbox.",
955
+ {
956
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
957
+ mailboxId: z3.string().optional().describe("Sender mailbox ID (defaults to project primary mailbox)"),
958
+ to: z3.string().describe("Recipient email address"),
959
+ subject: z3.string().describe("Email subject line"),
960
+ text: z3.string().optional().describe("Plain text body content"),
961
+ html: z3.string().optional().describe("HTML formatted body content"),
962
+ cc: z3.array(z3.string()).optional().describe("Optional CC recipients"),
963
+ bcc: z3.array(z3.string()).optional().describe("Optional BCC recipients")
964
+ },
965
+ async ({ projectId, mailboxId, to, subject, text, html, cc, bcc }) => {
966
+ try {
967
+ const id = await client.resolveProjectId(projectId);
968
+ const result = await client.sendMail(id, {
969
+ mailboxId,
970
+ to,
971
+ subject,
972
+ text,
973
+ html,
974
+ cc,
975
+ bcc
976
+ });
977
+ return {
978
+ content: [
979
+ {
980
+ type: "text",
981
+ text: JSON.stringify(
982
+ {
983
+ success: true,
984
+ message: `Email sent to ${to} successfully.`,
985
+ result
986
+ },
987
+ null,
988
+ 2
989
+ )
990
+ }
991
+ ]
992
+ };
993
+ } catch (err) {
994
+ return {
995
+ isError: true,
996
+ content: [{ type: "text", text: `Failed to send email: ${err.message}` }]
997
+ };
998
+ }
999
+ }
1000
+ );
1001
+ server.tool(
1002
+ "taghost_mail_create_mailbox",
1003
+ 'Provision a new corporate mailbox (e.g. "sales@acme.com" or "hello@acme.com") on TagHost.',
1004
+ {
1005
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
1006
+ localPart: z3.string().describe('Local part of address before @ (e.g. "support", "orders", "hello")'),
1007
+ domain: z3.string().optional().describe("Domain name for mailbox (defaults to project custom domain)"),
1008
+ displayName: z3.string().optional().describe('Friendly display name (e.g. "Support Team")'),
1009
+ password: z3.string().optional().describe("Initial password for Webmail/IMAP/SMTP access")
1010
+ },
1011
+ async ({ projectId, localPart, domain, displayName, password }) => {
1012
+ try {
1013
+ const id = await client.resolveProjectId(projectId);
1014
+ const result = await client.createMailbox(id, {
1015
+ localPart,
1016
+ domain,
1017
+ displayName,
1018
+ password
1019
+ });
1020
+ return {
1021
+ content: [
1022
+ {
1023
+ type: "text",
1024
+ text: JSON.stringify(
1025
+ {
1026
+ success: true,
1027
+ message: `Mailbox "${localPart}@${domain || "custom-domain"}" created.`,
1028
+ mailbox: result.mailbox || result
1029
+ },
1030
+ null,
1031
+ 2
1032
+ )
1033
+ }
1034
+ ]
1035
+ };
1036
+ } catch (err) {
1037
+ return {
1038
+ isError: true,
1039
+ content: [{ type: "text", text: `Failed to create mailbox: ${err.message}` }]
1040
+ };
1041
+ }
1042
+ }
1043
+ );
1044
+ server.tool(
1045
+ "taghost_mail_domain_verify",
1046
+ "Inspect DNS verification status for corporate email (MX, SPF, DKIM, DMARC records).",
1047
+ {
1048
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
1049
+ domain: z3.string().describe('Domain name to verify (e.g. "acme.com")')
1050
+ },
1051
+ async ({ projectId, domain }) => {
1052
+ try {
1053
+ const id = await client.resolveProjectId(projectId);
1054
+ const result = await client.getMailDomainVerification(id, domain);
1055
+ return {
1056
+ content: [
1057
+ {
1058
+ type: "text",
1059
+ text: JSON.stringify({ success: true, domain, verification: result }, null, 2)
1060
+ }
1061
+ ]
1062
+ };
1063
+ } catch (err) {
1064
+ return {
1065
+ isError: true,
1066
+ content: [{ type: "text", text: `Failed to verify email domain: ${err.message}` }]
1067
+ };
1068
+ }
1069
+ }
1070
+ );
1071
+ }
1072
+
1073
+ // src/tools/domains.ts
1074
+ import { z as z4 } from "zod";
1075
+ function registerDomainTools(server, client) {
1076
+ server.tool(
1077
+ "taghost_domain_check",
1078
+ "Check domain availability and wholesale registration price.",
1079
+ {
1080
+ domain: z4.string().describe('Domain name to check (e.g. "mybusiness.com", "boutique.ng")')
1081
+ },
1082
+ async ({ domain }) => {
1083
+ try {
1084
+ const result = await client.checkDomainAvailability(domain);
1085
+ return {
1086
+ content: [
1087
+ {
1088
+ type: "text",
1089
+ text: JSON.stringify({ success: true, domain, ...result }, null, 2)
1090
+ }
1091
+ ]
1092
+ };
1093
+ } catch (err) {
1094
+ return {
1095
+ isError: true,
1096
+ content: [{ type: "text", text: `Failed to check domain: ${err.message}` }]
1097
+ };
1098
+ }
1099
+ }
1100
+ );
1101
+ server.tool(
1102
+ "taghost_domain_search",
1103
+ "Search available domains and get TLD suggestions for a brand or business name.",
1104
+ {
1105
+ query: z4.string().describe('Search query or brand name (e.g. "lumiere", "craftbakery")')
1106
+ },
1107
+ async ({ query }) => {
1108
+ try {
1109
+ const result = await client.searchDomains(query);
1110
+ return {
1111
+ content: [
1112
+ {
1113
+ type: "text",
1114
+ text: JSON.stringify({ success: true, query, results: result }, null, 2)
1115
+ }
1116
+ ]
1117
+ };
1118
+ } catch (err) {
1119
+ return {
1120
+ isError: true,
1121
+ content: [{ type: "text", text: `Failed to search domains: ${err.message}` }]
1122
+ };
1123
+ }
1124
+ }
1125
+ );
1126
+ server.tool(
1127
+ "taghost_domain_checkout",
1128
+ "Purchase and automatically register a custom domain for a TagHost project.",
1129
+ {
1130
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1131
+ domain: z4.string().describe('Domain name to register (e.g. "acmestore.com")'),
1132
+ years: z4.number().optional().describe("Registration duration in years (default: 1)"),
1133
+ registrantContact: z4.object({
1134
+ name: z4.string().describe("Contact full name"),
1135
+ email: z4.string().describe("Contact email address"),
1136
+ phone: z4.string().optional().describe("Phone number in international format"),
1137
+ org: z4.string().optional().describe("Company or organization name")
1138
+ }).optional().describe("Registrant contact details")
1139
+ },
1140
+ async ({ projectId, domain, years, registrantContact }) => {
1141
+ try {
1142
+ const id = await client.resolveProjectId(projectId);
1143
+ const result = await client.checkoutDomain(id, {
1144
+ domain,
1145
+ years: years || 1,
1146
+ registrantContact
1147
+ });
1148
+ return {
1149
+ content: [
1150
+ {
1151
+ type: "text",
1152
+ text: JSON.stringify(
1153
+ {
1154
+ success: true,
1155
+ message: `Domain checkout initialized for ${domain}.`,
1156
+ result
1157
+ },
1158
+ null,
1159
+ 2
1160
+ )
1161
+ }
1162
+ ]
1163
+ };
1164
+ } catch (err) {
1165
+ return {
1166
+ isError: true,
1167
+ content: [{ type: "text", text: `Failed to checkout domain: ${err.message}` }]
1168
+ };
1169
+ }
1170
+ }
1171
+ );
1172
+ server.tool(
1173
+ "taghost_domain_attach",
1174
+ "Attach an external or owned domain (Bring-Your-Own-Domain) to a TagHost project.",
1175
+ {
1176
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1177
+ domain: z4.string().describe('Domain name to map (e.g. "shop.example.com" or "example.com")')
1178
+ },
1179
+ async ({ projectId, domain }) => {
1180
+ try {
1181
+ const id = await client.resolveProjectId(projectId);
1182
+ const result = await client.attachDomain(id, domain);
1183
+ return {
1184
+ content: [
1185
+ {
1186
+ type: "text",
1187
+ text: JSON.stringify(
1188
+ {
1189
+ success: true,
1190
+ domain,
1191
+ message: `Domain attached. Configure your DNS CNAME/A records to point to TagHost edge.`,
1192
+ result
1193
+ },
1194
+ null,
1195
+ 2
1196
+ )
1197
+ }
1198
+ ]
1199
+ };
1200
+ } catch (err) {
1201
+ return {
1202
+ isError: true,
1203
+ content: [{ type: "text", text: `Failed to attach domain: ${err.message}` }]
1204
+ };
1205
+ }
1206
+ }
1207
+ );
1208
+ server.tool(
1209
+ "taghost_domain_verify",
1210
+ "Trigger verification of custom domain DNS configuration and edge SSL certificate issuance.",
1211
+ {
1212
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1213
+ domain: z4.string().describe("Domain name to verify")
1214
+ },
1215
+ async ({ projectId, domain }) => {
1216
+ try {
1217
+ const id = await client.resolveProjectId(projectId);
1218
+ const result = await client.verifyDomain(id, domain);
1219
+ return {
1220
+ content: [
1221
+ {
1222
+ type: "text",
1223
+ text: JSON.stringify({ success: true, domain, result }, null, 2)
1224
+ }
1225
+ ]
1226
+ };
1227
+ } catch (err) {
1228
+ return {
1229
+ isError: true,
1230
+ content: [{ type: "text", text: `Failed to verify domain: ${err.message}` }]
1231
+ };
1232
+ }
1233
+ }
1234
+ );
1235
+ server.tool(
1236
+ "taghost_dns_manage",
1237
+ "Manage DNS records (list, create, update, delete) for a TagHost-managed domain.",
1238
+ {
1239
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1240
+ domain: z4.string().describe("Domain name with TagHost DNS zone"),
1241
+ action: z4.enum(["list", "create", "update", "delete"]).describe("Action to perform"),
1242
+ record: z4.object({
1243
+ id: z4.string().optional().describe("Record ID (for update or delete)"),
1244
+ type: z4.string().optional().describe("DNS Record Type: A, AAAA, CNAME, TXT, MX"),
1245
+ name: z4.string().optional().describe('Host name (e.g. "@", "www", "mail")'),
1246
+ content: z4.string().optional().describe("Value or target IP/host"),
1247
+ ttl: z4.number().optional().describe("Time to live in seconds (default: 3600)"),
1248
+ priority: z4.number().optional().describe("Priority for MX records")
1249
+ }).optional().describe("DNS record properties")
1250
+ },
1251
+ async ({ projectId, domain, action, record }) => {
1252
+ try {
1253
+ const id = await client.resolveProjectId(projectId);
1254
+ if (action === "list") {
1255
+ const records = await client.listDnsRecords(id, domain);
1256
+ return {
1257
+ content: [{ type: "text", text: JSON.stringify({ success: true, domain, records }, null, 2) }]
1258
+ };
1259
+ }
1260
+ if (action === "create") {
1261
+ if (!record?.type || !record?.name || !record?.content) {
1262
+ return {
1263
+ isError: true,
1264
+ content: [{ type: "text", text: "type, name, and content are required to create a DNS record." }]
1265
+ };
1266
+ }
1267
+ const res = await client.createDnsRecord(id, domain, {
1268
+ type: record.type,
1269
+ name: record.name,
1270
+ content: record.content,
1271
+ ttl: record.ttl,
1272
+ priority: record.priority
1273
+ });
1274
+ return {
1275
+ content: [
1276
+ {
1277
+ type: "text",
1278
+ text: JSON.stringify({ success: true, message: "DNS record created.", result: res }, null, 2)
1279
+ }
1280
+ ]
1281
+ };
1282
+ }
1283
+ if (action === "update") {
1284
+ if (!record?.id) {
1285
+ return { isError: true, content: [{ type: "text", text: "Record ID is required for update." }] };
1286
+ }
1287
+ const res = await client.updateDnsRecord(id, domain, record.id, {
1288
+ type: record.type,
1289
+ name: record.name,
1290
+ content: record.content,
1291
+ ttl: record.ttl,
1292
+ priority: record.priority
1293
+ });
1294
+ return {
1295
+ content: [
1296
+ {
1297
+ type: "text",
1298
+ text: JSON.stringify({ success: true, message: "DNS record updated.", result: res }, null, 2)
1299
+ }
1300
+ ]
1301
+ };
1302
+ }
1303
+ if (action === "delete") {
1304
+ if (!record?.id) {
1305
+ return { isError: true, content: [{ type: "text", text: "Record ID is required for delete." }] };
1306
+ }
1307
+ await client.deleteDnsRecord(id, domain, record.id);
1308
+ return {
1309
+ content: [
1310
+ {
1311
+ type: "text",
1312
+ text: JSON.stringify({ success: true, message: `DNS record ${record.id} deleted.` }, null, 2)
1313
+ }
1314
+ ]
1315
+ };
1316
+ }
1317
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
1318
+ } catch (err) {
1319
+ return {
1320
+ isError: true,
1321
+ content: [{ type: "text", text: `Failed to manage DNS: ${err.message}` }]
1322
+ };
1323
+ }
1324
+ }
1325
+ );
1326
+ }
1327
+
1328
+ // src/tools/commerce.ts
1329
+ import { z as z5 } from "zod";
1330
+ function registerCommerceTools(server, client) {
1331
+ server.tool(
1332
+ "taghost_commerce_config",
1333
+ "Configure store commerce settings: store installation mode (companion or standalone), currency, theme, and payment gateway (Paystack or Stripe).",
1334
+ {
1335
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1336
+ currency: z5.string().optional().describe('Store currency code (e.g. "USD", "EUR", "GBP", "NGN", "CAD")'),
1337
+ storeMode: z5.enum(["companion", "standalone"]).optional().describe('Storefront installation mode: "companion" (preserves existing site, adds /store.html) or "standalone" (store is main site)'),
1338
+ gateway: z5.object({
1339
+ provider: z5.enum(["paystack", "stripe"]).describe("Payment provider"),
1340
+ publicKey: z5.string().optional().describe("Client-side public or publishable key"),
1341
+ secretKey: z5.string().optional().describe("Server-side secret key (securely vaulted)"),
1342
+ testMode: z5.boolean().optional().describe("Enable test/sandbox mode"),
1343
+ enabled: z5.boolean().optional().describe("Enable or disable this payment gateway")
1344
+ }).optional().describe("Payment gateway configuration")
1345
+ },
1346
+ async ({ projectId, currency, storeMode, gateway }) => {
1347
+ try {
1348
+ const id = await client.resolveProjectId(projectId);
1349
+ const updates = {};
1350
+ if (currency || storeMode) {
1351
+ const currentTheme = await client.getCommerceTheme(id).catch(() => ({}));
1352
+ const themePayload = {
1353
+ ...currentTheme,
1354
+ ...currency ? { currency } : {},
1355
+ ...storeMode ? { storeMode } : {}
1356
+ };
1357
+ const themeRes = await client.updateCommerceTheme(id, themePayload);
1358
+ updates.theme = themeRes;
1359
+ }
1360
+ if (gateway) {
1361
+ const gwRes = await client.updateCommerceGateway(id, gateway.provider, {
1362
+ publicKey: gateway.publicKey,
1363
+ secretKey: gateway.secretKey,
1364
+ testMode: gateway.testMode ?? false,
1365
+ enabled: gateway.enabled ?? true
1366
+ });
1367
+ updates.gateway = gwRes;
1368
+ }
1369
+ return {
1370
+ content: [
1371
+ {
1372
+ type: "text",
1373
+ text: JSON.stringify(
1374
+ {
1375
+ success: true,
1376
+ message: "Commerce settings updated successfully.",
1377
+ projectId: id,
1378
+ updates
1379
+ },
1380
+ null,
1381
+ 2
1382
+ )
1383
+ }
1384
+ ]
1385
+ };
1386
+ } catch (err) {
1387
+ return {
1388
+ isError: true,
1389
+ content: [{ type: "text", text: `Failed to configure commerce: ${err.message}` }]
1390
+ };
1391
+ }
1392
+ }
1393
+ );
1394
+ server.tool(
1395
+ "taghost_commerce_orders_list",
1396
+ "List customer orders placed on the TagHost store with fulfillment status filtering.",
1397
+ {
1398
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1399
+ status: z5.enum(["pending", "paid", "fulfilled", "delivered", "cancelled", "refunded"]).optional().describe("Filter orders by status"),
1400
+ limit: z5.number().optional().describe("Maximum number of orders to return (default: 50)")
1401
+ },
1402
+ async ({ projectId, status, limit }) => {
1403
+ try {
1404
+ const id = await client.resolveProjectId(projectId);
1405
+ const result = await client.listOrders(id, { status, limit: limit || 50 });
1406
+ const orders = Array.isArray(result) ? result : result.orders || [];
1407
+ return {
1408
+ content: [
1409
+ {
1410
+ type: "text",
1411
+ text: JSON.stringify(
1412
+ {
1413
+ success: true,
1414
+ count: orders.length,
1415
+ orders: orders.map((o) => ({
1416
+ id: o.id,
1417
+ orderNumber: o.orderNumber || o.id,
1418
+ status: o.status,
1419
+ totalAmount: o.totalAmount || o.amount,
1420
+ currency: o.currency || "USD",
1421
+ customerEmail: o.customerEmail || o.email,
1422
+ itemCount: o.items?.length || 1,
1423
+ items: o.items,
1424
+ createdAt: o.createdAt
1425
+ }))
1426
+ },
1427
+ null,
1428
+ 2
1429
+ )
1430
+ }
1431
+ ]
1432
+ };
1433
+ } catch (err) {
1434
+ return {
1435
+ isError: true,
1436
+ content: [{ type: "text", text: `Failed to list orders: ${err.message}` }]
1437
+ };
1438
+ }
1439
+ }
1440
+ );
1441
+ server.tool(
1442
+ "taghost_commerce_order_fulfill",
1443
+ "Mark an order as fulfilled or delivered and update customer tracking details.",
1444
+ {
1445
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1446
+ orderId: z5.string().describe('The order ID to update (e.g. "ord_...")'),
1447
+ status: z5.enum(["fulfilled", "delivered", "cancelled"]).describe("New fulfillment status"),
1448
+ trackingNumber: z5.string().optional().describe("Shipment tracking number"),
1449
+ trackingCarrier: z5.string().optional().describe('Shipping carrier (e.g. "DHL", "FedEx", "USPS", "GIG Logistics")'),
1450
+ trackingUrl: z5.string().optional().describe("Direct link to carrier parcel tracker")
1451
+ },
1452
+ async ({ projectId, orderId, status, trackingNumber, trackingCarrier, trackingUrl }) => {
1453
+ try {
1454
+ const id = await client.resolveProjectId(projectId);
1455
+ const result = await client.updateOrder(id, orderId, {
1456
+ status,
1457
+ trackingNumber,
1458
+ trackingCarrier,
1459
+ trackingUrl
1460
+ });
1461
+ return {
1462
+ content: [
1463
+ {
1464
+ type: "text",
1465
+ text: JSON.stringify(
1466
+ {
1467
+ success: true,
1468
+ orderId,
1469
+ status,
1470
+ tracking: trackingNumber ? { carrier: trackingCarrier, number: trackingNumber, url: trackingUrl } : null,
1471
+ message: `Order ${orderId} marked as ${status}.`,
1472
+ result
1473
+ },
1474
+ null,
1475
+ 2
1476
+ )
1477
+ }
1478
+ ]
1479
+ };
1480
+ } catch (err) {
1481
+ return {
1482
+ isError: true,
1483
+ content: [{ type: "text", text: `Failed to fulfill order: ${err.message}` }]
1484
+ };
1485
+ }
1486
+ }
1487
+ );
1488
+ server.tool(
1489
+ "taghost_coupon_manage",
1490
+ "Manage discount coupons and promotional codes for the store.",
1491
+ {
1492
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1493
+ action: z5.enum(["list", "create", "delete"]).describe("Action to perform"),
1494
+ coupon: z5.object({
1495
+ id: z5.string().optional().describe("Coupon ID (for delete)"),
1496
+ code: z5.string().optional().describe('Promo code entered by shopper (e.g. "WELCOME10", "BLACKFRIDAY")'),
1497
+ discountType: z5.enum(["percentage", "fixed"]).optional().describe("Discount calculation type"),
1498
+ discountAmount: z5.number().optional().describe("Discount value (e.g. 15 for 15% or 20 for $20 off)"),
1499
+ maxUses: z5.number().optional().describe("Maximum number of redemptions allowed"),
1500
+ expiresAt: z5.number().optional().describe("Unix timestamp in milliseconds for expiration")
1501
+ }).optional().describe("Coupon details")
1502
+ },
1503
+ async ({ projectId, action, coupon }) => {
1504
+ try {
1505
+ const id = await client.resolveProjectId(projectId);
1506
+ if (action === "list") {
1507
+ const list = await client.listCoupons(id);
1508
+ return {
1509
+ content: [{ type: "text", text: JSON.stringify({ success: true, coupons: list }, null, 2) }]
1510
+ };
1511
+ }
1512
+ if (action === "create") {
1513
+ if (!coupon?.code || !coupon?.discountType || coupon?.discountAmount === void 0) {
1514
+ return {
1515
+ isError: true,
1516
+ content: [{ type: "text", text: "code, discountType, and discountAmount are required to create a coupon." }]
1517
+ };
1518
+ }
1519
+ const res = await client.createCoupon(id, {
1520
+ code: coupon.code.toUpperCase(),
1521
+ discountType: coupon.discountType,
1522
+ discountAmount: coupon.discountAmount,
1523
+ maxUses: coupon.maxUses,
1524
+ expiresAt: coupon.expiresAt
1525
+ });
1526
+ return {
1527
+ content: [
1528
+ {
1529
+ type: "text",
1530
+ text: JSON.stringify({ success: true, message: `Coupon "${coupon.code}" created.`, coupon: res }, null, 2)
1531
+ }
1532
+ ]
1533
+ };
1534
+ }
1535
+ if (action === "delete") {
1536
+ if (!coupon?.id) {
1537
+ return { isError: true, content: [{ type: "text", text: "Coupon ID is required for delete." }] };
1538
+ }
1539
+ await client.deleteCoupon(id, coupon.id);
1540
+ return {
1541
+ content: [
1542
+ {
1543
+ type: "text",
1544
+ text: JSON.stringify({ success: true, message: `Coupon ${coupon.id} deleted.` }, null, 2)
1545
+ }
1546
+ ]
1547
+ };
1548
+ }
1549
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
1550
+ } catch (err) {
1551
+ return {
1552
+ isError: true,
1553
+ content: [{ type: "text", text: `Failed to manage coupons: ${err.message}` }]
1554
+ };
1555
+ }
1556
+ }
1557
+ );
1558
+ }
1559
+
1560
+ // src/tools/collections.ts
1561
+ import { z as z6 } from "zod";
1562
+ function registerCollectionTools(server, client) {
1563
+ server.tool(
1564
+ "taghost_collection_create",
1565
+ 'Create a new CMS or product collection (e.g. "products", "services", "menu", "blog") on TagHost.',
1566
+ {
1567
+ projectId: z6.string().optional().describe("Project ID. Defaults to active project."),
1568
+ name: z6.string().describe('Machine identifier for collection (e.g. "products", "lookbook", "menu")'),
1569
+ displayName: z6.string().optional().describe('Friendly display name (e.g. "Featured Products")'),
1570
+ schemaFields: z6.array(
1571
+ z6.object({
1572
+ name: z6.string().describe("Field key name"),
1573
+ type: z6.enum(["text", "number", "boolean", "image", "json", "relation"]).describe("Field data type"),
1574
+ required: z6.boolean().optional().describe("Whether this field is mandatory")
1575
+ })
1576
+ ).optional().describe("Schema field definitions")
1577
+ },
1578
+ async ({ projectId, name, displayName, schemaFields }) => {
1579
+ try {
1580
+ const id = await client.resolveProjectId(projectId);
1581
+ const result = await client.createCollection(id, {
1582
+ name: name.toLowerCase().replace(/[^a-z0-9_-]/g, "_"),
1583
+ displayName: displayName || name,
1584
+ schemaFields
1585
+ });
1586
+ return {
1587
+ content: [
1588
+ {
1589
+ type: "text",
1590
+ text: JSON.stringify(
1591
+ {
1592
+ success: true,
1593
+ message: `Collection "${name}" created successfully.`,
1594
+ collection: result.collection || result
1595
+ },
1596
+ null,
1597
+ 2
1598
+ )
1599
+ }
1600
+ ]
1601
+ };
1602
+ } catch (err) {
1603
+ return {
1604
+ isError: true,
1605
+ content: [{ type: "text", text: `Failed to create collection: ${err.message}` }]
1606
+ };
1607
+ }
1608
+ }
1609
+ );
1610
+ server.tool(
1611
+ "taghost_collection_item_upsert",
1612
+ "Add or update an item/product in a collection with full e-commerce and CMS metadata (price, images, variants, stock).",
1613
+ {
1614
+ projectId: z6.string().optional().describe("Project ID. Defaults to active project."),
1615
+ collectionIdOrName: z6.string().describe('Collection ID or name (e.g. "products")'),
1616
+ itemId: z6.string().optional().describe("Item ID for updates. Omit to insert a new item."),
1617
+ data: z6.record(z6.any()).describe(
1618
+ 'Item payload properties (e.g. { name: "Silk Blouse", price: 85, currency: "USD", image: "https://...", inventory: 20 })'
1619
+ ),
1620
+ publishImmediately: z6.boolean().optional().describe("Whether to publish to live edge CDN immediately (default: true)")
1621
+ },
1622
+ async ({ projectId, collectionIdOrName, itemId, data, publishImmediately }) => {
1623
+ try {
1624
+ const id = await client.resolveProjectId(projectId);
1625
+ let targetCid = collectionIdOrName;
1626
+ if (!targetCid.startsWith("col_")) {
1627
+ const list = await client.listCollections(id);
1628
+ const collections = Array.isArray(list) ? list : list.collections || [];
1629
+ const matched = collections.find((c) => c.name?.toLowerCase() === collectionIdOrName.toLowerCase());
1630
+ if (matched && matched.id) {
1631
+ targetCid = matched.id;
1632
+ }
1633
+ }
1634
+ const result = await client.upsertCollectionItem(id, targetCid, data, itemId);
1635
+ const createdOrUpdatedId = itemId || result.item?.id || result.id;
1636
+ let publishResult = null;
1637
+ if (publishImmediately !== false && createdOrUpdatedId) {
1638
+ publishResult = await client.publishCollectionItem(id, targetCid, createdOrUpdatedId, true).catch(() => null);
1639
+ }
1640
+ return {
1641
+ content: [
1642
+ {
1643
+ type: "text",
1644
+ text: JSON.stringify(
1645
+ {
1646
+ success: true,
1647
+ collectionId: targetCid,
1648
+ itemId: createdOrUpdatedId,
1649
+ item: result.item || result,
1650
+ publishedToEdge: Boolean(publishResult),
1651
+ message: `Collection item ${itemId ? "updated" : "created"}${publishImmediately !== false ? " and published to edge" : ""}.`
1652
+ },
1653
+ null,
1654
+ 2
1655
+ )
1656
+ }
1657
+ ]
1658
+ };
1659
+ } catch (err) {
1660
+ return {
1661
+ isError: true,
1662
+ content: [{ type: "text", text: `Failed to upsert collection item: ${err.message}` }]
1663
+ };
1664
+ }
1665
+ }
1666
+ );
1667
+ server.tool(
1668
+ "taghost_collection_item_publish",
1669
+ "Publish or unpublish a collection item to/from the live edge CDN index (/_tag/collections/:name).",
1670
+ {
1671
+ projectId: z6.string().optional().describe("Project ID. Defaults to active project."),
1672
+ collectionIdOrName: z6.string().describe("Collection ID or name"),
1673
+ itemId: z6.string().describe("Item ID to publish/unpublish"),
1674
+ action: z6.enum(["publish", "unpublish"]).describe("Action to perform")
1675
+ },
1676
+ async ({ projectId, collectionIdOrName, itemId, action }) => {
1677
+ try {
1678
+ const id = await client.resolveProjectId(projectId);
1679
+ let targetCid = collectionIdOrName;
1680
+ if (!targetCid.startsWith("col_")) {
1681
+ const list = await client.listCollections(id);
1682
+ const collections = Array.isArray(list) ? list : list.collections || [];
1683
+ const matched = collections.find((c) => c.name?.toLowerCase() === collectionIdOrName.toLowerCase());
1684
+ if (matched && matched.id) targetCid = matched.id;
1685
+ }
1686
+ const result = await client.publishCollectionItem(id, targetCid, itemId, action === "publish");
1687
+ return {
1688
+ content: [
1689
+ {
1690
+ type: "text",
1691
+ text: JSON.stringify(
1692
+ {
1693
+ success: true,
1694
+ itemId,
1695
+ action,
1696
+ message: `Item ${action}ed on live edge CDN.`,
1697
+ result
1698
+ },
1699
+ null,
1700
+ 2
1701
+ )
1702
+ }
1703
+ ]
1704
+ };
1705
+ } catch (err) {
1706
+ return {
1707
+ isError: true,
1708
+ content: [{ type: "text", text: `Failed to ${action} item: ${err.message}` }]
1709
+ };
1710
+ }
1711
+ }
1712
+ );
1713
+ }
1714
+
1715
+ // src/tools/content.ts
1716
+ import { z as z7 } from "zod";
1717
+ function registerContentTools(server, client) {
1718
+ server.tool(
1719
+ "taghost_content_list",
1720
+ "List all live edge content keys and values (data-tag dictionary) served with sub-millisecond latency from Cloudflare KV.",
1721
+ {
1722
+ projectId: z7.string().optional().describe("Project ID. Defaults to active project.")
1723
+ },
1724
+ async ({ projectId }) => {
1725
+ try {
1726
+ const id = await client.resolveProjectId(projectId);
1727
+ const result = await client.getContent(id);
1728
+ const content = result.content || result || {};
1729
+ return {
1730
+ content: [
1731
+ {
1732
+ type: "text",
1733
+ text: JSON.stringify(
1734
+ {
1735
+ success: true,
1736
+ projectId: id,
1737
+ keyCount: Object.keys(content).length,
1738
+ content
1739
+ },
1740
+ null,
1741
+ 2
1742
+ )
1743
+ }
1744
+ ]
1745
+ };
1746
+ } catch (err) {
1747
+ return {
1748
+ isError: true,
1749
+ content: [{ type: "text", text: `Failed to fetch edge content: ${err.message}` }]
1750
+ };
1751
+ }
1752
+ }
1753
+ );
1754
+ server.tool(
1755
+ "taghost_content_patch",
1756
+ "Perform sub-millisecond live content updates on the edge CDN without redeploying. Patches key-value strings bound via data-tag attributes.",
1757
+ {
1758
+ projectId: z7.string().optional().describe("Project ID. Defaults to active project."),
1759
+ patches: z7.record(z7.string()).describe('Key-value pairs to update (e.g. { "hero.title": "Summer Flash Sale \u2014 40% Off", "contact.phone": "+1 555-0199" })')
1760
+ },
1761
+ async ({ projectId, patches }) => {
1762
+ try {
1763
+ const id = await client.resolveProjectId(projectId);
1764
+ const result = await client.patchContent(id, patches);
1765
+ return {
1766
+ content: [
1767
+ {
1768
+ type: "text",
1769
+ text: JSON.stringify(
1770
+ {
1771
+ success: true,
1772
+ message: `Patched ${Object.keys(patches).length} content keys in edge KV in <1ms.`,
1773
+ projectId: id,
1774
+ patchedKeys: Object.keys(patches),
1775
+ result
1776
+ },
1777
+ null,
1778
+ 2
1779
+ )
1780
+ }
1781
+ ]
1782
+ };
1783
+ } catch (err) {
1784
+ return {
1785
+ isError: true,
1786
+ content: [{ type: "text", text: `Failed to patch edge content: ${err.message}` }]
1787
+ };
1788
+ }
1789
+ }
1790
+ );
1791
+ server.tool(
1792
+ "taghost_canvas_patch_html",
1793
+ "Perform surgical DOM modifications on deployed HTML pages (e.g. changing headlines, buttons, or adding script tags) preserving the rest of the file and deployment assets.",
1794
+ {
1795
+ projectId: z7.string().optional().describe("Project ID. Defaults to active project."),
1796
+ path: z7.string().optional().describe('Relative path to HTML file (default: "index.html")'),
1797
+ searchString: z7.string().describe("Exact substring or tag snippet to find in the HTML document"),
1798
+ replaceString: z7.string().describe("New HTML replacement snippet to swap in"),
1799
+ commitMessage: z7.string().optional().describe("Publish commit message")
1800
+ },
1801
+ async ({ projectId, path: filePath, searchString, replaceString, commitMessage }) => {
1802
+ try {
1803
+ const id = await client.resolveProjectId(projectId);
1804
+ const targetPath = filePath || "index.html";
1805
+ const fileTree = await client.getProjectFiles(id);
1806
+ const filesList = fileTree.files || [];
1807
+ const targetFile = filesList.find((f) => f.path === targetPath);
1808
+ if (!targetFile || typeof targetFile.content !== "string") {
1809
+ return {
1810
+ isError: true,
1811
+ content: [{ type: "text", text: `File "${targetPath}" not found or content unreadable in deployment.` }]
1812
+ };
1813
+ }
1814
+ if (!targetFile.content.includes(searchString)) {
1815
+ return {
1816
+ isError: true,
1817
+ content: [
1818
+ {
1819
+ type: "text",
1820
+ text: `Target substring not found in "${targetPath}". Ensure the search snippet matches existing HTML characters exactly.`
1821
+ }
1822
+ ]
1823
+ };
1824
+ }
1825
+ const updatedContent = targetFile.content.replace(searchString, replaceString);
1826
+ const publishRes = await client.publishProjectFiles(id, {
1827
+ files: {
1828
+ [targetPath]: updatedContent
1829
+ },
1830
+ message: commitMessage || `MCP canvas DOM patch on ${targetPath}`
1831
+ });
1832
+ return {
1833
+ content: [
1834
+ {
1835
+ type: "text",
1836
+ text: JSON.stringify(
1837
+ {
1838
+ success: true,
1839
+ message: `Surgically patched "${targetPath}" and created new deployment.`,
1840
+ deploymentId: publishRes.deploymentId,
1841
+ previewUrl: publishRes.previewUrl,
1842
+ liveUrl: publishRes.liveUrl
1843
+ },
1844
+ null,
1845
+ 2
1846
+ )
1847
+ }
1848
+ ]
1849
+ };
1850
+ } catch (err) {
1851
+ return {
1852
+ isError: true,
1853
+ content: [{ type: "text", text: `Failed to patch HTML: ${err.message}` }]
1854
+ };
1855
+ }
1856
+ }
1857
+ );
1858
+ }
1859
+
1860
+ // src/tools/forms_crm.ts
1861
+ import { z as z8 } from "zod";
1862
+ function registerFormsCrmTools(server, client) {
1863
+ server.tool(
1864
+ "taghost_forms_get_submissions",
1865
+ 'Retrieve captured lead submissions from native HTML forms (<form action="/_tag/forms/submit" ...>) on TagHost.',
1866
+ {
1867
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
1868
+ formName: z8.string().optional().describe('Filter by specific form name (e.g. "contact", "newsletter", "quote")'),
1869
+ limit: z8.number().optional().describe("Maximum number of submissions to return (default: 50)")
1870
+ },
1871
+ async ({ projectId, formName, limit }) => {
1872
+ try {
1873
+ const id = await client.resolveProjectId(projectId);
1874
+ const result = await client.getFormSubmissions(id, { formName, limit: limit || 50 });
1875
+ const list = Array.isArray(result) ? result : result.submissions || [];
1876
+ return {
1877
+ content: [
1878
+ {
1879
+ type: "text",
1880
+ text: JSON.stringify(
1881
+ {
1882
+ success: true,
1883
+ count: list.length,
1884
+ submissions: list.map((s) => ({
1885
+ id: s.id,
1886
+ formName: s.formName || "default",
1887
+ data: s.data || s.payload,
1888
+ senderIp: s.ipAddress,
1889
+ submittedAt: s.createdAt
1890
+ }))
1891
+ },
1892
+ null,
1893
+ 2
1894
+ )
1895
+ }
1896
+ ]
1897
+ };
1898
+ } catch (err) {
1899
+ return {
1900
+ isError: true,
1901
+ content: [{ type: "text", text: `Failed to fetch form submissions: ${err.message}` }]
1902
+ };
1903
+ }
1904
+ }
1905
+ );
1906
+ server.tool(
1907
+ "taghost_crm_sequence_create",
1908
+ "Create an automated email marketing and nurture sequence (e.g. welcome drip, cart abandonment, post-purchase onboarding).",
1909
+ {
1910
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
1911
+ name: z8.string().describe('Campaign or sequence name (e.g. "New Customer Welcome Drip")'),
1912
+ triggerEvent: z8.enum(["form.submitted", "order.completed", "manual"]).describe("Triggering event for the sequence"),
1913
+ steps: z8.array(
1914
+ z8.object({
1915
+ stepOrder: z8.number().describe("Step index starting at 1"),
1916
+ delayMinutes: z8.number().describe("Delay after trigger or previous step in minutes (e.g. 0 for immediate, 1440 for 1 day)"),
1917
+ subject: z8.string().describe("Email subject line"),
1918
+ bodyText: z8.string().optional().describe("Plain text body"),
1919
+ bodyHtml: z8.string().optional().describe("Rich HTML body with merge tags like {{name}}")
1920
+ })
1921
+ ).describe("Sequence steps/emails in chronological order")
1922
+ },
1923
+ async ({ projectId, name, triggerEvent, steps }) => {
1924
+ try {
1925
+ const id = await client.resolveProjectId(projectId);
1926
+ const result = await client.createSequence(id, {
1927
+ name,
1928
+ triggerEvent,
1929
+ steps
1930
+ });
1931
+ return {
1932
+ content: [
1933
+ {
1934
+ type: "text",
1935
+ text: JSON.stringify(
1936
+ {
1937
+ success: true,
1938
+ message: `CRM Sequence "${name}" created with ${steps.length} email step(s).`,
1939
+ sequence: result.sequence || result
1940
+ },
1941
+ null,
1942
+ 2
1943
+ )
1944
+ }
1945
+ ]
1946
+ };
1947
+ } catch (err) {
1948
+ return {
1949
+ isError: true,
1950
+ content: [{ type: "text", text: `Failed to create CRM sequence: ${err.message}` }]
1951
+ };
1952
+ }
1953
+ }
1954
+ );
1955
+ server.tool(
1956
+ "taghost_crm_enroll_lead",
1957
+ "Enroll a customer or lead directly into an automated email nurture sequence.",
1958
+ {
1959
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
1960
+ sequenceId: z8.string().describe("The sequence ID to enroll into"),
1961
+ leadEmail: z8.string().describe("Lead email address"),
1962
+ leadName: z8.string().optional().describe("Lead name for personalized merge tags"),
1963
+ metadata: z8.record(z8.any()).optional().describe('Arbitrary metadata payload for merge tags (e.g. { company: "Acme", interest: "wholesale" })')
1964
+ },
1965
+ async ({ projectId, sequenceId, leadEmail, leadName, metadata }) => {
1966
+ try {
1967
+ const id = await client.resolveProjectId(projectId);
1968
+ const result = await client.enrollSequenceLead(id, sequenceId, {
1969
+ leadEmail,
1970
+ leadName,
1971
+ metadata
1972
+ });
1973
+ return {
1974
+ content: [
1975
+ {
1976
+ type: "text",
1977
+ text: JSON.stringify(
1978
+ {
1979
+ success: true,
1980
+ message: `Enrolled ${leadEmail} into sequence ${sequenceId}.`,
1981
+ result
1982
+ },
1983
+ null,
1984
+ 2
1985
+ )
1986
+ }
1987
+ ]
1988
+ };
1989
+ } catch (err) {
1990
+ return {
1991
+ isError: true,
1992
+ content: [{ type: "text", text: `Failed to enroll lead: ${err.message}` }]
1993
+ };
1994
+ }
1995
+ }
1996
+ );
1997
+ server.tool(
1998
+ "taghost_webhook_configure",
1999
+ "Configure HMAC-signed webhooks for real-time external event notifications (orders, leads, deployments).",
2000
+ {
2001
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
2002
+ action: z8.enum(["list", "create", "delete"]).describe("Action to perform"),
2003
+ webhook: z8.object({
2004
+ id: z8.string().optional().describe("Webhook ID (for delete)"),
2005
+ url: z8.string().optional().describe("Target HTTPS destination URL"),
2006
+ events: z8.array(z8.string()).optional().describe('Subscribed event types (e.g. ["order.created", "form.submitted"])'),
2007
+ secret: z8.string().optional().describe("HMAC SHA-256 signing secret")
2008
+ }).optional().describe("Webhook parameters")
2009
+ },
2010
+ async ({ projectId, action, webhook }) => {
2011
+ try {
2012
+ const id = await client.resolveProjectId(projectId);
2013
+ if (action === "list") {
2014
+ const list = await client.listWebhooks(id);
2015
+ return {
2016
+ content: [{ type: "text", text: JSON.stringify({ success: true, webhooks: list }, null, 2) }]
2017
+ };
2018
+ }
2019
+ if (action === "create") {
2020
+ if (!webhook?.url || !webhook?.events || webhook.events.length === 0) {
2021
+ return {
2022
+ isError: true,
2023
+ content: [{ type: "text", text: "url and events are required to create a webhook." }]
2024
+ };
2025
+ }
2026
+ const res = await client.createWebhook(id, {
2027
+ url: webhook.url,
2028
+ events: webhook.events,
2029
+ secret: webhook.secret
2030
+ });
2031
+ return {
2032
+ content: [
2033
+ {
2034
+ type: "text",
2035
+ text: JSON.stringify({ success: true, message: "Webhook created.", webhook: res }, null, 2)
2036
+ }
2037
+ ]
2038
+ };
2039
+ }
2040
+ if (action === "delete") {
2041
+ if (!webhook?.id) {
2042
+ return { isError: true, content: [{ type: "text", text: "Webhook ID is required for delete." }] };
2043
+ }
2044
+ await client.deleteWebhook(id, webhook.id);
2045
+ return {
2046
+ content: [
2047
+ {
2048
+ type: "text",
2049
+ text: JSON.stringify({ success: true, message: `Webhook ${webhook.id} deleted.` }, null, 2)
2050
+ }
2051
+ ]
2052
+ };
2053
+ }
2054
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
2055
+ } catch (err) {
2056
+ return {
2057
+ isError: true,
2058
+ content: [{ type: "text", text: `Failed to configure webhook: ${err.message}` }]
2059
+ };
2060
+ }
2061
+ }
2062
+ );
2063
+ }
2064
+
2065
+ // src/tools/sql.ts
2066
+ import { z as z9 } from "zod";
2067
+
2068
+ // src/utils/sql-guard.ts
2069
+ var FORBIDDEN_SQL_KEYWORDS = [
2070
+ "INSERT",
2071
+ "UPDATE",
2072
+ "DELETE",
2073
+ "DROP",
2074
+ "ALTER",
2075
+ "CREATE",
2076
+ "TRUNCATE",
2077
+ "REPLACE",
2078
+ "ATTACH",
2079
+ "DETACH",
2080
+ "REINDEX",
2081
+ "VACUUM",
2082
+ "GRANT",
2083
+ "REVOKE"
2084
+ ];
2085
+ var SENSITIVE_TABLE_PATTERN = /\b(studio_file_preview_sessions|api_tokens|users|user_\w+|sessions|webhooks|webhook_\w+|workspaces|workspace_\w+|domains|domain_\w+|dns_\w+|sqlite_\w*|email_\w*|mail_\w*|mailbox\w*|push_subscriptions|mfa_\w*|\w*mfa\w*|project_env_vars|platform_admins|payments|payment_\w+|receipt\w*|app_passwords|app_sign_in_\w*|git_connections|github_\w+|project_github_\w*|project_sync_\w*|auth_challenges|audit_logs|onboarding_profiles|partner_\w+|meet_\w+)\b/i;
2086
+ function validateReadOnlySql(sqlQuery) {
2087
+ const trimmed = (sqlQuery || "").trim();
2088
+ if (!trimmed) {
2089
+ return { valid: false, error: "SQL query cannot be empty." };
2090
+ }
2091
+ const cleaned = trimmed.replace(/--.*$/gm, " ").replace(/\/\*[\s\S]*?\*\//g, " ").trim();
2092
+ if (!cleaned) {
2093
+ return { valid: false, error: "SQL query cannot be empty after stripping comments." };
2094
+ }
2095
+ const firstWordMatch = cleaned.match(/^([A-Za-z]+)/);
2096
+ if (!firstWordMatch) {
2097
+ return { valid: false, error: "Invalid SQL syntax." };
2098
+ }
2099
+ const firstWord = firstWordMatch[1].toUpperCase();
2100
+ const allowedStarters = ["SELECT", "PRAGMA", "EXPLAIN", "WITH"];
2101
+ if (!allowedStarters.includes(firstWord)) {
2102
+ return {
2103
+ valid: false,
2104
+ error: `Forbidden SQL statement '${firstWord}'. The TagHost SQL Explorer only allows read-only statements (${allowedStarters.join(", ")}).`
2105
+ };
2106
+ }
2107
+ for (const keyword of FORBIDDEN_SQL_KEYWORDS) {
2108
+ const keywordRegex = new RegExp(`\\b${keyword}\\b`, "i");
2109
+ if (keywordRegex.test(cleaned)) {
2110
+ return {
2111
+ valid: false,
2112
+ error: `Query contains forbidden mutating statement keyword '${keyword}'. TagHost Serverless D1 queries are strictly read-only.`
2113
+ };
2114
+ }
2115
+ }
2116
+ const statements = cleaned.split(";").map((s) => s.trim()).filter(Boolean);
2117
+ if (statements.length > 1) {
2118
+ return {
2119
+ valid: false,
2120
+ error: "Multi-statement SQL queries are not permitted. Please submit one query at a time."
2121
+ };
2122
+ }
2123
+ if (SENSITIVE_TABLE_PATTERN.test(cleaned)) {
2124
+ return {
2125
+ valid: false,
2126
+ error: "Query accesses platform-internal or credentials tables. Direct query of platform metadata is forbidden."
2127
+ };
2128
+ }
2129
+ return { valid: true };
2130
+ }
2131
+
2132
+ // src/tools/sql.ts
2133
+ function registerSqlTools(server, client) {
2134
+ server.tool(
2135
+ "taghost_sql_introspect_schema",
2136
+ "Introspect the project Cloudflare Serverless D1 SQL database: tables, column names, data types, primary keys, and approximate row counts.",
2137
+ {
2138
+ projectId: z9.string().optional().describe("Project ID. Defaults to active project.")
2139
+ },
2140
+ async ({ projectId }) => {
2141
+ try {
2142
+ const id = await client.resolveProjectId(projectId);
2143
+ const result = await client.listSqlTables(id);
2144
+ return {
2145
+ content: [
2146
+ {
2147
+ type: "text",
2148
+ text: JSON.stringify(
2149
+ {
2150
+ success: true,
2151
+ projectId: id,
2152
+ database: result.database,
2153
+ tableCount: result.tables?.length || 0,
2154
+ tables: result.tables || []
2155
+ },
2156
+ null,
2157
+ 2
2158
+ )
2159
+ }
2160
+ ]
2161
+ };
2162
+ } catch (err) {
2163
+ return {
2164
+ isError: true,
2165
+ content: [{ type: "text", text: `Failed to introspect SQL schema: ${err.message}` }]
2166
+ };
2167
+ }
2168
+ }
2169
+ );
2170
+ server.tool(
2171
+ "taghost_sql_query",
2172
+ "Execute a read-only SQL query (SELECT, PRAGMA, EXPLAIN, WITH) against the project Cloudflare D1 SQL database. Strictly enforces read-only access (mutations like INSERT/UPDATE/DELETE/DROP are rejected).",
2173
+ {
2174
+ projectId: z9.string().optional().describe("Project ID. Defaults to active project."),
2175
+ query: z9.string().describe('Read-only SQL statement (e.g. "SELECT * FROM orders WHERE status = ? LIMIT 10")'),
2176
+ params: z9.array(z9.any()).optional().describe("Positional SQL query parameters")
2177
+ },
2178
+ async ({ projectId, query, params }) => {
2179
+ try {
2180
+ const guardCheck = validateReadOnlySql(query);
2181
+ if (!guardCheck.valid) {
2182
+ return {
2183
+ isError: true,
2184
+ content: [{ type: "text", text: `SQL Security Guard rejected query: ${guardCheck.error}` }]
2185
+ };
2186
+ }
2187
+ const id = await client.resolveProjectId(projectId);
2188
+ const result = await client.executeSqlQuery(id, query, params || []);
2189
+ return {
2190
+ content: [
2191
+ {
2192
+ type: "text",
2193
+ text: JSON.stringify(
2194
+ {
2195
+ success: true,
2196
+ rowCount: result.rows?.length ?? (Array.isArray(result.results) ? result.results.length : 0),
2197
+ columns: result.columns,
2198
+ rows: result.rows || result.results || [],
2199
+ durationMs: result.durationMs
2200
+ },
2201
+ null,
2202
+ 2
2203
+ )
2204
+ }
2205
+ ]
2206
+ };
2207
+ } catch (err) {
2208
+ return {
2209
+ isError: true,
2210
+ content: [{ type: "text", text: `Failed to execute SQL query: ${err.message}` }]
2211
+ };
2212
+ }
2213
+ }
2214
+ );
2215
+ }
2216
+
2217
+ // src/tools/observability.ts
2218
+ import { z as z10 } from "zod";
2219
+ function registerObservabilityTools(server, client) {
2220
+ server.tool(
2221
+ "taghost_quota_check",
2222
+ "Inspect workspace quota, plan tier, build usage, custom domain allocations, and mailbox seats.",
2223
+ {
2224
+ projectId: z10.string().optional().describe("Project ID. Defaults to active project.")
2225
+ },
2226
+ async ({ projectId }) => {
2227
+ try {
2228
+ const id = await client.resolveProjectId(projectId);
2229
+ const me = await client.getMe();
2230
+ const usage = await client.getWorkspaceUsage().catch(() => null);
2231
+ return {
2232
+ content: [
2233
+ {
2234
+ type: "text",
2235
+ text: JSON.stringify(
2236
+ {
2237
+ success: true,
2238
+ projectId: id,
2239
+ user: {
2240
+ id: me?.user?.id,
2241
+ email: me?.user?.email,
2242
+ role: me?.membership?.role || "owner"
2243
+ },
2244
+ workspace: {
2245
+ id: me?.workspace?.id,
2246
+ name: me?.workspace?.name,
2247
+ plan: me?.workspace?.plan || "hobby"
2248
+ },
2249
+ usage: usage || {
2250
+ note: "Platform quotas active. Refer to Console Settings for real-time edge meters."
2251
+ }
2252
+ },
2253
+ null,
2254
+ 2
2255
+ )
2256
+ }
2257
+ ]
2258
+ };
2259
+ } catch (err) {
2260
+ return {
2261
+ isError: true,
2262
+ content: [{ type: "text", text: `Failed to check quota: ${err.message}` }]
2263
+ };
2264
+ }
2265
+ }
2266
+ );
2267
+ server.tool(
2268
+ "taghost_ast_eject_preview",
2269
+ 'Zero-lock-in export preview: strip all "data-tag" and "data-th-id" attributes from HTML or JSX, returning clean, framework-independent standard code.',
2270
+ {
2271
+ htmlOrCode: z10.string().describe("HTML snippet or JSX code to clean and eject")
2272
+ },
2273
+ async ({ htmlOrCode }) => {
2274
+ try {
2275
+ let count = 0;
2276
+ const cleaned = htmlOrCode.replace(/\s+(data-tag|data-th-id)(="[^"]*"|='[^']*'|=\{[^}]*\})?/g, () => {
2277
+ count++;
2278
+ return "";
2279
+ });
2280
+ return {
2281
+ content: [
2282
+ {
2283
+ type: "text",
2284
+ text: JSON.stringify(
2285
+ {
2286
+ success: true,
2287
+ strippedCount: count,
2288
+ message: `Removed ${count} platform attribute(s). Code is 100% clean and portable.`,
2289
+ ejectedCode: cleaned
2290
+ },
2291
+ null,
2292
+ 2
2293
+ )
2294
+ }
2295
+ ]
2296
+ };
2297
+ } catch (err) {
2298
+ return {
2299
+ isError: true,
2300
+ content: [{ type: "text", text: `Failed to preview eject: ${err.message}` }]
2301
+ };
2302
+ }
2303
+ }
2304
+ );
2305
+ }
2306
+
2307
+ // src/resources/index.ts
2308
+ function registerResources(server, client) {
2309
+ server.resource(
2310
+ "taghost-project-current",
2311
+ "taghost://project/current",
2312
+ async (uri) => {
2313
+ try {
2314
+ const projectId = await client.resolveProjectId();
2315
+ const project = await client.getProject(projectId);
2316
+ return {
2317
+ contents: [
2318
+ {
2319
+ uri: uri.href,
2320
+ text: JSON.stringify(
2321
+ {
2322
+ id: project.id,
2323
+ name: project.name,
2324
+ slug: project.slug,
2325
+ framework: project.framework,
2326
+ activeDeploymentId: project.activeDeploymentId,
2327
+ customDomain: project.customDomain,
2328
+ previewUrl: project.activeDeploymentId ? `https://${project.activeDeploymentId}.taghost.site` : null,
2329
+ liveUrl: project.customDomain ? `https://${project.customDomain}` : `https://${project.slug}.taghost.site`
2330
+ },
2331
+ null,
2332
+ 2
2333
+ )
2334
+ }
2335
+ ]
2336
+ };
2337
+ } catch (err) {
2338
+ return {
2339
+ contents: [
2340
+ {
2341
+ uri: uri.href,
2342
+ text: JSON.stringify({ error: `Could not resolve current project: ${err.message}` }, null, 2)
2343
+ }
2344
+ ]
2345
+ };
2346
+ }
2347
+ }
2348
+ );
2349
+ server.resource(
2350
+ "taghost-design-tokens",
2351
+ "taghost://design-system/tokens",
2352
+ async (uri) => {
2353
+ return {
2354
+ contents: [
2355
+ {
2356
+ uri: uri.href,
2357
+ text: JSON.stringify(
2358
+ {
2359
+ brand: {
2360
+ primary: "#FF2636",
2361
+ primaryHover: "#E01E2E",
2362
+ darkBg: "#0A0A0C",
2363
+ darkSurface: "#121214",
2364
+ darkBorder: "rgba(255, 255, 255, 0.08)"
2365
+ },
2366
+ typography: {
2367
+ primaryFont: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
2368
+ displayFont: "Syne, Outfit, -apple-system, sans-serif"
2369
+ },
2370
+ rules: [
2371
+ "Use relatable, friendly design suitable for everyday business owners.",
2372
+ "Every layout wireframe must be structurally distinct (e.g. editorial split lookbook, bento stage, daily ritual arch, department deal columns, bakehouse batch cards).",
2373
+ "Never clobber existing websites \u2014 always check whether to publish companion storefronts (/store.html, /products.html) or standalone sites."
2374
+ ]
2375
+ },
2376
+ null,
2377
+ 2
2378
+ )
2379
+ }
2380
+ ]
2381
+ };
2382
+ }
2383
+ );
2384
+ server.resource(
2385
+ "taghost-docs-editing-scope",
2386
+ "taghost://docs/editing-scope",
2387
+ async (uri) => {
2388
+ return {
2389
+ contents: [
2390
+ {
2391
+ uri: uri.href,
2392
+ text: `# TagHost Editing Scope & Best Practices
2393
+
2394
+ 1. Non-Destructive File Publishing:
2395
+ - Use 'taghost_publish_files' to update specific files (such as adding /store.html and /products.html) while carrying forward all other deployment assets untouched.
2396
+ - Preserves customer websites and prevents 404s.
2397
+
2398
+ 2. Companion vs Standalone Stores:
2399
+ - Companion Store: For existing business websites. Generates /store.html and /products.html without overwriting index.html. Injects a navigation link into the existing header/nav.
2400
+ - Standalone Store: For brand-new stores. Generates index.html, store.html, products.html, about.html, and contact.html.
2401
+
2402
+ 3. Live Edge Content (data-tag):
2403
+ - Elements tagged with data-tag="key" can be patched in <1ms via 'taghost_content_patch' without triggering redeploys or cache invalidation delays.
2404
+
2405
+ 4. Serverless D1 SQL:
2406
+ - Strictly read-only queries (SELECT, PRAGMA, EXPLAIN, WITH CTE).
2407
+ - Direct DDL/DML mutations are blocked to protect tenant data isolation.
2408
+ `
2409
+ }
2410
+ ]
2411
+ };
2412
+ }
2413
+ );
2414
+ }
2415
+
2416
+ // src/prompts/index.ts
2417
+ import { z as z11 } from "zod";
2418
+ function registerPrompts(server) {
2419
+ server.prompt(
2420
+ "taghost-setup-ecommerce-store",
2421
+ "Guided autonomous workflow for AI agents to set up an e-commerce storefront, seed product collections, and configure payments.",
2422
+ {
2423
+ storeName: z11.string().describe('Business or store name (e.g. "Lumi\xE8re Atelier")'),
2424
+ storeType: z11.enum(["modern_home", "fashion_boutique", "beauty_wellness", "everyday_retail", "gourmet_artisan"]).describe("Store design style and layout template"),
2425
+ mode: z11.enum(["companion", "standalone"]).describe("Whether to accompany an existing website or build a standalone store"),
2426
+ currency: z11.string().optional().describe("Store currency (e.g. USD, EUR, GBP, NGN)")
2427
+ },
2428
+ async ({ storeName, storeType, mode, currency }) => {
2429
+ return {
2430
+ messages: [
2431
+ {
2432
+ role: "user",
2433
+ content: {
2434
+ type: "text",
2435
+ text: `Please set up an e-commerce store for "${storeName}".
2436
+
2437
+ Specifications:
2438
+ - Template Layout: ${storeType}
2439
+ - Installation Mode: ${mode} (${mode === "companion" ? "Accompany existing website at /store.html and /products.html without touching index.html" : "Full standalone store website replacing index.html"})
2440
+ - Store Currency: ${currency || "USD"}
2441
+
2442
+ Instructions for Autonomous AI Agent:
2443
+ 1. Use 'taghost_project_get' or check the active project binding.
2444
+ 2. If in companion mode, call 'taghost_publish_files' with 'store.html' and 'products.html' so existing website files are carried forward non-destructively.
2445
+ 3. Call 'taghost_collection_create' for 'products' collection if not already created.
2446
+ 4. Add 3 to 5 realistic, relatable sample products using 'taghost_collection_item_upsert' with name, price, description, and images.
2447
+ 5. Configure store currency and gateway using 'taghost_commerce_config'.
2448
+ 6. Confirm the live store URL and summary.`
2449
+ }
2450
+ }
2451
+ ]
2452
+ };
2453
+ }
2454
+ );
2455
+ server.prompt(
2456
+ "taghost-setup-business-mail",
2457
+ "Guided workflow to search/purchase a custom domain, configure DNS records, and provision professional business mailboxes (TagMail).",
2458
+ {
2459
+ domainName: z11.string().describe('The domain name to check, register, or attach (e.g. "acmebrands.com")'),
2460
+ mailboxUser: z11.string().describe('The primary mailbox username (e.g. "hello", "support", "orders")')
2461
+ },
2462
+ async ({ domainName, mailboxUser }) => {
2463
+ return {
2464
+ messages: [
2465
+ {
2466
+ role: "user",
2467
+ content: {
2468
+ type: "text",
2469
+ text: `Please configure custom business email for domain "${domainName}" with mailbox "${mailboxUser}@${domainName}".
2470
+
2471
+ Instructions for Autonomous AI Agent:
2472
+ 1. Call 'taghost_domain_check' to check domain registration status or price.
2473
+ 2. If the user owns the domain, call 'taghost_domain_attach'. If registering new, call 'taghost_domain_checkout'.
2474
+ 3. Call 'taghost_mail_domain_verify' to retrieve required MX, SPF, DKIM, and DMARC DNS records.
2475
+ 4. Call 'taghost_mail_create_mailbox' with localPart: "${mailboxUser}" and domain: "${domainName}".
2476
+ 5. Return instructions and mailbox status to the user.`
2477
+ }
2478
+ }
2479
+ ]
2480
+ };
2481
+ }
2482
+ );
2483
+ server.prompt(
2484
+ "taghost-scaffold-and-ship",
2485
+ "Guided workflow to create a new project, write high-converting HTML/CSS, and deploy it to the TagHost edge CDN.",
2486
+ {
2487
+ projectName: z11.string().describe("Name of the project to create"),
2488
+ businessType: z11.string().describe('Industry or business type (e.g. "Artisan Bakery", "Dental Clinic", "SaaS Platform")')
2489
+ },
2490
+ async ({ projectName, businessType }) => {
2491
+ return {
2492
+ messages: [
2493
+ {
2494
+ role: "user",
2495
+ content: {
2496
+ type: "text",
2497
+ text: `Please create and deploy a modern website for "${projectName}" (${businessType}).
2498
+
2499
+ Instructions for Autonomous AI Agent:
2500
+ 1. Call 'taghost_project_create' with name: "${projectName}".
2501
+ 2. Generate clean, semantic HTML5/Tailwind/CSS with native lead capture form (<form action="/_tag/forms/submit" method="POST">) and data-tag attributes on key headlines.
2502
+ 3. Call 'taghost_publish_files' to deploy the initial files directly to the edge CDN.
2503
+ 4. Output the preview URL and live edge status.`
2504
+ }
2505
+ }
2506
+ ]
2507
+ };
2508
+ }
2509
+ );
2510
+ }
2511
+
2512
+ // src/server.ts
2513
+ dotenv.config();
2514
+ function createTagHostMcpServer(options = {}) {
2515
+ const server = new McpServer({
2516
+ name: options.name || "taghost-mcp",
2517
+ version: options.version || "1.0.0"
2518
+ });
2519
+ const client = new TagHostClient(options);
2520
+ registerProjectTools(server, client);
2521
+ registerDeploymentTools(server, client);
2522
+ registerMailTools(server, client);
2523
+ registerDomainTools(server, client);
2524
+ registerCommerceTools(server, client);
2525
+ registerCollectionTools(server, client);
2526
+ registerContentTools(server, client);
2527
+ registerFormsCrmTools(server, client);
2528
+ registerSqlTools(server, client);
2529
+ registerObservabilityTools(server, client);
2530
+ registerResources(server, client);
2531
+ registerPrompts(server);
2532
+ return { server, client };
2533
+ }
2534
+ async function startServer(options = {}) {
2535
+ const { server } = createTagHostMcpServer(options);
2536
+ const transport = new StdioServerTransport();
2537
+ await server.connect(transport);
2538
+ return server;
2539
+ }
2540
+ if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("taghost-mcp.js")) {
2541
+ startServer().catch((err) => {
2542
+ console.error("Fatal error starting TagHost MCP server:", err);
2543
+ process.exit(1);
2544
+ });
2545
+ }
2546
+
2547
+ export {
2548
+ getApiUrl,
2549
+ resolveAuthToken,
2550
+ findProjectBinding,
2551
+ TagHostClient,
2552
+ bundleDirectory,
2553
+ bundleVirtualFiles,
2554
+ validateReadOnlySql,
2555
+ createTagHostMcpServer,
2556
+ startServer
2557
+ };