@taghost/mcp 1.0.0 → 1.0.1

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,3607 @@
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
+ var PLACEHOLDER_TOKEN_PATTERN = /^<?(your[_-].*token|replace[_-]?me|changeme|placeholder)>?$/i;
18
+ function sanitizeAuthToken(value) {
19
+ if (typeof value !== "string") return null;
20
+ const trimmed = value.trim();
21
+ if (!trimmed || PLACEHOLDER_TOKEN_PATTERN.test(trimmed)) {
22
+ return null;
23
+ }
24
+ return trimmed;
25
+ }
26
+ function resolveAuthToken() {
27
+ const apiToken = sanitizeAuthToken(process.env.TAGHOST_API_TOKEN);
28
+ if (apiToken) {
29
+ return apiToken;
30
+ }
31
+ const token = sanitizeAuthToken(process.env.TAGHOST_TOKEN);
32
+ if (token) {
33
+ return token;
34
+ }
35
+ const credsPath = credentialsPath();
36
+ if (fs.existsSync(credsPath)) {
37
+ try {
38
+ const data = JSON.parse(fs.readFileSync(credsPath, "utf8"));
39
+ const stored = sanitizeAuthToken(data?.token);
40
+ if (stored) {
41
+ return stored;
42
+ }
43
+ } catch {
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+
49
+ // src/client/project-context.ts
50
+ import fs2 from "fs";
51
+ import path2 from "path";
52
+ function findProjectBinding(startDir = process.cwd()) {
53
+ if (process.env.TAGHOST_PROJECT_ID && process.env.TAGHOST_PROJECT_ID.trim()) {
54
+ return { projectId: process.env.TAGHOST_PROJECT_ID.trim() };
55
+ }
56
+ let curr = path2.resolve(startDir);
57
+ while (true) {
58
+ const bindingFile = path2.join(curr, ".taghost", "project.json");
59
+ if (fs2.existsSync(bindingFile)) {
60
+ try {
61
+ const data = JSON.parse(fs2.readFileSync(bindingFile, "utf8"));
62
+ if (data && typeof data.projectId === "string" && data.projectId.trim()) {
63
+ return {
64
+ projectId: data.projectId.trim(),
65
+ slug: data.slug || data.name
66
+ };
67
+ }
68
+ } catch {
69
+ }
70
+ }
71
+ const parent = path2.dirname(curr);
72
+ if (parent === curr) break;
73
+ curr = parent;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ // src/client/taghost-client.ts
79
+ var TagHostClient = class {
80
+ apiUrl;
81
+ explicitToken;
82
+ constructor(options = {}) {
83
+ this.apiUrl = (options.apiUrl || getApiUrl()).replace(/\/+$/, "");
84
+ this.explicitToken = sanitizeAuthToken(options.token);
85
+ }
86
+ getToken() {
87
+ return this.explicitToken || resolveAuthToken();
88
+ }
89
+ async request(endpoint, options = {}) {
90
+ const url = endpoint.startsWith("http") ? endpoint : `${this.apiUrl}${endpoint.startsWith("/") ? "" : "/"}${endpoint}`;
91
+ const headers = new Headers(options.headers || {});
92
+ if (!headers.has("Authorization")) {
93
+ const token = this.getToken();
94
+ if (!token) {
95
+ const error = new Error(
96
+ 'Not authenticated with TagHost. Run "tag login" (saved to ~/.taghost/credentials.json) or set TAGHOST_API_TOKEN.'
97
+ );
98
+ error.status = 401;
99
+ throw error;
100
+ }
101
+ headers.set("Authorization", `Bearer ${token}`);
102
+ }
103
+ const response = await fetch(url, {
104
+ ...options,
105
+ headers
106
+ });
107
+ const contentType = response.headers.get("content-type") || "";
108
+ let body = null;
109
+ if (contentType.includes("application/json")) {
110
+ try {
111
+ body = await response.json();
112
+ } catch {
113
+ body = null;
114
+ }
115
+ } else {
116
+ body = await response.text();
117
+ }
118
+ if (!response.ok) {
119
+ const errorMessage = body && typeof body === "object" && (body.error || body.message) ? body.error || body.message : `HTTP ${response.status}: ${typeof body === "string" ? body : response.statusText}`;
120
+ const error = new Error(errorMessage);
121
+ error.status = response.status;
122
+ error.data = body;
123
+ throw error;
124
+ }
125
+ return body;
126
+ }
127
+ async resolveProjectId(explicitId) {
128
+ if (explicitId && explicitId.trim()) {
129
+ return explicitId.trim();
130
+ }
131
+ const local = findProjectBinding();
132
+ if (local && local.projectId) {
133
+ return local.projectId;
134
+ }
135
+ const projects = await this.listProjects();
136
+ const list = Array.isArray(projects) ? projects : projects?.projects || [];
137
+ if (list.length > 0 && list[0].id) {
138
+ return list[0].id;
139
+ }
140
+ throw new Error(
141
+ 'No project ID provided or found. Specify projectId or link a project with "tag login" / .taghost/project.json.'
142
+ );
143
+ }
144
+ // ── Authentication & Workspaces ─────────────────────────────────────────────
145
+ async getMe() {
146
+ return this.request("/auth/me");
147
+ }
148
+ // ── Projects ───────────────────────────────────────────────────────────────
149
+ async listProjects() {
150
+ return this.request("/projects");
151
+ }
152
+ async getProject(projectId) {
153
+ return this.request(`/projects/${projectId}`);
154
+ }
155
+ async createProject(data) {
156
+ return this.request("/projects", {
157
+ method: "POST",
158
+ headers: { "Content-Type": "application/json" },
159
+ body: JSON.stringify(data)
160
+ });
161
+ }
162
+ async getProjectEnv(projectId) {
163
+ return this.request(`/projects/${projectId}/env`);
164
+ }
165
+ async setProjectEnv(projectId, key, value, target = "all") {
166
+ return this.request(`/projects/${projectId}/env`, {
167
+ method: "POST",
168
+ headers: { "Content-Type": "application/json" },
169
+ body: JSON.stringify({ key, value, target })
170
+ });
171
+ }
172
+ async deleteProjectEnv(projectId, key) {
173
+ return this.request(`/projects/${projectId}/env/${encodeURIComponent(key)}`, {
174
+ method: "DELETE"
175
+ });
176
+ }
177
+ // ── Deployments & Files ───────────────────────────────────────────────────
178
+ async deployBundle(projectId, zipBytes, options = {}) {
179
+ const params = new URLSearchParams();
180
+ if (options.branch) params.set("branch", options.branch);
181
+ if (options.preview) params.set("preview", "true");
182
+ if (options.commitMessage) params.set("commitMessage", options.commitMessage);
183
+ const query = params.toString() ? `?${params.toString()}` : "";
184
+ return this.request(`/projects/${projectId}/deployments/bundle${query}`, {
185
+ method: "POST",
186
+ headers: {
187
+ "Content-Type": "application/zip"
188
+ },
189
+ body: zipBytes
190
+ });
191
+ }
192
+ async getProjectFiles(projectId) {
193
+ return this.request(`/projects/${projectId}/files`);
194
+ }
195
+ async publishProjectFiles(projectId, data) {
196
+ return this.request(`/projects/${projectId}/files`, {
197
+ method: "POST",
198
+ headers: { "Content-Type": "application/json" },
199
+ body: JSON.stringify(data)
200
+ });
201
+ }
202
+ async listDeployments(projectId) {
203
+ return this.request(`/projects/${projectId}/deployments`);
204
+ }
205
+ async rollbackDeployment(projectId, deploymentId) {
206
+ return this.request(`/projects/${projectId}/deployments/${deploymentId}/rollback`, {
207
+ method: "POST"
208
+ });
209
+ }
210
+ async setDeploymentExpiry(projectId, deploymentId, ttlSeconds, neverExpire) {
211
+ return this.request(`/projects/${projectId}/deployments/${deploymentId}/expiry`, {
212
+ method: "PATCH",
213
+ headers: { "Content-Type": "application/json" },
214
+ body: JSON.stringify({ ttlSeconds, neverExpire })
215
+ });
216
+ }
217
+ // ── Domains & DNS ──────────────────────────────────────────────────────────
218
+ async checkDomainAvailability(domain) {
219
+ return this.request(`/domains/check?domain=${encodeURIComponent(domain)}`);
220
+ }
221
+ async searchDomains(query) {
222
+ return this.request(`/domains/search?query=${encodeURIComponent(query)}`);
223
+ }
224
+ async checkoutDomain(projectId, data) {
225
+ return this.request(`/projects/${projectId}/domains/checkout`, {
226
+ method: "POST",
227
+ headers: { "Content-Type": "application/json" },
228
+ body: JSON.stringify(data)
229
+ });
230
+ }
231
+ async attachDomain(projectId, domain) {
232
+ return this.request(`/projects/${projectId}/domains`, {
233
+ method: "POST",
234
+ headers: { "Content-Type": "application/json" },
235
+ body: JSON.stringify({ domain })
236
+ });
237
+ }
238
+ async verifyDomain(projectId, domain) {
239
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/verify`, {
240
+ method: "POST"
241
+ });
242
+ }
243
+ async listDnsRecords(projectId, domain) {
244
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns`);
245
+ }
246
+ async createDnsRecord(projectId, domain, record) {
247
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns`, {
248
+ method: "POST",
249
+ headers: { "Content-Type": "application/json" },
250
+ body: JSON.stringify(record)
251
+ });
252
+ }
253
+ async updateDnsRecord(projectId, domain, recordId, record) {
254
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns/${recordId}`, {
255
+ method: "PATCH",
256
+ headers: { "Content-Type": "application/json" },
257
+ body: JSON.stringify(record)
258
+ });
259
+ }
260
+ async deleteDnsRecord(projectId, domain, recordId) {
261
+ return this.request(`/projects/${projectId}/domains/${encodeURIComponent(domain)}/dns/${recordId}`, {
262
+ method: "DELETE"
263
+ });
264
+ }
265
+ // ── TagMail (Corporate Inbox & Sending) ───────────────────────────────────
266
+ async listMailThreads(projectId, options = {}) {
267
+ const params = new URLSearchParams();
268
+ if (options.mailboxId) params.set("mailboxId", options.mailboxId);
269
+ if (options.query) params.set("q", options.query);
270
+ if (options.limit) params.set("limit", String(options.limit));
271
+ const query = params.toString() ? `?${params.toString()}` : "";
272
+ return this.request(`/projects/${projectId}/email/threads${query}`);
273
+ }
274
+ async getMailThread(projectId, threadId) {
275
+ return this.request(`/projects/${projectId}/email/threads/${threadId}`);
276
+ }
277
+ async sendMail(projectId, data) {
278
+ return this.request(`/projects/${projectId}/email/send`, {
279
+ method: "POST",
280
+ headers: { "Content-Type": "application/json" },
281
+ body: JSON.stringify(data)
282
+ });
283
+ }
284
+ async listMailboxes(projectId) {
285
+ return this.request(`/projects/${projectId}/email/mailboxes`);
286
+ }
287
+ async createMailbox(projectId, data) {
288
+ return this.request(`/projects/${projectId}/email/mailboxes`, {
289
+ method: "POST",
290
+ headers: { "Content-Type": "application/json" },
291
+ body: JSON.stringify(data)
292
+ });
293
+ }
294
+ async getMailDomainVerification(projectId, domain) {
295
+ return this.request(`/projects/${projectId}/email/domains/${encodeURIComponent(domain)}/verification`);
296
+ }
297
+ // ── Commerce, Themes & Gateways ───────────────────────────────────────────
298
+ async getCommerceTheme(projectId) {
299
+ return this.request(`/projects/${projectId}/commerce/theme`);
300
+ }
301
+ async updateCommerceTheme(projectId, theme) {
302
+ return this.request(`/projects/${projectId}/commerce/theme`, {
303
+ method: "PUT",
304
+ headers: { "Content-Type": "application/json" },
305
+ body: JSON.stringify(theme)
306
+ });
307
+ }
308
+ async getCommerceGateways(projectId) {
309
+ return this.request(`/projects/${projectId}/commerce/gateways`);
310
+ }
311
+ async updateCommerceGateway(projectId, provider, config) {
312
+ return this.request(`/projects/${projectId}/commerce/gateways/${provider}`, {
313
+ method: "PUT",
314
+ headers: { "Content-Type": "application/json" },
315
+ body: JSON.stringify(config)
316
+ });
317
+ }
318
+ async migrateWooCommerce(projectId, payload) {
319
+ return this.request(`/projects/${projectId}/commerce/migrate/woocommerce`, {
320
+ method: "POST",
321
+ headers: { "Content-Type": "application/json" },
322
+ body: JSON.stringify(payload)
323
+ });
324
+ }
325
+ async cloneWordPressSite(projectId, payload) {
326
+ return this.request(`/projects/${projectId}/migrations/wordpress/clone`, {
327
+ method: "POST",
328
+ headers: { "Content-Type": "application/json" },
329
+ body: JSON.stringify(payload)
330
+ });
331
+ }
332
+ async listOrders(projectId, options = {}) {
333
+ const params = new URLSearchParams();
334
+ if (options.status) params.set("status", options.status);
335
+ if (options.limit) params.set("limit", String(options.limit));
336
+ const query = params.toString() ? `?${params.toString()}` : "";
337
+ return this.request(`/projects/${projectId}/orders${query}`);
338
+ }
339
+ async getOrder(projectId, orderId) {
340
+ return this.request(`/projects/${projectId}/orders/${orderId}`);
341
+ }
342
+ async updateOrder(projectId, orderId, data) {
343
+ return this.request(`/projects/${projectId}/orders/${orderId}`, {
344
+ method: "PATCH",
345
+ headers: { "Content-Type": "application/json" },
346
+ body: JSON.stringify(data)
347
+ });
348
+ }
349
+ async listCoupons(projectId) {
350
+ return this.request(`/projects/${projectId}/commerce/coupons`);
351
+ }
352
+ async createCoupon(projectId, coupon) {
353
+ return this.request(`/projects/${projectId}/commerce/coupons`, {
354
+ method: "POST",
355
+ headers: { "Content-Type": "application/json" },
356
+ body: JSON.stringify(coupon)
357
+ });
358
+ }
359
+ async deleteCoupon(projectId, couponId) {
360
+ return this.request(`/projects/${projectId}/commerce/coupons/${couponId}`, {
361
+ method: "DELETE"
362
+ });
363
+ }
364
+ // ── CMS & Edge Collections ────────────────────────────────────────────────
365
+ async listCollections(projectId) {
366
+ return this.request(`/projects/${projectId}/collections`);
367
+ }
368
+ async createCollection(projectId, data) {
369
+ return this.request(`/projects/${projectId}/collections`, {
370
+ method: "POST",
371
+ headers: { "Content-Type": "application/json" },
372
+ body: JSON.stringify(data)
373
+ });
374
+ }
375
+ async listCollectionItems(projectId, collectionId) {
376
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items`);
377
+ }
378
+ async upsertCollectionItem(projectId, collectionId, data, itemId) {
379
+ if (itemId) {
380
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items/${itemId}`, {
381
+ method: "PATCH",
382
+ headers: { "Content-Type": "application/json" },
383
+ body: JSON.stringify({ data })
384
+ });
385
+ }
386
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items`, {
387
+ method: "POST",
388
+ headers: { "Content-Type": "application/json" },
389
+ body: JSON.stringify({ data })
390
+ });
391
+ }
392
+ async publishCollectionItem(projectId, collectionId, itemId, publish = true) {
393
+ const action = publish ? "publish" : "unpublish";
394
+ return this.request(`/projects/${projectId}/collections/${collectionId}/items/${itemId}/${action}`, {
395
+ method: "POST"
396
+ });
397
+ }
398
+ // ── Edge Content (data-tag <1ms dictionary) ───────────────────────────────
399
+ async getContent(projectId) {
400
+ return this.request(`/projects/${projectId}/content`);
401
+ }
402
+ async patchContent(projectId, patches) {
403
+ return this.request(`/projects/${projectId}/content`, {
404
+ method: "POST",
405
+ headers: { "Content-Type": "application/json" },
406
+ body: JSON.stringify({ content: patches })
407
+ });
408
+ }
409
+ // ── Native Forms, CRM & Webhooks ──────────────────────────────────────────
410
+ async getFormSubmissions(projectId, options = {}) {
411
+ const params = new URLSearchParams();
412
+ if (options.formName) params.set("formName", options.formName);
413
+ if (options.limit) params.set("limit", String(options.limit));
414
+ const query = params.toString() ? `?${params.toString()}` : "";
415
+ return this.request(`/projects/${projectId}/forms/submissions${query}`);
416
+ }
417
+ async listSequences(projectId) {
418
+ return this.request(`/projects/${projectId}/sequences`);
419
+ }
420
+ async createSequence(projectId, data) {
421
+ return this.request(`/projects/${projectId}/sequences`, {
422
+ method: "POST",
423
+ headers: { "Content-Type": "application/json" },
424
+ body: JSON.stringify(data)
425
+ });
426
+ }
427
+ async enrollSequenceLead(projectId, sequenceId, data) {
428
+ return this.request(`/projects/${projectId}/sequences/${sequenceId}/enroll`, {
429
+ method: "POST",
430
+ headers: { "Content-Type": "application/json" },
431
+ body: JSON.stringify(data)
432
+ });
433
+ }
434
+ async listWebhooks(projectId) {
435
+ return this.request(`/projects/${projectId}/webhooks`);
436
+ }
437
+ async createWebhook(projectId, data) {
438
+ return this.request(`/projects/${projectId}/webhooks`, {
439
+ method: "POST",
440
+ headers: { "Content-Type": "application/json" },
441
+ body: JSON.stringify(data)
442
+ });
443
+ }
444
+ async deleteWebhook(projectId, webhookId) {
445
+ return this.request(`/projects/${projectId}/webhooks/${webhookId}`, {
446
+ method: "DELETE"
447
+ });
448
+ }
449
+ // ── Serverless D1 SQL Explorer ────────────────────────────────────────────
450
+ async listSqlTables(projectId) {
451
+ return this.request(`/projects/${projectId}/sql/tables`);
452
+ }
453
+ async executeSqlQuery(projectId, query, params = []) {
454
+ return this.request(`/projects/${projectId}/sql/query`, {
455
+ method: "POST",
456
+ headers: { "Content-Type": "application/json" },
457
+ body: JSON.stringify({ query, params })
458
+ });
459
+ }
460
+ // ── Observability & Quota ─────────────────────────────────────────────────
461
+ async getWorkspaceUsage() {
462
+ const me = await this.getMe();
463
+ const workspaceId = me?.workspace?.id || me?.user?.workspaceId;
464
+ if (!workspaceId) {
465
+ throw new Error("Unable to resolve workspace ID from session.");
466
+ }
467
+ return this.request(`/workspaces/${workspaceId}/usage`);
468
+ }
469
+ // ── TagWork Tasks, Calendar & Meet ────────────────────────────────────────
470
+ async resolveWorkspaceId(explicitId) {
471
+ if (explicitId && explicitId.trim()) return explicitId.trim();
472
+ if (process.env.TAGHOST_WORKSPACE_ID && process.env.TAGHOST_WORKSPACE_ID.trim()) {
473
+ return process.env.TAGHOST_WORKSPACE_ID.trim();
474
+ }
475
+ const me = await this.getMe();
476
+ const wsId = me?.workspace?.id || me?.user?.workspaceId || me?.membership?.workspaceId;
477
+ if (wsId) return wsId;
478
+ throw new Error("Unable to resolve active workspace ID from session.");
479
+ }
480
+ async listTasks(workspaceId, options = {}) {
481
+ const params = new URLSearchParams();
482
+ if (options.completed !== void 0) params.set("completed", String(options.completed));
483
+ if (options.threadId) params.set("threadId", options.threadId);
484
+ const query = params.toString() ? `?${params.toString()}` : "";
485
+ return this.request(`/workspaces/${workspaceId}/tasks${query}`);
486
+ }
487
+ async createTask(workspaceId, data) {
488
+ return this.request(`/workspaces/${workspaceId}/tasks`, {
489
+ method: "POST",
490
+ headers: { "Content-Type": "application/json" },
491
+ body: JSON.stringify(data)
492
+ });
493
+ }
494
+ async updateTask(workspaceId, taskId, data) {
495
+ return this.request(`/workspaces/${workspaceId}/tasks/${taskId}`, {
496
+ method: "PATCH",
497
+ headers: { "Content-Type": "application/json" },
498
+ body: JSON.stringify(data)
499
+ });
500
+ }
501
+ async deleteTask(workspaceId, taskId) {
502
+ return this.request(`/workspaces/${workspaceId}/tasks/${taskId}`, {
503
+ method: "DELETE"
504
+ });
505
+ }
506
+ async listCalendarEvents(workspaceId, options = {}) {
507
+ const params = new URLSearchParams();
508
+ if (options.start) params.set("start", String(options.start));
509
+ if (options.end) params.set("end", String(options.end));
510
+ if (options.mailboxId) params.set("mailboxId", options.mailboxId);
511
+ const query = params.toString() ? `?${params.toString()}` : "";
512
+ return this.request(`/workspaces/${workspaceId}/calendar/events${query}`);
513
+ }
514
+ async createCalendarEvent(workspaceId, data) {
515
+ return this.request(`/workspaces/${workspaceId}/calendar/events`, {
516
+ method: "POST",
517
+ headers: { "Content-Type": "application/json" },
518
+ body: JSON.stringify(data)
519
+ });
520
+ }
521
+ async updateCalendarEvent(workspaceId, eventId, data) {
522
+ return this.request(`/workspaces/${workspaceId}/calendar/events/${eventId}`, {
523
+ method: "PATCH",
524
+ headers: { "Content-Type": "application/json" },
525
+ body: JSON.stringify(data)
526
+ });
527
+ }
528
+ async deleteCalendarEvent(workspaceId, eventId) {
529
+ return this.request(`/workspaces/${workspaceId}/calendar/events/${eventId}`, {
530
+ method: "DELETE"
531
+ });
532
+ }
533
+ async createMeetRoom(data) {
534
+ return this.request("/meet/rooms", {
535
+ method: "POST",
536
+ headers: { "Content-Type": "application/json" },
537
+ body: JSON.stringify(data)
538
+ });
539
+ }
540
+ async listNotes(workspaceId) {
541
+ return this.request(`/workspaces/${workspaceId}/notes`);
542
+ }
543
+ async createNote(workspaceId, data) {
544
+ return this.request(`/workspaces/${workspaceId}/notes`, {
545
+ method: "POST",
546
+ headers: { "Content-Type": "application/json" },
547
+ body: JSON.stringify(data)
548
+ });
549
+ }
550
+ };
551
+
552
+ // src/tools/projects.ts
553
+ import { z } from "zod";
554
+
555
+ // src/scopes.ts
556
+ var MCP_SCOPES = [
557
+ {
558
+ id: "projects:read",
559
+ label: "Projects & quotas",
560
+ description: "List projects, inspect configuration, check quotas, and preview AST eject output.",
561
+ icon: "layers",
562
+ access: "read",
563
+ defaultSelected: true
564
+ },
565
+ {
566
+ id: "deployments:write",
567
+ label: "Deployments & environment",
568
+ description: "Deploy site bundles, publish partial files, manage env vars, set expiry, and rollback.",
569
+ icon: "deployed_code",
570
+ access: "write",
571
+ defaultSelected: true
572
+ },
573
+ {
574
+ id: "content:write",
575
+ label: "Edge content & collections",
576
+ description: "Edit [data-tag] bindings, patch HTML canvas elements, and publish CMS collection items.",
577
+ icon: "draw",
578
+ access: "write",
579
+ defaultSelected: true
580
+ },
581
+ {
582
+ id: "domains:write",
583
+ label: "Domains & DNS",
584
+ description: "Search/check domain availability, attach custom domains, verify SSL, and manage DNS records.",
585
+ icon: "language",
586
+ access: "write"
587
+ },
588
+ {
589
+ id: "mail:read",
590
+ label: "TagMail (read)",
591
+ description: "List and read TagMail threads and check mail domain DNS verification.",
592
+ icon: "inbox",
593
+ access: "read"
594
+ },
595
+ {
596
+ id: "mail:send",
597
+ label: "TagMail (send & mailboxes)",
598
+ description: "Send outbound transactional email and create workspace mailboxes.",
599
+ icon: "mail",
600
+ access: "write"
601
+ },
602
+ {
603
+ id: "commerce:write",
604
+ label: "Commerce & orders",
605
+ description: "Configure stores, manage coupons, view/fulfill orders, and migrate catalogs.",
606
+ icon: "storefront",
607
+ access: "write"
608
+ },
609
+ {
610
+ id: "forms:read",
611
+ label: "Forms, CRM & webhooks",
612
+ description: "Inspect form submissions, enroll leads in CRM sequences, and configure webhooks.",
613
+ icon: "assignment",
614
+ access: "write"
615
+ },
616
+ {
617
+ id: "sql:read",
618
+ label: "Serverless D1 SQL (read-only)",
619
+ description: "Introspect project database schemas and execute read-only SELECT queries.",
620
+ icon: "database",
621
+ access: "read"
622
+ },
623
+ {
624
+ id: "workspace:collaborate",
625
+ label: "Tasks, calendar, notes & Meet",
626
+ description: "Manage TagWork tasks, calendar events, notes, Meet rooms, and scheduled automations.",
627
+ icon: "event",
628
+ access: "write"
629
+ }
630
+ ];
631
+ var ALL_MCP_SCOPES = MCP_SCOPES.map((s) => s.id);
632
+ var VALID_SCOPE_SET = new Set(ALL_MCP_SCOPES);
633
+ function normalizeMcpScopes(input) {
634
+ if (!input) return [];
635
+ const raw = Array.isArray(input) ? input : input.split(/[\s,]+/);
636
+ const seen = /* @__PURE__ */ new Set();
637
+ for (const item of raw) {
638
+ const trimmed = item.trim();
639
+ if (VALID_SCOPE_SET.has(trimmed)) {
640
+ seen.add(trimmed);
641
+ }
642
+ }
643
+ return Array.from(seen);
644
+ }
645
+ function hasMcpScope(granted, required) {
646
+ if (granted == null) return true;
647
+ if (granted.includes("*")) return true;
648
+ return granted.includes(required);
649
+ }
650
+
651
+ // src/tools/projects.ts
652
+ function registerProjectTools(server, client, scopes) {
653
+ if (hasMcpScope(scopes, "deployments:write")) {
654
+ server.tool(
655
+ "taghost_project_create",
656
+ "Create a new project on TagHost edge platform.",
657
+ {
658
+ name: z.string().describe('Human readable name of the project (e.g. "Acme Storefront")'),
659
+ slug: z.string().optional().describe('URL slug for the project (e.g. "acme-storefront")'),
660
+ framework: z.string().optional().describe('Framework template (e.g. "html", "react", "nextjs", "vue")')
661
+ },
662
+ async ({ name, slug, framework }) => {
663
+ try {
664
+ const result = await client.createProject({ name, slug, framework });
665
+ return {
666
+ content: [
667
+ {
668
+ type: "text",
669
+ text: JSON.stringify(
670
+ {
671
+ success: true,
672
+ message: `Project "${name}" created successfully.`,
673
+ project: result.project || result
674
+ },
675
+ null,
676
+ 2
677
+ )
678
+ }
679
+ ]
680
+ };
681
+ } catch (err) {
682
+ return {
683
+ isError: true,
684
+ content: [{ type: "text", text: `Failed to create project: ${err.message}` }]
685
+ };
686
+ }
687
+ }
688
+ );
689
+ }
690
+ if (hasMcpScope(scopes, "projects:read")) {
691
+ server.tool(
692
+ "taghost_project_list",
693
+ "List all projects accessible within the current TagHost workspace.",
694
+ {
695
+ limit: z.number().optional().describe("Maximum number of projects to return (default: 50)")
696
+ },
697
+ async ({ limit }) => {
698
+ try {
699
+ const result = await client.listProjects();
700
+ const list = Array.isArray(result) ? result : result.projects || [];
701
+ const items = limit ? list.slice(0, limit) : list;
702
+ return {
703
+ content: [
704
+ {
705
+ type: "text",
706
+ text: JSON.stringify({ success: true, count: items.length, projects: items }, null, 2)
707
+ }
708
+ ]
709
+ };
710
+ } catch (err) {
711
+ return {
712
+ isError: true,
713
+ content: [{ type: "text", text: `Failed to list projects: ${err.message}` }]
714
+ };
715
+ }
716
+ }
717
+ );
718
+ server.tool(
719
+ "taghost_project_get",
720
+ "Get detailed information about a specific TagHost project, including active deployment and domains.",
721
+ {
722
+ projectId: z.string().optional().describe('Project ID (e.g. "proj_..."). Defaults to active project.')
723
+ },
724
+ async ({ projectId }) => {
725
+ try {
726
+ const id = await client.resolveProjectId(projectId);
727
+ const result = await client.getProject(id);
728
+ return {
729
+ content: [
730
+ {
731
+ type: "text",
732
+ text: JSON.stringify({ success: true, project: result.project || result }, null, 2)
733
+ }
734
+ ]
735
+ };
736
+ } catch (err) {
737
+ return {
738
+ isError: true,
739
+ content: [{ type: "text", text: `Failed to get project: ${err.message}` }]
740
+ };
741
+ }
742
+ }
743
+ );
744
+ }
745
+ if (hasMcpScope(scopes, "deployments:write")) {
746
+ server.tool(
747
+ "taghost_env_manage",
748
+ "Manage environment variables for a TagHost project.",
749
+ {
750
+ projectId: z.string().optional().describe("Project ID. Defaults to active project."),
751
+ action: z.enum(["list", "set", "delete"]).describe("Action to perform"),
752
+ key: z.string().optional().describe("Environment variable key"),
753
+ value: z.string().optional().describe("Environment variable value (for set action)"),
754
+ target: z.enum(["production", "preview", "all"]).optional().describe("Deployment target")
755
+ },
756
+ async ({ projectId, action, key, value, target }) => {
757
+ try {
758
+ const id = await client.resolveProjectId(projectId);
759
+ if (action === "list") {
760
+ const res = await client.getProjectEnv(id);
761
+ return {
762
+ content: [{ type: "text", text: JSON.stringify({ success: true, envVars: res }, null, 2) }]
763
+ };
764
+ }
765
+ if (action === "set") {
766
+ if (!key || value === void 0) {
767
+ return {
768
+ isError: true,
769
+ content: [{ type: "text", text: 'Both key and value are required for "set" action.' }]
770
+ };
771
+ }
772
+ const res = await client.setProjectEnv(id, key, value, target || "all");
773
+ return {
774
+ content: [
775
+ {
776
+ type: "text",
777
+ text: JSON.stringify({ success: true, message: `Environment variable "${key}" set.`, result: res }, null, 2)
778
+ }
779
+ ]
780
+ };
781
+ }
782
+ if (action === "delete") {
783
+ if (!key) {
784
+ return { isError: true, content: [{ type: "text", text: 'Key is required for "delete" action.' }] };
785
+ }
786
+ await client.deleteProjectEnv(id, key);
787
+ return {
788
+ content: [
789
+ {
790
+ type: "text",
791
+ text: JSON.stringify({ success: true, message: `Environment variable "${key}" deleted.` }, null, 2)
792
+ }
793
+ ]
794
+ };
795
+ }
796
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
797
+ } catch (err) {
798
+ return {
799
+ isError: true,
800
+ content: [{ type: "text", text: `Failed to manage env vars: ${err.message}` }]
801
+ };
802
+ }
803
+ }
804
+ );
805
+ }
806
+ }
807
+
808
+ // src/tools/deployments.ts
809
+ import path4 from "path";
810
+ import { z as z2 } from "zod";
811
+
812
+ // src/utils/bundle.ts
813
+ import fs3 from "fs";
814
+ import path3 from "path";
815
+ import { zipSync } from "fflate";
816
+ var IGNORED_ENTRIES = /* @__PURE__ */ new Set([
817
+ ".DS_Store",
818
+ "Thumbs.db",
819
+ "desktop.ini",
820
+ "__MACOSX",
821
+ "node_modules",
822
+ ".git",
823
+ ".turbo",
824
+ ".next",
825
+ ".taghost"
826
+ ]);
827
+ function bundleDirectory(dirPath) {
828
+ const resolved = path3.resolve(dirPath);
829
+ if (!fs3.existsSync(resolved) || !fs3.statSync(resolved).isDirectory()) {
830
+ throw new Error(`Directory does not exist or is not a directory: ${resolved}`);
831
+ }
832
+ const filesRecord = {};
833
+ const fileList = [];
834
+ let totalBytes = 0;
835
+ function walk(currentDir, relativePrefix = "") {
836
+ const items = fs3.readdirSync(currentDir);
837
+ for (const item of items) {
838
+ if (IGNORED_ENTRIES.has(item)) continue;
839
+ const fullPath = path3.join(currentDir, item);
840
+ const relativePath = relativePrefix ? `${relativePrefix}/${item}` : item;
841
+ const stat = fs3.statSync(fullPath);
842
+ if (stat.isDirectory()) {
843
+ walk(fullPath, relativePath);
844
+ } else if (stat.isFile()) {
845
+ const content = fs3.readFileSync(fullPath);
846
+ filesRecord[relativePath] = content;
847
+ fileList.push(relativePath);
848
+ totalBytes += content.byteLength;
849
+ }
850
+ }
851
+ }
852
+ walk(resolved);
853
+ if (fileList.length === 0) {
854
+ throw new Error(`Directory is empty: ${resolved}`);
855
+ }
856
+ const zipBuffer = zipSync(filesRecord, { level: 6 });
857
+ return {
858
+ zipBuffer,
859
+ fileCount: fileList.length,
860
+ totalBytes,
861
+ fileList
862
+ };
863
+ }
864
+ function bundleVirtualFiles(files) {
865
+ const filesRecord = {};
866
+ const fileList = [];
867
+ let totalBytes = 0;
868
+ for (const [filePath, content] of Object.entries(files)) {
869
+ const normalized = filePath.replace(/^[/\\]+/, "");
870
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
871
+ filesRecord[normalized] = bytes;
872
+ fileList.push(normalized);
873
+ totalBytes += bytes.byteLength;
874
+ }
875
+ if (fileList.length === 0) {
876
+ throw new Error("No files provided in bundle");
877
+ }
878
+ const zipBuffer = zipSync(filesRecord, { level: 6 });
879
+ return {
880
+ zipBuffer,
881
+ fileCount: fileList.length,
882
+ totalBytes,
883
+ fileList
884
+ };
885
+ }
886
+
887
+ // src/tools/deployments.ts
888
+ function registerDeploymentTools(server, client) {
889
+ server.tool(
890
+ "taghost_deploy_bundle",
891
+ "Deploy a local directory of static web assets to TagHost edge CDN via direct ZIP archive ingestion.",
892
+ {
893
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
894
+ directoryPath: z2.string().describe('Absolute or relative path to the build directory (e.g. "./dist", "./out", "./public")'),
895
+ branch: z2.string().optional().describe('Git branch reference (default: "main")'),
896
+ preview: z2.boolean().optional().describe("Whether to deploy as an ephemeral preview instead of production (default: false)"),
897
+ commitMessage: z2.string().optional().describe("Deployment description or commit message")
898
+ },
899
+ async ({ projectId, directoryPath, branch, preview, commitMessage }) => {
900
+ try {
901
+ const id = await client.resolveProjectId(projectId);
902
+ const resolvedDir = path4.resolve(process.cwd(), directoryPath);
903
+ const bundle = bundleDirectory(resolvedDir);
904
+ const result = await client.deployBundle(id, bundle.zipBuffer, {
905
+ branch: branch || "main",
906
+ preview: preview || false,
907
+ commitMessage: commitMessage || `MCP deploy: ${bundle.fileCount} assets (${Math.round(bundle.totalBytes / 1024)} KB)`
908
+ });
909
+ return {
910
+ content: [
911
+ {
912
+ type: "text",
913
+ text: JSON.stringify(
914
+ {
915
+ success: true,
916
+ deploymentId: result.deploymentId || result.id,
917
+ previewUrl: result.previewUrl,
918
+ liveUrl: result.liveUrl,
919
+ fileCount: bundle.fileCount,
920
+ totalBytes: bundle.totalBytes,
921
+ message: "Bundle uploaded and deployed to edge successfully."
922
+ },
923
+ null,
924
+ 2
925
+ )
926
+ }
927
+ ]
928
+ };
929
+ } catch (err) {
930
+ return {
931
+ isError: true,
932
+ content: [{ type: "text", text: `Failed to deploy bundle: ${err.message}` }]
933
+ };
934
+ }
935
+ }
936
+ );
937
+ server.tool(
938
+ "taghost_publish_files",
939
+ "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.",
940
+ {
941
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
942
+ files: z2.record(z2.string()).describe('Map of file paths to their string content (e.g. { "store.html": "...", "products.html": "..." })'),
943
+ deletedPaths: z2.array(z2.string()).optional().describe("Optional list of paths to delete"),
944
+ message: z2.string().optional().describe("Commit or publish description")
945
+ },
946
+ async ({ projectId, files, deletedPaths, message }) => {
947
+ try {
948
+ const id = await client.resolveProjectId(projectId);
949
+ const result = await client.publishProjectFiles(id, {
950
+ files,
951
+ deletedPaths,
952
+ message: message || "MCP non-destructive file publish"
953
+ });
954
+ return {
955
+ content: [
956
+ {
957
+ type: "text",
958
+ text: JSON.stringify(
959
+ {
960
+ success: true,
961
+ deploymentId: result.deploymentId,
962
+ previewUrl: result.previewUrl,
963
+ liveUrl: result.liveUrl,
964
+ updatedFiles: Object.keys(files),
965
+ deletedFiles: deletedPaths || [],
966
+ message: "Files published non-destructively; existing website assets preserved."
967
+ },
968
+ null,
969
+ 2
970
+ )
971
+ }
972
+ ]
973
+ };
974
+ } catch (err) {
975
+ return {
976
+ isError: true,
977
+ content: [{ type: "text", text: `Failed to publish files: ${err.message}` }]
978
+ };
979
+ }
980
+ }
981
+ );
982
+ server.tool(
983
+ "taghost_deployment_status",
984
+ "Check deployment status, preview and live edge URLs for a project.",
985
+ {
986
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project.")
987
+ },
988
+ async ({ projectId }) => {
989
+ try {
990
+ const id = await client.resolveProjectId(projectId);
991
+ const project = await client.getProject(id);
992
+ const deployments = await client.listDeployments(id);
993
+ return {
994
+ content: [
995
+ {
996
+ type: "text",
997
+ text: JSON.stringify(
998
+ {
999
+ success: true,
1000
+ projectId: id,
1001
+ name: project.name,
1002
+ activeDeploymentId: project.activeDeploymentId,
1003
+ slug: project.slug,
1004
+ customDomain: project.customDomain,
1005
+ liveUrl: project.customDomain ? `https://${project.customDomain}` : `https://${project.slug}.taghost.site`,
1006
+ recentDeployments: Array.isArray(deployments) ? deployments.slice(0, 5) : deployments?.deployments?.slice(0, 5) || []
1007
+ },
1008
+ null,
1009
+ 2
1010
+ )
1011
+ }
1012
+ ]
1013
+ };
1014
+ } catch (err) {
1015
+ return {
1016
+ isError: true,
1017
+ content: [{ type: "text", text: `Failed to fetch deployment status: ${err.message}` }]
1018
+ };
1019
+ }
1020
+ }
1021
+ );
1022
+ server.tool(
1023
+ "taghost_deployment_rollback",
1024
+ "Perform an instant atomic rollback to a previous deployment.",
1025
+ {
1026
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
1027
+ deploymentId: z2.string().describe('The deployment ID to roll back to (e.g. "dep_...")')
1028
+ },
1029
+ async ({ projectId, deploymentId }) => {
1030
+ try {
1031
+ const id = await client.resolveProjectId(projectId);
1032
+ const result = await client.rollbackDeployment(id, deploymentId);
1033
+ return {
1034
+ content: [
1035
+ {
1036
+ type: "text",
1037
+ text: JSON.stringify(
1038
+ {
1039
+ success: true,
1040
+ message: `Project rolled back successfully to ${deploymentId}.`,
1041
+ result
1042
+ },
1043
+ null,
1044
+ 2
1045
+ )
1046
+ }
1047
+ ]
1048
+ };
1049
+ } catch (err) {
1050
+ return {
1051
+ isError: true,
1052
+ content: [{ type: "text", text: `Failed to rollback deployment: ${err.message}` }]
1053
+ };
1054
+ }
1055
+ }
1056
+ );
1057
+ server.tool(
1058
+ "taghost_deployment_set_expiry",
1059
+ "Configure ephemeral preview auto-expiry TTL or disable expiry for a deployment.",
1060
+ {
1061
+ projectId: z2.string().optional().describe("Project ID. Defaults to active project."),
1062
+ deploymentId: z2.string().describe('Deployment ID (e.g. "dep_...")'),
1063
+ ttlSeconds: z2.number().optional().describe("Time to live in seconds (e.g. 7200 for 2 hours)"),
1064
+ neverExpire: z2.boolean().optional().describe("Set to true to retain deployment indefinitely")
1065
+ },
1066
+ async ({ projectId, deploymentId, ttlSeconds, neverExpire }) => {
1067
+ try {
1068
+ const id = await client.resolveProjectId(projectId);
1069
+ const result = await client.setDeploymentExpiry(id, deploymentId, ttlSeconds, neverExpire);
1070
+ return {
1071
+ content: [
1072
+ {
1073
+ type: "text",
1074
+ text: JSON.stringify(
1075
+ {
1076
+ success: true,
1077
+ deploymentId,
1078
+ neverExpire: Boolean(neverExpire),
1079
+ ttlSeconds,
1080
+ result
1081
+ },
1082
+ null,
1083
+ 2
1084
+ )
1085
+ }
1086
+ ]
1087
+ };
1088
+ } catch (err) {
1089
+ return {
1090
+ isError: true,
1091
+ content: [{ type: "text", text: `Failed to set deployment expiry: ${err.message}` }]
1092
+ };
1093
+ }
1094
+ }
1095
+ );
1096
+ }
1097
+
1098
+ // src/tools/mail.ts
1099
+ import { z as z3 } from "zod";
1100
+ function registerMailTools(server, client, scopes) {
1101
+ if (hasMcpScope(scopes, "mail:read")) {
1102
+ server.tool(
1103
+ "taghost_mail_threads_list",
1104
+ "Check mail: list email threads and messages in the TagMail inbox with search and mailbox filters.",
1105
+ {
1106
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
1107
+ mailboxId: z3.string().optional().describe("Filter by specific mailbox ID"),
1108
+ query: z3.string().optional().describe("Search query for sender, subject or body text"),
1109
+ limit: z3.number().optional().describe("Maximum number of threads to return (default: 25)")
1110
+ },
1111
+ async ({ projectId, mailboxId, query, limit }) => {
1112
+ try {
1113
+ const id = await client.resolveProjectId(projectId);
1114
+ const result = await client.listMailThreads(id, { mailboxId, query, limit: limit || 25 });
1115
+ const threads = Array.isArray(result) ? result : result.threads || [];
1116
+ return {
1117
+ content: [
1118
+ {
1119
+ type: "text",
1120
+ text: JSON.stringify(
1121
+ {
1122
+ success: true,
1123
+ count: threads.length,
1124
+ threads: threads.map((t) => ({
1125
+ id: t.id,
1126
+ subject: t.subject || "(no subject)",
1127
+ from: t.fromAddress || t.snippetSender,
1128
+ snippet: t.snippet,
1129
+ unread: Boolean(t.unread),
1130
+ messageCount: t.messageCount || 1,
1131
+ receivedAt: t.lastMessageAt || t.receivedAt || t.createdAt
1132
+ }))
1133
+ },
1134
+ null,
1135
+ 2
1136
+ )
1137
+ }
1138
+ ]
1139
+ };
1140
+ } catch (err) {
1141
+ return {
1142
+ isError: true,
1143
+ content: [{ type: "text", text: `Failed to check mail: ${err.message}` }]
1144
+ };
1145
+ }
1146
+ }
1147
+ );
1148
+ server.tool(
1149
+ "taghost_mail_thread_get",
1150
+ "Read the full contents of an email thread, including all inbound and outbound messages and attachment metadata.",
1151
+ {
1152
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
1153
+ threadId: z3.string().describe("The email thread ID to retrieve")
1154
+ },
1155
+ async ({ projectId, threadId }) => {
1156
+ try {
1157
+ const id = await client.resolveProjectId(projectId);
1158
+ const result = await client.getMailThread(id, threadId);
1159
+ return {
1160
+ content: [
1161
+ {
1162
+ type: "text",
1163
+ text: JSON.stringify({ success: true, thread: result.thread || result }, null, 2)
1164
+ }
1165
+ ]
1166
+ };
1167
+ } catch (err) {
1168
+ return {
1169
+ isError: true,
1170
+ content: [{ type: "text", text: `Failed to read mail thread: ${err.message}` }]
1171
+ };
1172
+ }
1173
+ }
1174
+ );
1175
+ }
1176
+ if (hasMcpScope(scopes, "mail:send")) {
1177
+ server.tool(
1178
+ "taghost_mail_send",
1179
+ "Send an email from a TagMail mailbox.",
1180
+ {
1181
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
1182
+ mailboxId: z3.string().optional().describe("Sender mailbox ID (defaults to project primary mailbox)"),
1183
+ to: z3.string().describe("Recipient email address"),
1184
+ subject: z3.string().describe("Email subject line"),
1185
+ text: z3.string().optional().describe("Plain text body content"),
1186
+ html: z3.string().optional().describe("HTML formatted body content"),
1187
+ cc: z3.array(z3.string()).optional().describe("Optional CC recipients"),
1188
+ bcc: z3.array(z3.string()).optional().describe("Optional BCC recipients")
1189
+ },
1190
+ async ({ projectId, mailboxId, to, subject, text, html, cc, bcc }) => {
1191
+ try {
1192
+ const id = await client.resolveProjectId(projectId);
1193
+ const result = await client.sendMail(id, {
1194
+ mailboxId,
1195
+ to,
1196
+ subject,
1197
+ text,
1198
+ html,
1199
+ cc,
1200
+ bcc
1201
+ });
1202
+ return {
1203
+ content: [
1204
+ {
1205
+ type: "text",
1206
+ text: JSON.stringify(
1207
+ {
1208
+ success: true,
1209
+ message: `Email sent to ${to} successfully.`,
1210
+ result
1211
+ },
1212
+ null,
1213
+ 2
1214
+ )
1215
+ }
1216
+ ]
1217
+ };
1218
+ } catch (err) {
1219
+ return {
1220
+ isError: true,
1221
+ content: [{ type: "text", text: `Failed to send email: ${err.message}` }]
1222
+ };
1223
+ }
1224
+ }
1225
+ );
1226
+ server.tool(
1227
+ "taghost_mail_create_mailbox",
1228
+ 'Provision a new corporate mailbox (e.g. "sales@acme.com" or "hello@acme.com") on TagHost.',
1229
+ {
1230
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
1231
+ localPart: z3.string().describe('Local part of address before @ (e.g. "support", "orders", "hello")'),
1232
+ domain: z3.string().optional().describe("Domain name for mailbox (defaults to project custom domain)"),
1233
+ displayName: z3.string().optional().describe('Friendly display name (e.g. "Support Team")'),
1234
+ password: z3.string().optional().describe("Initial password for Webmail/IMAP/SMTP access")
1235
+ },
1236
+ async ({ projectId, localPart, domain, displayName, password }) => {
1237
+ try {
1238
+ const id = await client.resolveProjectId(projectId);
1239
+ const result = await client.createMailbox(id, {
1240
+ localPart,
1241
+ domain,
1242
+ displayName,
1243
+ password
1244
+ });
1245
+ return {
1246
+ content: [
1247
+ {
1248
+ type: "text",
1249
+ text: JSON.stringify(
1250
+ {
1251
+ success: true,
1252
+ message: `Mailbox "${localPart}@${domain || "custom-domain"}" created.`,
1253
+ mailbox: result.mailbox || result
1254
+ },
1255
+ null,
1256
+ 2
1257
+ )
1258
+ }
1259
+ ]
1260
+ };
1261
+ } catch (err) {
1262
+ return {
1263
+ isError: true,
1264
+ content: [{ type: "text", text: `Failed to create mailbox: ${err.message}` }]
1265
+ };
1266
+ }
1267
+ }
1268
+ );
1269
+ }
1270
+ if (hasMcpScope(scopes, "mail:read")) {
1271
+ server.tool(
1272
+ "taghost_mail_domain_verify",
1273
+ "Inspect DNS verification status for corporate email (MX, SPF, DKIM, DMARC records).",
1274
+ {
1275
+ projectId: z3.string().optional().describe("Project ID. Defaults to active project."),
1276
+ domain: z3.string().describe('Domain name to verify (e.g. "acme.com")')
1277
+ },
1278
+ async ({ projectId, domain }) => {
1279
+ try {
1280
+ const id = await client.resolveProjectId(projectId);
1281
+ const result = await client.getMailDomainVerification(id, domain);
1282
+ return {
1283
+ content: [
1284
+ {
1285
+ type: "text",
1286
+ text: JSON.stringify({ success: true, domain, verification: result }, null, 2)
1287
+ }
1288
+ ]
1289
+ };
1290
+ } catch (err) {
1291
+ return {
1292
+ isError: true,
1293
+ content: [{ type: "text", text: `Failed to verify email domain: ${err.message}` }]
1294
+ };
1295
+ }
1296
+ }
1297
+ );
1298
+ }
1299
+ }
1300
+
1301
+ // src/tools/domains.ts
1302
+ import { z as z4 } from "zod";
1303
+ function registerDomainTools(server, client) {
1304
+ server.tool(
1305
+ "taghost_domain_check",
1306
+ "Check domain availability and wholesale registration price.",
1307
+ {
1308
+ domain: z4.string().describe('Domain name to check (e.g. "mybusiness.com", "boutique.ng")')
1309
+ },
1310
+ async ({ domain }) => {
1311
+ try {
1312
+ const result = await client.checkDomainAvailability(domain);
1313
+ return {
1314
+ content: [
1315
+ {
1316
+ type: "text",
1317
+ text: JSON.stringify({ success: true, domain, ...result }, null, 2)
1318
+ }
1319
+ ]
1320
+ };
1321
+ } catch (err) {
1322
+ return {
1323
+ isError: true,
1324
+ content: [{ type: "text", text: `Failed to check domain: ${err.message}` }]
1325
+ };
1326
+ }
1327
+ }
1328
+ );
1329
+ server.tool(
1330
+ "taghost_domain_search",
1331
+ "Search available domains and get TLD suggestions for a brand or business name.",
1332
+ {
1333
+ query: z4.string().describe('Search query or brand name (e.g. "lumiere", "craftbakery")')
1334
+ },
1335
+ async ({ query }) => {
1336
+ try {
1337
+ const result = await client.searchDomains(query);
1338
+ return {
1339
+ content: [
1340
+ {
1341
+ type: "text",
1342
+ text: JSON.stringify({ success: true, query, results: result }, null, 2)
1343
+ }
1344
+ ]
1345
+ };
1346
+ } catch (err) {
1347
+ return {
1348
+ isError: true,
1349
+ content: [{ type: "text", text: `Failed to search domains: ${err.message}` }]
1350
+ };
1351
+ }
1352
+ }
1353
+ );
1354
+ server.tool(
1355
+ "taghost_domain_checkout",
1356
+ "Purchase and automatically register a custom domain for a TagHost project.",
1357
+ {
1358
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1359
+ domain: z4.string().describe('Domain name to register (e.g. "acmestore.com")'),
1360
+ years: z4.number().optional().describe("Registration duration in years (default: 1)"),
1361
+ registrantContact: z4.object({
1362
+ name: z4.string().describe("Contact full name"),
1363
+ email: z4.string().describe("Contact email address"),
1364
+ phone: z4.string().optional().describe("Phone number in international format"),
1365
+ org: z4.string().optional().describe("Company or organization name")
1366
+ }).optional().describe("Registrant contact details")
1367
+ },
1368
+ async ({ projectId, domain, years, registrantContact }) => {
1369
+ try {
1370
+ const id = await client.resolveProjectId(projectId);
1371
+ const result = await client.checkoutDomain(id, {
1372
+ domain,
1373
+ years: years || 1,
1374
+ registrantContact
1375
+ });
1376
+ return {
1377
+ content: [
1378
+ {
1379
+ type: "text",
1380
+ text: JSON.stringify(
1381
+ {
1382
+ success: true,
1383
+ message: `Domain checkout initialized for ${domain}.`,
1384
+ result
1385
+ },
1386
+ null,
1387
+ 2
1388
+ )
1389
+ }
1390
+ ]
1391
+ };
1392
+ } catch (err) {
1393
+ return {
1394
+ isError: true,
1395
+ content: [{ type: "text", text: `Failed to checkout domain: ${err.message}` }]
1396
+ };
1397
+ }
1398
+ }
1399
+ );
1400
+ server.tool(
1401
+ "taghost_domain_attach",
1402
+ "Attach an external or owned domain (Bring-Your-Own-Domain) to a TagHost project.",
1403
+ {
1404
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1405
+ domain: z4.string().describe('Domain name to map (e.g. "shop.example.com" or "example.com")')
1406
+ },
1407
+ async ({ projectId, domain }) => {
1408
+ try {
1409
+ const id = await client.resolveProjectId(projectId);
1410
+ const result = await client.attachDomain(id, domain);
1411
+ return {
1412
+ content: [
1413
+ {
1414
+ type: "text",
1415
+ text: JSON.stringify(
1416
+ {
1417
+ success: true,
1418
+ domain,
1419
+ message: `Domain attached. Configure your DNS CNAME/A records to point to TagHost edge.`,
1420
+ result
1421
+ },
1422
+ null,
1423
+ 2
1424
+ )
1425
+ }
1426
+ ]
1427
+ };
1428
+ } catch (err) {
1429
+ return {
1430
+ isError: true,
1431
+ content: [{ type: "text", text: `Failed to attach domain: ${err.message}` }]
1432
+ };
1433
+ }
1434
+ }
1435
+ );
1436
+ server.tool(
1437
+ "taghost_domain_verify",
1438
+ "Trigger verification of custom domain DNS configuration and edge SSL certificate issuance.",
1439
+ {
1440
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1441
+ domain: z4.string().describe("Domain name to verify")
1442
+ },
1443
+ async ({ projectId, domain }) => {
1444
+ try {
1445
+ const id = await client.resolveProjectId(projectId);
1446
+ const result = await client.verifyDomain(id, domain);
1447
+ return {
1448
+ content: [
1449
+ {
1450
+ type: "text",
1451
+ text: JSON.stringify({ success: true, domain, result }, null, 2)
1452
+ }
1453
+ ]
1454
+ };
1455
+ } catch (err) {
1456
+ return {
1457
+ isError: true,
1458
+ content: [{ type: "text", text: `Failed to verify domain: ${err.message}` }]
1459
+ };
1460
+ }
1461
+ }
1462
+ );
1463
+ server.tool(
1464
+ "taghost_dns_manage",
1465
+ "Manage DNS records (list, create, update, delete) for a TagHost-managed domain.",
1466
+ {
1467
+ projectId: z4.string().optional().describe("Project ID. Defaults to active project."),
1468
+ domain: z4.string().describe("Domain name with TagHost DNS zone"),
1469
+ action: z4.enum(["list", "create", "update", "delete"]).describe("Action to perform"),
1470
+ record: z4.object({
1471
+ id: z4.string().optional().describe("Record ID (for update or delete)"),
1472
+ type: z4.string().optional().describe("DNS Record Type: A, AAAA, CNAME, TXT, MX"),
1473
+ name: z4.string().optional().describe('Host name (e.g. "@", "www", "mail")'),
1474
+ content: z4.string().optional().describe("Value or target IP/host"),
1475
+ ttl: z4.number().optional().describe("Time to live in seconds (default: 3600)"),
1476
+ priority: z4.number().optional().describe("Priority for MX records")
1477
+ }).optional().describe("DNS record properties")
1478
+ },
1479
+ async ({ projectId, domain, action, record }) => {
1480
+ try {
1481
+ const id = await client.resolveProjectId(projectId);
1482
+ if (action === "list") {
1483
+ const records = await client.listDnsRecords(id, domain);
1484
+ return {
1485
+ content: [{ type: "text", text: JSON.stringify({ success: true, domain, records }, null, 2) }]
1486
+ };
1487
+ }
1488
+ if (action === "create") {
1489
+ if (!record?.type || !record?.name || !record?.content) {
1490
+ return {
1491
+ isError: true,
1492
+ content: [{ type: "text", text: "type, name, and content are required to create a DNS record." }]
1493
+ };
1494
+ }
1495
+ const res = await client.createDnsRecord(id, domain, {
1496
+ type: record.type,
1497
+ name: record.name,
1498
+ content: record.content,
1499
+ ttl: record.ttl,
1500
+ priority: record.priority
1501
+ });
1502
+ return {
1503
+ content: [
1504
+ {
1505
+ type: "text",
1506
+ text: JSON.stringify({ success: true, message: "DNS record created.", result: res }, null, 2)
1507
+ }
1508
+ ]
1509
+ };
1510
+ }
1511
+ if (action === "update") {
1512
+ if (!record?.id) {
1513
+ return { isError: true, content: [{ type: "text", text: "Record ID is required for update." }] };
1514
+ }
1515
+ const res = await client.updateDnsRecord(id, domain, record.id, {
1516
+ type: record.type,
1517
+ name: record.name,
1518
+ content: record.content,
1519
+ ttl: record.ttl,
1520
+ priority: record.priority
1521
+ });
1522
+ return {
1523
+ content: [
1524
+ {
1525
+ type: "text",
1526
+ text: JSON.stringify({ success: true, message: "DNS record updated.", result: res }, null, 2)
1527
+ }
1528
+ ]
1529
+ };
1530
+ }
1531
+ if (action === "delete") {
1532
+ if (!record?.id) {
1533
+ return { isError: true, content: [{ type: "text", text: "Record ID is required for delete." }] };
1534
+ }
1535
+ await client.deleteDnsRecord(id, domain, record.id);
1536
+ return {
1537
+ content: [
1538
+ {
1539
+ type: "text",
1540
+ text: JSON.stringify({ success: true, message: `DNS record ${record.id} deleted.` }, null, 2)
1541
+ }
1542
+ ]
1543
+ };
1544
+ }
1545
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
1546
+ } catch (err) {
1547
+ return {
1548
+ isError: true,
1549
+ content: [{ type: "text", text: `Failed to manage DNS: ${err.message}` }]
1550
+ };
1551
+ }
1552
+ }
1553
+ );
1554
+ }
1555
+
1556
+ // src/tools/commerce.ts
1557
+ import { z as z5 } from "zod";
1558
+ function registerCommerceTools(server, client) {
1559
+ server.tool(
1560
+ "taghost_commerce_config",
1561
+ "Configure store commerce settings: store installation mode (companion or standalone), currency, theme, and payment gateway (Paystack or Stripe).",
1562
+ {
1563
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1564
+ currency: z5.string().optional().describe('Store currency code (e.g. "USD", "EUR", "GBP", "NGN", "CAD")'),
1565
+ storeMode: z5.enum(["companion", "standalone"]).optional().describe('Storefront installation mode: "companion" (preserves existing site, adds /store.html) or "standalone" (store is main site)'),
1566
+ gateway: z5.object({
1567
+ provider: z5.enum(["paystack", "stripe"]).describe("Payment provider"),
1568
+ publicKey: z5.string().optional().describe("Client-side public or publishable key"),
1569
+ secretKey: z5.string().optional().describe("Server-side secret key (securely vaulted)"),
1570
+ testMode: z5.boolean().optional().describe("Enable test/sandbox mode"),
1571
+ enabled: z5.boolean().optional().describe("Enable or disable this payment gateway")
1572
+ }).optional().describe("Payment gateway configuration")
1573
+ },
1574
+ async ({ projectId, currency, storeMode, gateway }) => {
1575
+ try {
1576
+ const id = await client.resolveProjectId(projectId);
1577
+ const updates = {};
1578
+ if (currency || storeMode) {
1579
+ const currentTheme = await client.getCommerceTheme(id).catch(() => ({}));
1580
+ const themePayload = {
1581
+ ...currentTheme,
1582
+ ...currency ? { currency } : {},
1583
+ ...storeMode ? { storeMode } : {}
1584
+ };
1585
+ const themeRes = await client.updateCommerceTheme(id, themePayload);
1586
+ updates.theme = themeRes;
1587
+ }
1588
+ if (gateway) {
1589
+ const gwRes = await client.updateCommerceGateway(id, gateway.provider, {
1590
+ publicKey: gateway.publicKey,
1591
+ secretKey: gateway.secretKey,
1592
+ testMode: gateway.testMode ?? false,
1593
+ enabled: gateway.enabled ?? true
1594
+ });
1595
+ updates.gateway = gwRes;
1596
+ }
1597
+ return {
1598
+ content: [
1599
+ {
1600
+ type: "text",
1601
+ text: JSON.stringify(
1602
+ {
1603
+ success: true,
1604
+ message: "Commerce settings updated successfully.",
1605
+ projectId: id,
1606
+ updates
1607
+ },
1608
+ null,
1609
+ 2
1610
+ )
1611
+ }
1612
+ ]
1613
+ };
1614
+ } catch (err) {
1615
+ return {
1616
+ isError: true,
1617
+ content: [{ type: "text", text: `Failed to configure commerce: ${err.message}` }]
1618
+ };
1619
+ }
1620
+ }
1621
+ );
1622
+ server.tool(
1623
+ "taghost_commerce_orders_list",
1624
+ "List customer orders placed on the TagHost store with fulfillment status filtering.",
1625
+ {
1626
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1627
+ status: z5.enum(["pending", "paid", "fulfilled", "delivered", "cancelled", "refunded"]).optional().describe("Filter orders by status"),
1628
+ limit: z5.number().optional().describe("Maximum number of orders to return (default: 50)")
1629
+ },
1630
+ async ({ projectId, status, limit }) => {
1631
+ try {
1632
+ const id = await client.resolveProjectId(projectId);
1633
+ const result = await client.listOrders(id, { status, limit: limit || 50 });
1634
+ const orders = Array.isArray(result) ? result : result.orders || [];
1635
+ return {
1636
+ content: [
1637
+ {
1638
+ type: "text",
1639
+ text: JSON.stringify(
1640
+ {
1641
+ success: true,
1642
+ count: orders.length,
1643
+ orders: orders.map((o) => ({
1644
+ id: o.id,
1645
+ orderNumber: o.orderNumber || o.id,
1646
+ status: o.status,
1647
+ totalAmount: o.totalAmount || o.amount,
1648
+ currency: o.currency || "USD",
1649
+ customerEmail: o.customerEmail || o.email,
1650
+ itemCount: o.items?.length || 1,
1651
+ items: o.items,
1652
+ createdAt: o.createdAt
1653
+ }))
1654
+ },
1655
+ null,
1656
+ 2
1657
+ )
1658
+ }
1659
+ ]
1660
+ };
1661
+ } catch (err) {
1662
+ return {
1663
+ isError: true,
1664
+ content: [{ type: "text", text: `Failed to list orders: ${err.message}` }]
1665
+ };
1666
+ }
1667
+ }
1668
+ );
1669
+ server.tool(
1670
+ "taghost_commerce_order_fulfill",
1671
+ "Mark an order as fulfilled or delivered and update customer tracking details.",
1672
+ {
1673
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1674
+ orderId: z5.string().describe('The order ID to update (e.g. "ord_...")'),
1675
+ status: z5.enum(["fulfilled", "delivered", "cancelled"]).describe("New fulfillment status"),
1676
+ trackingNumber: z5.string().optional().describe("Shipment tracking number"),
1677
+ trackingCarrier: z5.string().optional().describe('Shipping carrier (e.g. "DHL", "FedEx", "USPS", "GIG Logistics")'),
1678
+ trackingUrl: z5.string().optional().describe("Direct link to carrier parcel tracker")
1679
+ },
1680
+ async ({ projectId, orderId, status, trackingNumber, trackingCarrier, trackingUrl }) => {
1681
+ try {
1682
+ const id = await client.resolveProjectId(projectId);
1683
+ const result = await client.updateOrder(id, orderId, {
1684
+ status,
1685
+ trackingNumber,
1686
+ trackingCarrier,
1687
+ trackingUrl
1688
+ });
1689
+ return {
1690
+ content: [
1691
+ {
1692
+ type: "text",
1693
+ text: JSON.stringify(
1694
+ {
1695
+ success: true,
1696
+ orderId,
1697
+ status,
1698
+ tracking: trackingNumber ? { carrier: trackingCarrier, number: trackingNumber, url: trackingUrl } : null,
1699
+ message: `Order ${orderId} marked as ${status}.`,
1700
+ result
1701
+ },
1702
+ null,
1703
+ 2
1704
+ )
1705
+ }
1706
+ ]
1707
+ };
1708
+ } catch (err) {
1709
+ return {
1710
+ isError: true,
1711
+ content: [{ type: "text", text: `Failed to fulfill order: ${err.message}` }]
1712
+ };
1713
+ }
1714
+ }
1715
+ );
1716
+ server.tool(
1717
+ "taghost_coupon_manage",
1718
+ "Manage discount coupons and promotional codes for the store.",
1719
+ {
1720
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1721
+ action: z5.enum(["list", "create", "delete"]).describe("Action to perform"),
1722
+ coupon: z5.object({
1723
+ id: z5.string().optional().describe("Coupon ID (for delete)"),
1724
+ code: z5.string().optional().describe('Promo code entered by shopper (e.g. "WELCOME10", "BLACKFRIDAY")'),
1725
+ discountType: z5.enum(["percentage", "fixed"]).optional().describe("Discount calculation type"),
1726
+ discountAmount: z5.number().optional().describe("Discount value (e.g. 15 for 15% or 20 for $20 off)"),
1727
+ maxUses: z5.number().optional().describe("Maximum number of redemptions allowed"),
1728
+ expiresAt: z5.number().optional().describe("Unix timestamp in milliseconds for expiration")
1729
+ }).optional().describe("Coupon details")
1730
+ },
1731
+ async ({ projectId, action, coupon }) => {
1732
+ try {
1733
+ const id = await client.resolveProjectId(projectId);
1734
+ if (action === "list") {
1735
+ const list = await client.listCoupons(id);
1736
+ return {
1737
+ content: [{ type: "text", text: JSON.stringify({ success: true, coupons: list }, null, 2) }]
1738
+ };
1739
+ }
1740
+ if (action === "create") {
1741
+ if (!coupon?.code || !coupon?.discountType || coupon?.discountAmount === void 0) {
1742
+ return {
1743
+ isError: true,
1744
+ content: [{ type: "text", text: "code, discountType, and discountAmount are required to create a coupon." }]
1745
+ };
1746
+ }
1747
+ const res = await client.createCoupon(id, {
1748
+ code: coupon.code.toUpperCase(),
1749
+ discountType: coupon.discountType,
1750
+ discountAmount: coupon.discountAmount,
1751
+ maxUses: coupon.maxUses,
1752
+ expiresAt: coupon.expiresAt
1753
+ });
1754
+ return {
1755
+ content: [
1756
+ {
1757
+ type: "text",
1758
+ text: JSON.stringify({ success: true, message: `Coupon "${coupon.code}" created.`, coupon: res }, null, 2)
1759
+ }
1760
+ ]
1761
+ };
1762
+ }
1763
+ if (action === "delete") {
1764
+ if (!coupon?.id) {
1765
+ return { isError: true, content: [{ type: "text", text: "Coupon ID is required for delete." }] };
1766
+ }
1767
+ await client.deleteCoupon(id, coupon.id);
1768
+ return {
1769
+ content: [
1770
+ {
1771
+ type: "text",
1772
+ text: JSON.stringify({ success: true, message: `Coupon ${coupon.id} deleted.` }, null, 2)
1773
+ }
1774
+ ]
1775
+ };
1776
+ }
1777
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
1778
+ } catch (err) {
1779
+ return {
1780
+ isError: true,
1781
+ content: [{ type: "text", text: `Failed to manage coupons: ${err.message}` }]
1782
+ };
1783
+ }
1784
+ }
1785
+ );
1786
+ server.tool(
1787
+ "taghost_commerce_migrate_woocommerce",
1788
+ "Migrate a WordPress/WooCommerce site to TagHost Edge. Migrates products, posts, pages, custom post types, customers, orders, R2 media, theme tokens, and 301 _redirects.",
1789
+ {
1790
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1791
+ url: z5.string().optional().describe('WordPress/WooCommerce site URL (e.g. "https://my-store.com")'),
1792
+ consumerKey: z5.string().optional().describe("WooCommerce REST API Consumer Key (ck_...)"),
1793
+ consumerSecret: z5.string().optional().describe("WooCommerce REST API Consumer Secret (cs_...)"),
1794
+ products: z5.array(z5.any()).optional().describe("Direct array of WooCommerce product objects to import (or parsed from CSV/JSON)"),
1795
+ posts: z5.array(z5.any()).optional().describe("Direct array of WordPress blog post objects to import"),
1796
+ pages: z5.array(z5.any()).optional().describe("Direct array of WordPress page objects to import"),
1797
+ customers: z5.array(z5.any()).optional().describe("Direct array of WooCommerce customer objects to import"),
1798
+ orders: z5.array(z5.any()).optional().describe("Direct array of WooCommerce order objects to import"),
1799
+ wxrXml: z5.string().optional().describe("Raw WordPress WXR XML export content (from Tools > Export) for complete offline migration"),
1800
+ options: z5.object({
1801
+ importProducts: z5.boolean().optional().describe("Whether to import products (default: true)"),
1802
+ importPosts: z5.boolean().optional().describe("Whether to import WordPress blog posts (default: true)"),
1803
+ importPages: z5.boolean().optional().describe("Whether to import WordPress pages into a pages collection (default: true)"),
1804
+ importCustomers: z5.boolean().optional().describe("Whether to import customers (default: true)"),
1805
+ importOrders: z5.boolean().optional().describe("Whether to import orders (default: true)"),
1806
+ scrapeDesign: z5.boolean().optional().describe("Whether to scrape brand design & font tokens from site HTML (default: true)"),
1807
+ mirrorMedia: z5.boolean().optional().describe("Whether to mirror remote images into Cloudflare R2 Edge Storage (default: true)"),
1808
+ cleanMarkup: z5.boolean().optional().describe("Whether to strip Gutenberg comments and legacy page-builder shortcodes (default: true)"),
1809
+ writeRedirects: z5.boolean().optional().describe("Whether to generate and merge 301 _redirects for legacy WordPress permalinks (default: true)"),
1810
+ maxPages: z5.number().int().min(1).max(25).optional().describe("Max REST API pages to fetch per resource (100 items/page, default: 10)")
1811
+ }).optional().describe("Migration options")
1812
+ },
1813
+ async ({ projectId, url, consumerKey, consumerSecret, products, posts, pages, customers, orders, wxrXml, options }) => {
1814
+ try {
1815
+ const id = await client.resolveProjectId(projectId);
1816
+ const res = await client.migrateWooCommerce(id, {
1817
+ url,
1818
+ consumerKey,
1819
+ consumerSecret,
1820
+ products,
1821
+ posts,
1822
+ pages,
1823
+ customers,
1824
+ orders,
1825
+ wxrXml,
1826
+ options
1827
+ });
1828
+ return {
1829
+ content: [
1830
+ {
1831
+ type: "text",
1832
+ text: JSON.stringify(
1833
+ {
1834
+ success: res.success,
1835
+ message: `WordPress/WooCommerce migration completed for project ${id}.`,
1836
+ summary: {
1837
+ productsMigrated: res.productsMigrated,
1838
+ postsMigrated: res.postsMigrated,
1839
+ pagesMigrated: res.pagesMigrated,
1840
+ customItemsMigrated: res.customItemsMigrated,
1841
+ mediaMirrored: res.mediaMirrored,
1842
+ customersMigrated: res.customersMigrated,
1843
+ ordersMigrated: res.ordersMigrated,
1844
+ redirectsGenerated: res.redirectsGenerated,
1845
+ redirectsAppliedToDeployment: res.redirectsAppliedToDeployment,
1846
+ themeScraped: res.themeScraped
1847
+ },
1848
+ errors: res.errors
1849
+ },
1850
+ null,
1851
+ 2
1852
+ )
1853
+ }
1854
+ ]
1855
+ };
1856
+ } catch (err) {
1857
+ return {
1858
+ isError: true,
1859
+ content: [{ type: "text", text: `Failed to execute WordPress/WooCommerce migration: ${err.message}` }]
1860
+ };
1861
+ }
1862
+ }
1863
+ );
1864
+ server.tool(
1865
+ "taghost_wordpress_visual_clone",
1866
+ "Clone a live WordPress website into TagHost Edge preserving its exact visual design (HTML, theme/Elementor/Divi CSS, webfonts, images) as an immutable R2 deployment ready for Tier 2 Visual Studio editing, with WordPress forms auto-rewired to /_tag/forms/*.",
1867
+ {
1868
+ projectId: z5.string().optional().describe("Project ID. Defaults to active project."),
1869
+ url: z5.string().describe('Public live WordPress site URL (e.g. "https://example.com")'),
1870
+ maxPages: z5.number().int().min(1).max(30).optional().describe("Max pages to clone (default: 15, max: 30)"),
1871
+ maxAssets: z5.number().int().min(10).max(250).optional().describe("Max CSS/font/image assets to mirror (default: 120, max: 250)"),
1872
+ rewireForms: z5.boolean().optional().describe("Auto-rewire WordPress contact forms to TagHost Edge Forms (default: true)"),
1873
+ syncCollections: z5.boolean().optional().describe("Also import WP posts & pages into TagHost Collections CMS (default: false)")
1874
+ },
1875
+ async ({ projectId, url, maxPages, maxAssets, rewireForms, syncCollections }) => {
1876
+ try {
1877
+ const id = await client.resolveProjectId(projectId);
1878
+ const res = await client.cloneWordPressSite(id, {
1879
+ url,
1880
+ maxPages,
1881
+ maxAssets,
1882
+ rewireForms,
1883
+ syncCollections
1884
+ });
1885
+ return {
1886
+ content: [
1887
+ {
1888
+ type: "text",
1889
+ text: JSON.stringify(
1890
+ {
1891
+ success: res.success,
1892
+ message: `WordPress visual clone deployed for project ${id}.`,
1893
+ deployment: res.deployment,
1894
+ summary: {
1895
+ pagesCloned: res.pagesCloned,
1896
+ editablePagesCount: res.editablePagesCount,
1897
+ totalDiscoveredPages: res.totalDiscoveredPages,
1898
+ assetsMirrored: res.assetsMirrored,
1899
+ formsRewired: res.formsRewired,
1900
+ rewiredFormNames: res.rewiredFormNames,
1901
+ detectedDynamicWidgets: res.detectedDynamicWidgets
1902
+ },
1903
+ errors: res.errors
1904
+ },
1905
+ null,
1906
+ 2
1907
+ )
1908
+ }
1909
+ ]
1910
+ };
1911
+ } catch (err) {
1912
+ return {
1913
+ isError: true,
1914
+ content: [{ type: "text", text: `Failed to visually clone WordPress site: ${err.message}` }]
1915
+ };
1916
+ }
1917
+ }
1918
+ );
1919
+ }
1920
+
1921
+ // src/tools/collections.ts
1922
+ import { z as z6 } from "zod";
1923
+ function registerCollectionTools(server, client) {
1924
+ server.tool(
1925
+ "taghost_collection_create",
1926
+ 'Create a new CMS or product collection (e.g. "products", "services", "menu", "blog") on TagHost.',
1927
+ {
1928
+ projectId: z6.string().optional().describe("Project ID. Defaults to active project."),
1929
+ name: z6.string().describe('Machine identifier for collection (e.g. "products", "lookbook", "menu")'),
1930
+ displayName: z6.string().optional().describe('Friendly display name (e.g. "Featured Products")'),
1931
+ schemaFields: z6.array(
1932
+ z6.object({
1933
+ name: z6.string().describe("Field key name"),
1934
+ type: z6.enum(["text", "number", "boolean", "image", "json", "relation"]).describe("Field data type"),
1935
+ required: z6.boolean().optional().describe("Whether this field is mandatory")
1936
+ })
1937
+ ).optional().describe("Schema field definitions")
1938
+ },
1939
+ async ({ projectId, name, displayName, schemaFields }) => {
1940
+ try {
1941
+ const id = await client.resolveProjectId(projectId);
1942
+ const result = await client.createCollection(id, {
1943
+ name: name.toLowerCase().replace(/[^a-z0-9_-]/g, "_"),
1944
+ displayName: displayName || name,
1945
+ schemaFields
1946
+ });
1947
+ return {
1948
+ content: [
1949
+ {
1950
+ type: "text",
1951
+ text: JSON.stringify(
1952
+ {
1953
+ success: true,
1954
+ message: `Collection "${name}" created successfully.`,
1955
+ collection: result.collection || result
1956
+ },
1957
+ null,
1958
+ 2
1959
+ )
1960
+ }
1961
+ ]
1962
+ };
1963
+ } catch (err) {
1964
+ return {
1965
+ isError: true,
1966
+ content: [{ type: "text", text: `Failed to create collection: ${err.message}` }]
1967
+ };
1968
+ }
1969
+ }
1970
+ );
1971
+ server.tool(
1972
+ "taghost_collection_item_upsert",
1973
+ "Add or update an item/product in a collection with full e-commerce and CMS metadata (price, images, variants, stock).",
1974
+ {
1975
+ projectId: z6.string().optional().describe("Project ID. Defaults to active project."),
1976
+ collectionIdOrName: z6.string().describe('Collection ID or name (e.g. "products")'),
1977
+ itemId: z6.string().optional().describe("Item ID for updates. Omit to insert a new item."),
1978
+ data: z6.record(z6.any()).describe(
1979
+ 'Item payload properties (e.g. { name: "Silk Blouse", price: 85, currency: "USD", image: "https://...", inventory: 20 })'
1980
+ ),
1981
+ publishImmediately: z6.boolean().optional().describe("Whether to publish to live edge CDN immediately (default: true)")
1982
+ },
1983
+ async ({ projectId, collectionIdOrName, itemId, data, publishImmediately }) => {
1984
+ try {
1985
+ const id = await client.resolveProjectId(projectId);
1986
+ let targetCid = collectionIdOrName;
1987
+ if (!targetCid.startsWith("col_")) {
1988
+ const list = await client.listCollections(id);
1989
+ const collections = Array.isArray(list) ? list : list.collections || [];
1990
+ const matched = collections.find((c) => c.name?.toLowerCase() === collectionIdOrName.toLowerCase());
1991
+ if (matched && matched.id) {
1992
+ targetCid = matched.id;
1993
+ }
1994
+ }
1995
+ const result = await client.upsertCollectionItem(id, targetCid, data, itemId);
1996
+ const createdOrUpdatedId = itemId || result.item?.id || result.id;
1997
+ let publishResult = null;
1998
+ if (publishImmediately !== false && createdOrUpdatedId) {
1999
+ publishResult = await client.publishCollectionItem(id, targetCid, createdOrUpdatedId, true).catch(() => null);
2000
+ }
2001
+ return {
2002
+ content: [
2003
+ {
2004
+ type: "text",
2005
+ text: JSON.stringify(
2006
+ {
2007
+ success: true,
2008
+ collectionId: targetCid,
2009
+ itemId: createdOrUpdatedId,
2010
+ item: result.item || result,
2011
+ publishedToEdge: Boolean(publishResult),
2012
+ message: `Collection item ${itemId ? "updated" : "created"}${publishImmediately !== false ? " and published to edge" : ""}.`
2013
+ },
2014
+ null,
2015
+ 2
2016
+ )
2017
+ }
2018
+ ]
2019
+ };
2020
+ } catch (err) {
2021
+ return {
2022
+ isError: true,
2023
+ content: [{ type: "text", text: `Failed to upsert collection item: ${err.message}` }]
2024
+ };
2025
+ }
2026
+ }
2027
+ );
2028
+ server.tool(
2029
+ "taghost_collection_item_publish",
2030
+ "Publish or unpublish a collection item to/from the live edge CDN index (/_tag/collections/:name).",
2031
+ {
2032
+ projectId: z6.string().optional().describe("Project ID. Defaults to active project."),
2033
+ collectionIdOrName: z6.string().describe("Collection ID or name"),
2034
+ itemId: z6.string().describe("Item ID to publish/unpublish"),
2035
+ action: z6.enum(["publish", "unpublish"]).describe("Action to perform")
2036
+ },
2037
+ async ({ projectId, collectionIdOrName, itemId, action }) => {
2038
+ try {
2039
+ const id = await client.resolveProjectId(projectId);
2040
+ let targetCid = collectionIdOrName;
2041
+ if (!targetCid.startsWith("col_")) {
2042
+ const list = await client.listCollections(id);
2043
+ const collections = Array.isArray(list) ? list : list.collections || [];
2044
+ const matched = collections.find((c) => c.name?.toLowerCase() === collectionIdOrName.toLowerCase());
2045
+ if (matched && matched.id) targetCid = matched.id;
2046
+ }
2047
+ const result = await client.publishCollectionItem(id, targetCid, itemId, action === "publish");
2048
+ return {
2049
+ content: [
2050
+ {
2051
+ type: "text",
2052
+ text: JSON.stringify(
2053
+ {
2054
+ success: true,
2055
+ itemId,
2056
+ action,
2057
+ message: `Item ${action}ed on live edge CDN.`,
2058
+ result
2059
+ },
2060
+ null,
2061
+ 2
2062
+ )
2063
+ }
2064
+ ]
2065
+ };
2066
+ } catch (err) {
2067
+ return {
2068
+ isError: true,
2069
+ content: [{ type: "text", text: `Failed to ${action} item: ${err.message}` }]
2070
+ };
2071
+ }
2072
+ }
2073
+ );
2074
+ }
2075
+
2076
+ // src/tools/content.ts
2077
+ import { z as z7 } from "zod";
2078
+ function registerContentTools(server, client) {
2079
+ server.tool(
2080
+ "taghost_content_list",
2081
+ "List all live edge content keys and values (data-tag dictionary) served with sub-millisecond latency from Cloudflare KV.",
2082
+ {
2083
+ projectId: z7.string().optional().describe("Project ID. Defaults to active project.")
2084
+ },
2085
+ async ({ projectId }) => {
2086
+ try {
2087
+ const id = await client.resolveProjectId(projectId);
2088
+ const result = await client.getContent(id);
2089
+ const content = result.content || result || {};
2090
+ return {
2091
+ content: [
2092
+ {
2093
+ type: "text",
2094
+ text: JSON.stringify(
2095
+ {
2096
+ success: true,
2097
+ projectId: id,
2098
+ keyCount: Object.keys(content).length,
2099
+ content
2100
+ },
2101
+ null,
2102
+ 2
2103
+ )
2104
+ }
2105
+ ]
2106
+ };
2107
+ } catch (err) {
2108
+ return {
2109
+ isError: true,
2110
+ content: [{ type: "text", text: `Failed to fetch edge content: ${err.message}` }]
2111
+ };
2112
+ }
2113
+ }
2114
+ );
2115
+ server.tool(
2116
+ "taghost_content_patch",
2117
+ "Perform sub-millisecond live content updates on the edge CDN without redeploying. Patches key-value strings bound via data-tag attributes.",
2118
+ {
2119
+ projectId: z7.string().optional().describe("Project ID. Defaults to active project."),
2120
+ 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" })')
2121
+ },
2122
+ async ({ projectId, patches }) => {
2123
+ try {
2124
+ const id = await client.resolveProjectId(projectId);
2125
+ const result = await client.patchContent(id, patches);
2126
+ return {
2127
+ content: [
2128
+ {
2129
+ type: "text",
2130
+ text: JSON.stringify(
2131
+ {
2132
+ success: true,
2133
+ message: `Patched ${Object.keys(patches).length} content keys in edge KV in <1ms.`,
2134
+ projectId: id,
2135
+ patchedKeys: Object.keys(patches),
2136
+ result
2137
+ },
2138
+ null,
2139
+ 2
2140
+ )
2141
+ }
2142
+ ]
2143
+ };
2144
+ } catch (err) {
2145
+ return {
2146
+ isError: true,
2147
+ content: [{ type: "text", text: `Failed to patch edge content: ${err.message}` }]
2148
+ };
2149
+ }
2150
+ }
2151
+ );
2152
+ server.tool(
2153
+ "taghost_canvas_patch_html",
2154
+ "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.",
2155
+ {
2156
+ projectId: z7.string().optional().describe("Project ID. Defaults to active project."),
2157
+ path: z7.string().optional().describe('Relative path to HTML file (default: "index.html")'),
2158
+ searchString: z7.string().describe("Exact substring or tag snippet to find in the HTML document"),
2159
+ replaceString: z7.string().describe("New HTML replacement snippet to swap in"),
2160
+ commitMessage: z7.string().optional().describe("Publish commit message")
2161
+ },
2162
+ async ({ projectId, path: filePath, searchString, replaceString, commitMessage }) => {
2163
+ try {
2164
+ const id = await client.resolveProjectId(projectId);
2165
+ const targetPath = filePath || "index.html";
2166
+ const fileTree = await client.getProjectFiles(id);
2167
+ const filesList = fileTree.files || [];
2168
+ const targetFile = filesList.find((f) => f.path === targetPath);
2169
+ if (!targetFile || typeof targetFile.content !== "string") {
2170
+ return {
2171
+ isError: true,
2172
+ content: [{ type: "text", text: `File "${targetPath}" not found or content unreadable in deployment.` }]
2173
+ };
2174
+ }
2175
+ if (!targetFile.content.includes(searchString)) {
2176
+ return {
2177
+ isError: true,
2178
+ content: [
2179
+ {
2180
+ type: "text",
2181
+ text: `Target substring not found in "${targetPath}". Ensure the search snippet matches existing HTML characters exactly.`
2182
+ }
2183
+ ]
2184
+ };
2185
+ }
2186
+ const updatedContent = targetFile.content.replace(searchString, replaceString);
2187
+ const publishRes = await client.publishProjectFiles(id, {
2188
+ files: {
2189
+ [targetPath]: updatedContent
2190
+ },
2191
+ message: commitMessage || `MCP canvas DOM patch on ${targetPath}`
2192
+ });
2193
+ return {
2194
+ content: [
2195
+ {
2196
+ type: "text",
2197
+ text: JSON.stringify(
2198
+ {
2199
+ success: true,
2200
+ message: `Surgically patched "${targetPath}" and created new deployment.`,
2201
+ deploymentId: publishRes.deploymentId,
2202
+ previewUrl: publishRes.previewUrl,
2203
+ liveUrl: publishRes.liveUrl
2204
+ },
2205
+ null,
2206
+ 2
2207
+ )
2208
+ }
2209
+ ]
2210
+ };
2211
+ } catch (err) {
2212
+ return {
2213
+ isError: true,
2214
+ content: [{ type: "text", text: `Failed to patch HTML: ${err.message}` }]
2215
+ };
2216
+ }
2217
+ }
2218
+ );
2219
+ }
2220
+
2221
+ // src/tools/forms_crm.ts
2222
+ import { z as z8 } from "zod";
2223
+ function registerFormsCrmTools(server, client) {
2224
+ server.tool(
2225
+ "taghost_forms_get_submissions",
2226
+ 'Retrieve captured lead submissions from native HTML forms (<form action="/_tag/forms/submit" ...>) on TagHost.',
2227
+ {
2228
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
2229
+ formName: z8.string().optional().describe('Filter by specific form name (e.g. "contact", "newsletter", "quote")'),
2230
+ limit: z8.number().optional().describe("Maximum number of submissions to return (default: 50)")
2231
+ },
2232
+ async ({ projectId, formName, limit }) => {
2233
+ try {
2234
+ const id = await client.resolveProjectId(projectId);
2235
+ const result = await client.getFormSubmissions(id, { formName, limit: limit || 50 });
2236
+ const list = Array.isArray(result) ? result : result.submissions || [];
2237
+ return {
2238
+ content: [
2239
+ {
2240
+ type: "text",
2241
+ text: JSON.stringify(
2242
+ {
2243
+ success: true,
2244
+ count: list.length,
2245
+ submissions: list.map((s) => ({
2246
+ id: s.id,
2247
+ formName: s.formName || "default",
2248
+ data: s.data || s.payload,
2249
+ senderIp: s.ipAddress,
2250
+ submittedAt: s.createdAt
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 fetch form submissions: ${err.message}` }]
2263
+ };
2264
+ }
2265
+ }
2266
+ );
2267
+ server.tool(
2268
+ "taghost_crm_sequence_create",
2269
+ "Create an automated email marketing and nurture sequence (e.g. welcome drip, cart abandonment, post-purchase onboarding).",
2270
+ {
2271
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
2272
+ name: z8.string().describe('Campaign or sequence name (e.g. "New Customer Welcome Drip")'),
2273
+ triggerEvent: z8.enum(["form.submitted", "order.completed", "manual"]).describe("Triggering event for the sequence"),
2274
+ steps: z8.array(
2275
+ z8.object({
2276
+ stepOrder: z8.number().describe("Step index starting at 1"),
2277
+ delayMinutes: z8.number().describe("Delay after trigger or previous step in minutes (e.g. 0 for immediate, 1440 for 1 day)"),
2278
+ subject: z8.string().describe("Email subject line"),
2279
+ bodyText: z8.string().optional().describe("Plain text body"),
2280
+ bodyHtml: z8.string().optional().describe("Rich HTML body with merge tags like {{name}}")
2281
+ })
2282
+ ).describe("Sequence steps/emails in chronological order")
2283
+ },
2284
+ async ({ projectId, name, triggerEvent, steps }) => {
2285
+ try {
2286
+ const id = await client.resolveProjectId(projectId);
2287
+ const result = await client.createSequence(id, {
2288
+ name,
2289
+ triggerEvent,
2290
+ steps
2291
+ });
2292
+ return {
2293
+ content: [
2294
+ {
2295
+ type: "text",
2296
+ text: JSON.stringify(
2297
+ {
2298
+ success: true,
2299
+ message: `CRM Sequence "${name}" created with ${steps.length} email step(s).`,
2300
+ sequence: result.sequence || result
2301
+ },
2302
+ null,
2303
+ 2
2304
+ )
2305
+ }
2306
+ ]
2307
+ };
2308
+ } catch (err) {
2309
+ return {
2310
+ isError: true,
2311
+ content: [{ type: "text", text: `Failed to create CRM sequence: ${err.message}` }]
2312
+ };
2313
+ }
2314
+ }
2315
+ );
2316
+ server.tool(
2317
+ "taghost_crm_enroll_lead",
2318
+ "Enroll a customer or lead directly into an automated email nurture sequence.",
2319
+ {
2320
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
2321
+ sequenceId: z8.string().describe("The sequence ID to enroll into"),
2322
+ leadEmail: z8.string().describe("Lead email address"),
2323
+ leadName: z8.string().optional().describe("Lead name for personalized merge tags"),
2324
+ metadata: z8.record(z8.any()).optional().describe('Arbitrary metadata payload for merge tags (e.g. { company: "Acme", interest: "wholesale" })')
2325
+ },
2326
+ async ({ projectId, sequenceId, leadEmail, leadName, metadata }) => {
2327
+ try {
2328
+ const id = await client.resolveProjectId(projectId);
2329
+ const result = await client.enrollSequenceLead(id, sequenceId, {
2330
+ leadEmail,
2331
+ leadName,
2332
+ metadata
2333
+ });
2334
+ return {
2335
+ content: [
2336
+ {
2337
+ type: "text",
2338
+ text: JSON.stringify(
2339
+ {
2340
+ success: true,
2341
+ message: `Enrolled ${leadEmail} into sequence ${sequenceId}.`,
2342
+ result
2343
+ },
2344
+ null,
2345
+ 2
2346
+ )
2347
+ }
2348
+ ]
2349
+ };
2350
+ } catch (err) {
2351
+ return {
2352
+ isError: true,
2353
+ content: [{ type: "text", text: `Failed to enroll lead: ${err.message}` }]
2354
+ };
2355
+ }
2356
+ }
2357
+ );
2358
+ server.tool(
2359
+ "taghost_webhook_configure",
2360
+ "Configure HMAC-signed webhooks for real-time external event notifications (orders, leads, deployments).",
2361
+ {
2362
+ projectId: z8.string().optional().describe("Project ID. Defaults to active project."),
2363
+ action: z8.enum(["list", "create", "delete"]).describe("Action to perform"),
2364
+ webhook: z8.object({
2365
+ id: z8.string().optional().describe("Webhook ID (for delete)"),
2366
+ url: z8.string().optional().describe("Target HTTPS destination URL"),
2367
+ events: z8.array(z8.string()).optional().describe('Subscribed event types (e.g. ["order.created", "form.submitted"])'),
2368
+ secret: z8.string().optional().describe("HMAC SHA-256 signing secret")
2369
+ }).optional().describe("Webhook parameters")
2370
+ },
2371
+ async ({ projectId, action, webhook }) => {
2372
+ try {
2373
+ const id = await client.resolveProjectId(projectId);
2374
+ if (action === "list") {
2375
+ const list = await client.listWebhooks(id);
2376
+ return {
2377
+ content: [{ type: "text", text: JSON.stringify({ success: true, webhooks: list }, null, 2) }]
2378
+ };
2379
+ }
2380
+ if (action === "create") {
2381
+ if (!webhook?.url || !webhook?.events || webhook.events.length === 0) {
2382
+ return {
2383
+ isError: true,
2384
+ content: [{ type: "text", text: "url and events are required to create a webhook." }]
2385
+ };
2386
+ }
2387
+ const res = await client.createWebhook(id, {
2388
+ url: webhook.url,
2389
+ events: webhook.events,
2390
+ secret: webhook.secret
2391
+ });
2392
+ return {
2393
+ content: [
2394
+ {
2395
+ type: "text",
2396
+ text: JSON.stringify({ success: true, message: "Webhook created.", webhook: res }, null, 2)
2397
+ }
2398
+ ]
2399
+ };
2400
+ }
2401
+ if (action === "delete") {
2402
+ if (!webhook?.id) {
2403
+ return { isError: true, content: [{ type: "text", text: "Webhook ID is required for delete." }] };
2404
+ }
2405
+ await client.deleteWebhook(id, webhook.id);
2406
+ return {
2407
+ content: [
2408
+ {
2409
+ type: "text",
2410
+ text: JSON.stringify({ success: true, message: `Webhook ${webhook.id} deleted.` }, null, 2)
2411
+ }
2412
+ ]
2413
+ };
2414
+ }
2415
+ return { isError: true, content: [{ type: "text", text: `Unknown action: ${action}` }] };
2416
+ } catch (err) {
2417
+ return {
2418
+ isError: true,
2419
+ content: [{ type: "text", text: `Failed to configure webhook: ${err.message}` }]
2420
+ };
2421
+ }
2422
+ }
2423
+ );
2424
+ }
2425
+
2426
+ // src/tools/sql.ts
2427
+ import { z as z9 } from "zod";
2428
+
2429
+ // src/utils/sql-guard.ts
2430
+ var FORBIDDEN_SQL_KEYWORDS = [
2431
+ "INSERT",
2432
+ "UPDATE",
2433
+ "DELETE",
2434
+ "DROP",
2435
+ "ALTER",
2436
+ "CREATE",
2437
+ "TRUNCATE",
2438
+ "REPLACE",
2439
+ "ATTACH",
2440
+ "DETACH",
2441
+ "REINDEX",
2442
+ "VACUUM",
2443
+ "GRANT",
2444
+ "REVOKE"
2445
+ ];
2446
+ 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;
2447
+ function validateReadOnlySql(sqlQuery) {
2448
+ const trimmed = (sqlQuery || "").trim();
2449
+ if (!trimmed) {
2450
+ return { valid: false, error: "SQL query cannot be empty." };
2451
+ }
2452
+ const cleaned = trimmed.replace(/--.*$/gm, " ").replace(/\/\*[\s\S]*?\*\//g, " ").trim();
2453
+ if (!cleaned) {
2454
+ return { valid: false, error: "SQL query cannot be empty after stripping comments." };
2455
+ }
2456
+ const firstWordMatch = cleaned.match(/^([A-Za-z]+)/);
2457
+ if (!firstWordMatch) {
2458
+ return { valid: false, error: "Invalid SQL syntax." };
2459
+ }
2460
+ const firstWord = firstWordMatch[1].toUpperCase();
2461
+ const allowedStarters = ["SELECT", "PRAGMA", "EXPLAIN", "WITH"];
2462
+ if (!allowedStarters.includes(firstWord)) {
2463
+ return {
2464
+ valid: false,
2465
+ error: `Forbidden SQL statement '${firstWord}'. The TagHost SQL Explorer only allows read-only statements (${allowedStarters.join(", ")}).`
2466
+ };
2467
+ }
2468
+ const statements = cleaned.split(";").map((s) => s.trim()).filter(Boolean);
2469
+ if (statements.length > 1) {
2470
+ return {
2471
+ valid: false,
2472
+ error: "Multi-statement SQL queries are not permitted. Please submit one query at a time."
2473
+ };
2474
+ }
2475
+ for (const keyword of FORBIDDEN_SQL_KEYWORDS) {
2476
+ const keywordRegex = new RegExp(`\\b${keyword}\\b`, "i");
2477
+ if (keywordRegex.test(cleaned)) {
2478
+ return {
2479
+ valid: false,
2480
+ error: `Query contains forbidden mutating statement keyword '${keyword}'. TagHost Serverless D1 queries are strictly read-only.`
2481
+ };
2482
+ }
2483
+ }
2484
+ if (SENSITIVE_TABLE_PATTERN.test(cleaned)) {
2485
+ return {
2486
+ valid: false,
2487
+ error: "Query accesses platform-internal or credentials tables. Direct query of platform metadata is forbidden."
2488
+ };
2489
+ }
2490
+ return { valid: true };
2491
+ }
2492
+
2493
+ // src/tools/sql.ts
2494
+ function registerSqlTools(server, client) {
2495
+ server.tool(
2496
+ "taghost_sql_introspect_schema",
2497
+ "Introspect the project Cloudflare Serverless D1 SQL database: tables, column names, data types, primary keys, and approximate row counts.",
2498
+ {
2499
+ projectId: z9.string().optional().describe("Project ID. Defaults to active project.")
2500
+ },
2501
+ async ({ projectId }) => {
2502
+ try {
2503
+ const id = await client.resolveProjectId(projectId);
2504
+ const result = await client.listSqlTables(id);
2505
+ return {
2506
+ content: [
2507
+ {
2508
+ type: "text",
2509
+ text: JSON.stringify(
2510
+ {
2511
+ success: true,
2512
+ projectId: id,
2513
+ database: result.database,
2514
+ tableCount: result.tables?.length || 0,
2515
+ tables: result.tables || []
2516
+ },
2517
+ null,
2518
+ 2
2519
+ )
2520
+ }
2521
+ ]
2522
+ };
2523
+ } catch (err) {
2524
+ return {
2525
+ isError: true,
2526
+ content: [{ type: "text", text: `Failed to introspect SQL schema: ${err.message}` }]
2527
+ };
2528
+ }
2529
+ }
2530
+ );
2531
+ server.tool(
2532
+ "taghost_sql_query",
2533
+ "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).",
2534
+ {
2535
+ projectId: z9.string().optional().describe("Project ID. Defaults to active project."),
2536
+ query: z9.string().describe('Read-only SQL statement (e.g. "SELECT * FROM orders WHERE status = ? LIMIT 10")'),
2537
+ params: z9.array(z9.any()).optional().describe("Positional SQL query parameters")
2538
+ },
2539
+ async ({ projectId, query, params }) => {
2540
+ try {
2541
+ const guardCheck = validateReadOnlySql(query);
2542
+ if (!guardCheck.valid) {
2543
+ return {
2544
+ isError: true,
2545
+ content: [{ type: "text", text: `SQL Security Guard rejected query: ${guardCheck.error}` }]
2546
+ };
2547
+ }
2548
+ const id = await client.resolveProjectId(projectId);
2549
+ const result = await client.executeSqlQuery(id, query, params || []);
2550
+ return {
2551
+ content: [
2552
+ {
2553
+ type: "text",
2554
+ text: JSON.stringify(
2555
+ {
2556
+ success: true,
2557
+ rowCount: result.rows?.length ?? (Array.isArray(result.results) ? result.results.length : 0),
2558
+ columns: result.columns,
2559
+ rows: result.rows || result.results || [],
2560
+ durationMs: result.durationMs
2561
+ },
2562
+ null,
2563
+ 2
2564
+ )
2565
+ }
2566
+ ]
2567
+ };
2568
+ } catch (err) {
2569
+ return {
2570
+ isError: true,
2571
+ content: [{ type: "text", text: `Failed to execute SQL query: ${err.message}` }]
2572
+ };
2573
+ }
2574
+ }
2575
+ );
2576
+ }
2577
+
2578
+ // src/tools/observability.ts
2579
+ import { z as z10 } from "zod";
2580
+ function registerObservabilityTools(server, client) {
2581
+ server.tool(
2582
+ "taghost_quota_check",
2583
+ "Inspect workspace quota, plan tier, build usage, custom domain allocations, and mailbox seats.",
2584
+ {
2585
+ projectId: z10.string().optional().describe("Project ID. Defaults to active project.")
2586
+ },
2587
+ async ({ projectId }) => {
2588
+ try {
2589
+ const id = await client.resolveProjectId(projectId);
2590
+ const me = await client.getMe();
2591
+ const usage = await client.getWorkspaceUsage().catch(() => null);
2592
+ return {
2593
+ content: [
2594
+ {
2595
+ type: "text",
2596
+ text: JSON.stringify(
2597
+ {
2598
+ success: true,
2599
+ projectId: id,
2600
+ user: {
2601
+ id: me?.user?.id,
2602
+ email: me?.user?.email,
2603
+ role: me?.membership?.role || "owner"
2604
+ },
2605
+ workspace: {
2606
+ id: me?.workspace?.id,
2607
+ name: me?.workspace?.name,
2608
+ plan: me?.workspace?.plan || "hobby"
2609
+ },
2610
+ usage: usage || {
2611
+ note: "Platform quotas active. Refer to Console Settings for real-time edge meters."
2612
+ }
2613
+ },
2614
+ null,
2615
+ 2
2616
+ )
2617
+ }
2618
+ ]
2619
+ };
2620
+ } catch (err) {
2621
+ return {
2622
+ isError: true,
2623
+ content: [{ type: "text", text: `Failed to check quota: ${err.message}` }]
2624
+ };
2625
+ }
2626
+ }
2627
+ );
2628
+ server.tool(
2629
+ "taghost_ast_eject_preview",
2630
+ 'Zero-lock-in export preview: strip all "data-tag" and "data-th-id" attributes from HTML or JSX, returning clean, framework-independent standard code.',
2631
+ {
2632
+ htmlOrCode: z10.string().describe("HTML snippet or JSX code to clean and eject")
2633
+ },
2634
+ async ({ htmlOrCode }) => {
2635
+ try {
2636
+ let count = 0;
2637
+ const cleaned = htmlOrCode.replace(/\s+(data-tag|data-th-id)(="[^"]*"|='[^']*'|=\{[^}]*\})?/g, () => {
2638
+ count++;
2639
+ return "";
2640
+ });
2641
+ return {
2642
+ content: [
2643
+ {
2644
+ type: "text",
2645
+ text: JSON.stringify(
2646
+ {
2647
+ success: true,
2648
+ strippedCount: count,
2649
+ message: `Removed ${count} platform attribute(s). Code is 100% clean and portable.`,
2650
+ ejectedCode: cleaned
2651
+ },
2652
+ null,
2653
+ 2
2654
+ )
2655
+ }
2656
+ ]
2657
+ };
2658
+ } catch (err) {
2659
+ return {
2660
+ isError: true,
2661
+ content: [{ type: "text", text: `Failed to preview eject: ${err.message}` }]
2662
+ };
2663
+ }
2664
+ }
2665
+ );
2666
+ }
2667
+
2668
+ // src/tools/tasks_collaboration.ts
2669
+ import { z as z11 } from "zod";
2670
+ function registerTasksCollaborationTools(server, client) {
2671
+ server.tool(
2672
+ "taghost_task_create",
2673
+ "Create and schedule a task, to-do, or reminder in TagWork with due dates, priorities, and team assignments.",
2674
+ {
2675
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
2676
+ title: z11.string().describe('Title of the task (e.g. "Review customer return requests", "Prep monthly email newsletter")'),
2677
+ description: z11.string().optional().describe("Detailed task instructions, checklist, or context"),
2678
+ dueAt: z11.number().optional().describe("Due date as Unix timestamp in milliseconds"),
2679
+ priority: z11.enum(["urgent", "high", "medium", "low"]).optional().describe("Task priority level (default: medium)"),
2680
+ assigneeId: z11.string().optional().describe("User ID of workspace team member to assign"),
2681
+ threadId: z11.string().optional().describe("Optional TagMail email thread ID to link this task to"),
2682
+ color: z11.enum(["crimson", "blue", "amber", "emerald", "violet"]).optional().describe("Card highlight color")
2683
+ },
2684
+ async ({ workspaceId, title, description, dueAt, priority, assigneeId, threadId, color }) => {
2685
+ try {
2686
+ const wsId = await client.resolveWorkspaceId(workspaceId);
2687
+ const result = await client.createTask(wsId, {
2688
+ title,
2689
+ description,
2690
+ dueAt,
2691
+ priority: priority || "medium",
2692
+ assigneeId,
2693
+ threadId,
2694
+ color
2695
+ });
2696
+ return {
2697
+ content: [
2698
+ {
2699
+ type: "text",
2700
+ text: JSON.stringify(
2701
+ {
2702
+ success: true,
2703
+ message: `Task "${title}" created and scheduled.`,
2704
+ task: result.task || result
2705
+ },
2706
+ null,
2707
+ 2
2708
+ )
2709
+ }
2710
+ ]
2711
+ };
2712
+ } catch (err) {
2713
+ return {
2714
+ isError: true,
2715
+ content: [{ type: "text", text: `Failed to create task: ${err.message}` }]
2716
+ };
2717
+ }
2718
+ }
2719
+ );
2720
+ server.tool(
2721
+ "taghost_task_list",
2722
+ "List tasks and reminders in the TagWork workspace with status filters (todo, done, due date).",
2723
+ {
2724
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
2725
+ completed: z11.boolean().optional().describe("Filter by completion status (false for pending to-dos, true for finished)"),
2726
+ threadId: z11.string().optional().describe("Filter tasks attached to a specific email thread")
2727
+ },
2728
+ async ({ workspaceId, completed, threadId }) => {
2729
+ try {
2730
+ const wsId = await client.resolveWorkspaceId(workspaceId);
2731
+ const result = await client.listTasks(wsId, { completed, threadId });
2732
+ const tasks = Array.isArray(result) ? result : result.tasks || [];
2733
+ return {
2734
+ content: [
2735
+ {
2736
+ type: "text",
2737
+ text: JSON.stringify(
2738
+ {
2739
+ success: true,
2740
+ count: tasks.length,
2741
+ tasks: tasks.map((t) => ({
2742
+ id: t.id,
2743
+ title: t.title,
2744
+ description: t.description,
2745
+ priority: t.priority,
2746
+ completed: Boolean(t.completed),
2747
+ dueAt: t.dueAt ? new Date(t.dueAt).toISOString() : null,
2748
+ assigneeId: t.assigneeId,
2749
+ threadId: t.threadId,
2750
+ createdAt: t.createdAt
2751
+ }))
2752
+ },
2753
+ null,
2754
+ 2
2755
+ )
2756
+ }
2757
+ ]
2758
+ };
2759
+ } catch (err) {
2760
+ return {
2761
+ isError: true,
2762
+ content: [{ type: "text", text: `Failed to list tasks: ${err.message}` }]
2763
+ };
2764
+ }
2765
+ }
2766
+ );
2767
+ server.tool(
2768
+ "taghost_task_update",
2769
+ "Update a task status (mark done/completed), reschedule due date, reassign, or edit instructions.",
2770
+ {
2771
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
2772
+ taskId: z11.string().describe('The task ID to update (e.g. "tsk_...")'),
2773
+ completed: z11.boolean().optional().describe("Mark task completed (true) or open (false)"),
2774
+ title: z11.string().optional().describe("Updated task title"),
2775
+ description: z11.string().optional().describe("Updated instructions or notes"),
2776
+ dueAt: z11.number().nullable().optional().describe("Updated due date Unix timestamp in milliseconds (or null to clear)"),
2777
+ priority: z11.enum(["urgent", "high", "medium", "low"]).optional().describe("Updated priority"),
2778
+ assigneeId: z11.string().nullable().optional().describe("Reassign to team member user ID")
2779
+ },
2780
+ async ({ workspaceId, taskId, completed, title, description, dueAt, priority, assigneeId }) => {
2781
+ try {
2782
+ const wsId = await client.resolveWorkspaceId(workspaceId);
2783
+ const patch = {};
2784
+ if (completed !== void 0) patch.completed = completed;
2785
+ if (title !== void 0) patch.title = title;
2786
+ if (description !== void 0) patch.description = description;
2787
+ if (dueAt !== void 0) patch.dueAt = dueAt;
2788
+ if (priority !== void 0) patch.priority = priority;
2789
+ if (assigneeId !== void 0) patch.assigneeId = assigneeId;
2790
+ const result = await client.updateTask(wsId, taskId, patch);
2791
+ return {
2792
+ content: [
2793
+ {
2794
+ type: "text",
2795
+ text: JSON.stringify(
2796
+ {
2797
+ success: true,
2798
+ message: `Task ${taskId} updated.`,
2799
+ task: result.task || result
2800
+ },
2801
+ null,
2802
+ 2
2803
+ )
2804
+ }
2805
+ ]
2806
+ };
2807
+ } catch (err) {
2808
+ return {
2809
+ isError: true,
2810
+ content: [{ type: "text", text: `Failed to update task: ${err.message}` }]
2811
+ };
2812
+ }
2813
+ }
2814
+ );
2815
+ server.tool(
2816
+ "taghost_task_delete",
2817
+ "Delete a task from the workspace.",
2818
+ {
2819
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
2820
+ taskId: z11.string().describe("The task ID to delete")
2821
+ },
2822
+ async ({ workspaceId, taskId }) => {
2823
+ try {
2824
+ const wsId = await client.resolveWorkspaceId(workspaceId);
2825
+ await client.deleteTask(wsId, taskId);
2826
+ return {
2827
+ content: [
2828
+ {
2829
+ type: "text",
2830
+ text: JSON.stringify({ success: true, message: `Task ${taskId} deleted.` }, null, 2)
2831
+ }
2832
+ ]
2833
+ };
2834
+ } catch (err) {
2835
+ return {
2836
+ isError: true,
2837
+ content: [{ type: "text", text: `Failed to delete task: ${err.message}` }]
2838
+ };
2839
+ }
2840
+ }
2841
+ );
2842
+ server.tool(
2843
+ "taghost_calendar_schedule_event",
2844
+ "Schedule a meeting, appointment, deadline, or team event on the workspace calendar.",
2845
+ {
2846
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
2847
+ title: z11.string().describe('Event or meeting title (e.g. "Q4 Product Strategy Review", "Supplier Order Catch-up")'),
2848
+ startAt: z11.number().describe('Start timestamp in milliseconds (e.g. Date.parse("2026-11-10T14:00:00Z"))'),
2849
+ endAt: z11.number().describe("End timestamp in milliseconds"),
2850
+ description: z11.string().optional().describe("Agenda, dial-in notes, or meeting summary"),
2851
+ location: z11.string().optional().describe('Location or virtual meeting link (e.g. "https://meet.taghost.io/room/acme-weekly")'),
2852
+ attendees: z11.array(z11.string()).optional().describe("List of attendee email addresses"),
2853
+ allDay: z11.boolean().optional().describe("Whether this is an all-day event"),
2854
+ recurrence: z11.enum(["none", "daily", "weekly", "monthly", "yearly"]).optional().describe("Recurrence rule (default: none)")
2855
+ },
2856
+ async ({ workspaceId, title, startAt, endAt, description, location, attendees, allDay, recurrence }) => {
2857
+ try {
2858
+ const wsId = await client.resolveWorkspaceId(workspaceId);
2859
+ const result = await client.createCalendarEvent(wsId, {
2860
+ title,
2861
+ startAt,
2862
+ endAt,
2863
+ description,
2864
+ location,
2865
+ attendees,
2866
+ allDay: Boolean(allDay),
2867
+ recurrence: recurrence || "none"
2868
+ });
2869
+ return {
2870
+ content: [
2871
+ {
2872
+ type: "text",
2873
+ text: JSON.stringify(
2874
+ {
2875
+ success: true,
2876
+ message: `Calendar event "${title}" scheduled.`,
2877
+ event: result.event || result
2878
+ },
2879
+ null,
2880
+ 2
2881
+ )
2882
+ }
2883
+ ]
2884
+ };
2885
+ } catch (err) {
2886
+ return {
2887
+ isError: true,
2888
+ content: [{ type: "text", text: `Failed to schedule calendar event: ${err.message}` }]
2889
+ };
2890
+ }
2891
+ }
2892
+ );
2893
+ server.tool(
2894
+ "taghost_calendar_list_events",
2895
+ "List scheduled calendar events and meetings within a date range.",
2896
+ {
2897
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
2898
+ start: z11.number().optional().describe("Range start timestamp in milliseconds (defaults to current time)"),
2899
+ end: z11.number().optional().describe("Range end timestamp in milliseconds (defaults to 30 days ahead)")
2900
+ },
2901
+ async ({ workspaceId, start, end }) => {
2902
+ try {
2903
+ const wsId = await client.resolveWorkspaceId(workspaceId);
2904
+ const now = Date.now();
2905
+ const startTs = start || now;
2906
+ const endTs = end || now + 30 * 24 * 60 * 60 * 1e3;
2907
+ const result = await client.listCalendarEvents(wsId, { start: startTs, end: endTs });
2908
+ const events = Array.isArray(result) ? result : result.events || [];
2909
+ return {
2910
+ content: [
2911
+ {
2912
+ type: "text",
2913
+ text: JSON.stringify(
2914
+ {
2915
+ success: true,
2916
+ count: events.length,
2917
+ events: events.map((e) => ({
2918
+ id: e.id,
2919
+ title: e.title,
2920
+ description: e.description,
2921
+ location: e.location,
2922
+ startAt: new Date(e.startAt).toISOString(),
2923
+ endAt: new Date(e.endAt).toISOString(),
2924
+ allDay: Boolean(e.allDay),
2925
+ recurrence: e.recurrence,
2926
+ attendees: e.attendees
2927
+ }))
2928
+ },
2929
+ null,
2930
+ 2
2931
+ )
2932
+ }
2933
+ ]
2934
+ };
2935
+ } catch (err) {
2936
+ return {
2937
+ isError: true,
2938
+ content: [{ type: "text", text: `Failed to list calendar events: ${err.message}` }]
2939
+ };
2940
+ }
2941
+ }
2942
+ );
2943
+ server.tool(
2944
+ "taghost_calendar_delete_event",
2945
+ "Cancel or delete a scheduled event from the workspace calendar.",
2946
+ {
2947
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
2948
+ eventId: z11.string().describe("The calendar event ID to delete")
2949
+ },
2950
+ async ({ workspaceId, eventId }) => {
2951
+ try {
2952
+ const wsId = await client.resolveWorkspaceId(workspaceId);
2953
+ await client.deleteCalendarEvent(wsId, eventId);
2954
+ return {
2955
+ content: [
2956
+ {
2957
+ type: "text",
2958
+ text: JSON.stringify({ success: true, message: `Event ${eventId} removed from calendar.` }, null, 2)
2959
+ }
2960
+ ]
2961
+ };
2962
+ } catch (err) {
2963
+ return {
2964
+ isError: true,
2965
+ content: [{ type: "text", text: `Failed to delete calendar event: ${err.message}` }]
2966
+ };
2967
+ }
2968
+ }
2969
+ );
2970
+ server.tool(
2971
+ "taghost_meet_create_room",
2972
+ "Create an instant or scheduled video conference meeting room on TagMeet with custom link, recording, and transcription.",
2973
+ {
2974
+ name: z11.string().optional().describe('Friendly room or meeting name (e.g. "Weekly Standup", "Client Demo")'),
2975
+ scheduledStartAt: z11.number().optional().describe("Scheduled start Unix timestamp in milliseconds"),
2976
+ allowGuests: z11.boolean().optional().describe("Allow external attendees to join via link without signing in (default: true)"),
2977
+ recordRoom: z11.boolean().optional().describe("Automatically record audio/video session")
2978
+ },
2979
+ async ({ name, scheduledStartAt, allowGuests, recordRoom }) => {
2980
+ try {
2981
+ const result = await client.createMeetRoom({
2982
+ name: name || "TagMeet Conference",
2983
+ scheduledStartAt,
2984
+ allowGuests: allowGuests !== false,
2985
+ recordRoom: Boolean(recordRoom)
2986
+ });
2987
+ const room = result.room || result;
2988
+ const roomCode = room.code || room.id;
2989
+ const joinUrl = `https://meet.taghost.io/room/${roomCode}`;
2990
+ return {
2991
+ content: [
2992
+ {
2993
+ type: "text",
2994
+ text: JSON.stringify(
2995
+ {
2996
+ success: true,
2997
+ roomCode,
2998
+ joinUrl,
2999
+ name: room.name,
3000
+ scheduledStartAt: room.scheduledStartAt ? new Date(room.scheduledStartAt).toISOString() : "instant",
3001
+ allowGuests: room.allowGuests,
3002
+ message: `TagMeet room created. Join link: ${joinUrl}`
3003
+ },
3004
+ null,
3005
+ 2
3006
+ )
3007
+ }
3008
+ ]
3009
+ };
3010
+ } catch (err) {
3011
+ return {
3012
+ isError: true,
3013
+ content: [{ type: "text", text: `Failed to create TagMeet room: ${err.message}` }]
3014
+ };
3015
+ }
3016
+ }
3017
+ );
3018
+ server.tool(
3019
+ "taghost_note_create",
3020
+ "Create a persistent workspace note or meeting agenda in TagWork.",
3021
+ {
3022
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
3023
+ title: z11.string().describe("Note headline"),
3024
+ content: z11.string().optional().describe("Markdown or plain text content"),
3025
+ color: z11.enum(["crimson", "blue", "amber", "emerald", "violet"]).optional().describe("Card color")
3026
+ },
3027
+ async ({ workspaceId, title, content, color }) => {
3028
+ try {
3029
+ const wsId = await client.resolveWorkspaceId(workspaceId);
3030
+ const result = await client.createNote(wsId, { title, content, color });
3031
+ return {
3032
+ content: [
3033
+ {
3034
+ type: "text",
3035
+ text: JSON.stringify(
3036
+ {
3037
+ success: true,
3038
+ message: `Note "${title}" saved.`,
3039
+ note: result.note || result
3040
+ },
3041
+ null,
3042
+ 2
3043
+ )
3044
+ }
3045
+ ]
3046
+ };
3047
+ } catch (err) {
3048
+ return {
3049
+ isError: true,
3050
+ content: [{ type: "text", text: `Failed to create note: ${err.message}` }]
3051
+ };
3052
+ }
3053
+ }
3054
+ );
3055
+ server.tool(
3056
+ "taghost_note_list",
3057
+ "List all shared team notes and agendas in the workspace.",
3058
+ {
3059
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace.")
3060
+ },
3061
+ async ({ workspaceId }) => {
3062
+ try {
3063
+ const wsId = await client.resolveWorkspaceId(workspaceId);
3064
+ const result = await client.listNotes(wsId);
3065
+ const notes = Array.isArray(result) ? result : result.notes || [];
3066
+ return {
3067
+ content: [
3068
+ {
3069
+ type: "text",
3070
+ text: JSON.stringify({ success: true, count: notes.length, notes }, null, 2)
3071
+ }
3072
+ ]
3073
+ };
3074
+ } catch (err) {
3075
+ return {
3076
+ isError: true,
3077
+ content: [{ type: "text", text: `Failed to list notes: ${err.message}` }]
3078
+ };
3079
+ }
3080
+ }
3081
+ );
3082
+ server.tool(
3083
+ "taghost_automation_schedule",
3084
+ "Schedule an autonomous AI background automation or standing cron task for TagHost (e.g. daily inventory check, weekly blog post draft, hourly order sync, or custom prompt).",
3085
+ {
3086
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
3087
+ name: z11.string().describe('Friendly name of the automation (e.g. "Daily Order Fulfillment Digest", "Weekly Tech Blog Post Draft")'),
3088
+ prompt: z11.string().describe("Clear, actionable instructions or prompt for the autonomous agent to execute when triggered"),
3089
+ target: z11.enum(["store_orders", "inventory_monitor", "content_drafting", "seo_health", "custom"]).describe("Target system or workflow category"),
3090
+ recurrence: z11.enum(["hourly", "daily", "weekly", "monthly", "once"]).describe("Execution schedule frequency"),
3091
+ cronExpression: z11.string().optional().describe('Optional standard cron string (e.g. "0 8 * * *" for 8:00 AM daily)'),
3092
+ parameters: z11.record(z11.any()).optional().describe('Optional structured payload parameters (e.g. { lowStockThreshold: 3, channel: "email" })')
3093
+ },
3094
+ async ({ workspaceId, name, prompt, target, recurrence, cronExpression, parameters }) => {
3095
+ try {
3096
+ const wsId = await client.resolveWorkspaceId(workspaceId);
3097
+ const now = Date.now();
3098
+ let dueAt = now + 36e5;
3099
+ if (recurrence === "daily") dueAt = now + 864e5;
3100
+ else if (recurrence === "weekly") dueAt = now + 7 * 864e5;
3101
+ else if (recurrence === "monthly") dueAt = now + 30 * 864e5;
3102
+ else if (recurrence === "hourly") dueAt = now + 36e5;
3103
+ const automationMeta = {
3104
+ type: "agent_automation",
3105
+ name,
3106
+ prompt,
3107
+ target,
3108
+ recurrence,
3109
+ cronExpression: cronExpression || (recurrence === "daily" ? "0 8 * * *" : void 0),
3110
+ parameters: parameters || {},
3111
+ lastRunAt: null,
3112
+ runCount: 0,
3113
+ status: "active"
3114
+ };
3115
+ const result = await client.createTask(wsId, {
3116
+ title: `\u{1F916} [AI Automation] ${name}`,
3117
+ description: JSON.stringify(automationMeta, null, 2),
3118
+ dueAt,
3119
+ priority: "medium",
3120
+ color: "lilac"
3121
+ });
3122
+ const task = result.task || result;
3123
+ return {
3124
+ content: [
3125
+ {
3126
+ type: "text",
3127
+ text: JSON.stringify(
3128
+ {
3129
+ success: true,
3130
+ message: `Autonomous automation "${name}" scheduled successfully.`,
3131
+ automation: {
3132
+ id: task.id,
3133
+ name,
3134
+ target,
3135
+ recurrence,
3136
+ cronExpression: automationMeta.cronExpression,
3137
+ firstRunAt: new Date(dueAt).toISOString(),
3138
+ prompt
3139
+ }
3140
+ },
3141
+ null,
3142
+ 2
3143
+ )
3144
+ }
3145
+ ]
3146
+ };
3147
+ } catch (err) {
3148
+ return {
3149
+ isError: true,
3150
+ content: [{ type: "text", text: `Failed to schedule automation: ${err.message}` }]
3151
+ };
3152
+ }
3153
+ }
3154
+ );
3155
+ server.tool(
3156
+ "taghost_automation_list",
3157
+ "List all standing autonomous AI agent automations and scheduled background tasks in the workspace.",
3158
+ {
3159
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
3160
+ status: z11.enum(["all", "active", "paused"]).optional().describe("Filter by automation status (default: all)")
3161
+ },
3162
+ async ({ workspaceId, status }) => {
3163
+ try {
3164
+ const wsId = await client.resolveWorkspaceId(workspaceId);
3165
+ const result = await client.listTasks(wsId);
3166
+ const allTasks = Array.isArray(result) ? result : result.tasks || [];
3167
+ const automations = allTasks.filter((t) => {
3168
+ if (t.title?.includes("[AI Automation]") || t.title?.includes("\u{1F916}")) return true;
3169
+ try {
3170
+ const parsed = JSON.parse(t.description || "{}");
3171
+ return parsed.type === "agent_automation";
3172
+ } catch {
3173
+ return false;
3174
+ }
3175
+ }).map((t) => {
3176
+ let meta = {};
3177
+ try {
3178
+ meta = JSON.parse(t.description || "{}");
3179
+ } catch {
3180
+ meta = { prompt: t.description };
3181
+ }
3182
+ return {
3183
+ id: t.id,
3184
+ name: meta.name || t.title.replace(/^🤖\s*(\[AI Automation\]\s*)?/, ""),
3185
+ prompt: meta.prompt || t.description,
3186
+ target: meta.target || "custom",
3187
+ recurrence: meta.recurrence || "custom",
3188
+ cronExpression: meta.cronExpression,
3189
+ status: t.completed ? "completed" : meta.status || "active",
3190
+ nextRunAt: t.dueAt ? new Date(t.dueAt).toISOString() : null,
3191
+ lastRunAt: meta.lastRunAt ? new Date(meta.lastRunAt).toISOString() : null,
3192
+ runCount: meta.runCount || 0,
3193
+ createdAt: t.createdAt ? new Date(t.createdAt).toISOString() : null
3194
+ };
3195
+ }).filter((a) => {
3196
+ if (!status || status === "all") return true;
3197
+ return a.status === status;
3198
+ });
3199
+ return {
3200
+ content: [
3201
+ {
3202
+ type: "text",
3203
+ text: JSON.stringify(
3204
+ {
3205
+ success: true,
3206
+ count: automations.length,
3207
+ automations
3208
+ },
3209
+ null,
3210
+ 2
3211
+ )
3212
+ }
3213
+ ]
3214
+ };
3215
+ } catch (err) {
3216
+ return {
3217
+ isError: true,
3218
+ content: [{ type: "text", text: `Failed to list automations: ${err.message}` }]
3219
+ };
3220
+ }
3221
+ }
3222
+ );
3223
+ server.tool(
3224
+ "taghost_automation_trigger",
3225
+ "Manually trigger an immediate execution run of an autonomous AI agent automation.",
3226
+ {
3227
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
3228
+ automationId: z11.string().describe('The task/automation ID to run immediately (e.g. "tsk_...")'),
3229
+ summaryResult: z11.string().optional().describe("Optional summary or logs of what the agent performed during this run")
3230
+ },
3231
+ async ({ workspaceId, automationId, summaryResult }) => {
3232
+ try {
3233
+ const wsId = await client.resolveWorkspaceId(workspaceId);
3234
+ const result = await client.listTasks(wsId);
3235
+ const allTasks = Array.isArray(result) ? result : result.tasks || [];
3236
+ const task = allTasks.find((t) => t.id === automationId);
3237
+ if (!task) {
3238
+ return {
3239
+ isError: true,
3240
+ content: [{ type: "text", text: `Automation with ID "${automationId}" not found.` }]
3241
+ };
3242
+ }
3243
+ let meta = {};
3244
+ try {
3245
+ meta = JSON.parse(task.description || "{}");
3246
+ } catch {
3247
+ meta = {};
3248
+ }
3249
+ const now = Date.now();
3250
+ const recurrence = meta.recurrence || "daily";
3251
+ let nextDueAt = now + 864e5;
3252
+ if (recurrence === "hourly") nextDueAt = now + 36e5;
3253
+ else if (recurrence === "weekly") nextDueAt = now + 7 * 864e5;
3254
+ else if (recurrence === "monthly") nextDueAt = now + 30 * 864e5;
3255
+ const updatedMeta = {
3256
+ ...meta,
3257
+ lastRunAt: now,
3258
+ runCount: (meta.runCount || 0) + 1,
3259
+ latestExecutionSummary: summaryResult || `Executed by AI Agent at ${new Date(now).toISOString()}`
3260
+ };
3261
+ await client.updateTask(wsId, automationId, {
3262
+ description: JSON.stringify(updatedMeta, null, 2),
3263
+ dueAt: nextDueAt
3264
+ });
3265
+ return {
3266
+ content: [
3267
+ {
3268
+ type: "text",
3269
+ text: JSON.stringify(
3270
+ {
3271
+ success: true,
3272
+ message: `Automation "${meta.name || task.title}" executed.`,
3273
+ runCount: updatedMeta.runCount,
3274
+ executedAt: new Date(now).toISOString(),
3275
+ nextRunAt: new Date(nextDueAt).toISOString(),
3276
+ executionSummary: updatedMeta.latestExecutionSummary
3277
+ },
3278
+ null,
3279
+ 2
3280
+ )
3281
+ }
3282
+ ]
3283
+ };
3284
+ } catch (err) {
3285
+ return {
3286
+ isError: true,
3287
+ content: [{ type: "text", text: `Failed to trigger automation: ${err.message}` }]
3288
+ };
3289
+ }
3290
+ }
3291
+ );
3292
+ server.tool(
3293
+ "taghost_automation_cancel",
3294
+ "Cancel and delete a scheduled autonomous agent automation.",
3295
+ {
3296
+ workspaceId: z11.string().optional().describe("Workspace ID. Defaults to active workspace."),
3297
+ automationId: z11.string().describe("The automation task ID to cancel and remove")
3298
+ },
3299
+ async ({ workspaceId, automationId }) => {
3300
+ try {
3301
+ const wsId = await client.resolveWorkspaceId(workspaceId);
3302
+ await client.deleteTask(wsId, automationId);
3303
+ return {
3304
+ content: [
3305
+ {
3306
+ type: "text",
3307
+ text: JSON.stringify(
3308
+ {
3309
+ success: true,
3310
+ message: `Automation ${automationId} cancelled and deleted.`
3311
+ },
3312
+ null,
3313
+ 2
3314
+ )
3315
+ }
3316
+ ]
3317
+ };
3318
+ } catch (err) {
3319
+ return {
3320
+ isError: true,
3321
+ content: [{ type: "text", text: `Failed to cancel automation: ${err.message}` }]
3322
+ };
3323
+ }
3324
+ }
3325
+ );
3326
+ }
3327
+
3328
+ // src/resources/index.ts
3329
+ function registerResources(server, client) {
3330
+ server.resource(
3331
+ "taghost-project-current",
3332
+ "taghost://project/current",
3333
+ async (uri) => {
3334
+ try {
3335
+ const projectId = await client.resolveProjectId();
3336
+ const project = await client.getProject(projectId);
3337
+ return {
3338
+ contents: [
3339
+ {
3340
+ uri: uri.href,
3341
+ text: JSON.stringify(
3342
+ {
3343
+ id: project.id,
3344
+ name: project.name,
3345
+ slug: project.slug,
3346
+ framework: project.framework,
3347
+ activeDeploymentId: project.activeDeploymentId,
3348
+ customDomain: project.customDomain,
3349
+ previewUrl: project.activeDeploymentId ? `https://${project.activeDeploymentId}.taghost.site` : null,
3350
+ liveUrl: project.customDomain ? `https://${project.customDomain}` : `https://${project.slug}.taghost.site`
3351
+ },
3352
+ null,
3353
+ 2
3354
+ )
3355
+ }
3356
+ ]
3357
+ };
3358
+ } catch (err) {
3359
+ return {
3360
+ contents: [
3361
+ {
3362
+ uri: uri.href,
3363
+ text: JSON.stringify({ error: `Could not resolve current project: ${err.message}` }, null, 2)
3364
+ }
3365
+ ]
3366
+ };
3367
+ }
3368
+ }
3369
+ );
3370
+ server.resource(
3371
+ "taghost-design-tokens",
3372
+ "taghost://design-system/tokens",
3373
+ async (uri) => {
3374
+ return {
3375
+ contents: [
3376
+ {
3377
+ uri: uri.href,
3378
+ text: JSON.stringify(
3379
+ {
3380
+ brand: {
3381
+ primary: "#FF2636",
3382
+ primaryHover: "#E01E2E",
3383
+ darkBg: "#0A0A0C",
3384
+ darkSurface: "#121214",
3385
+ darkBorder: "rgba(255, 255, 255, 0.08)"
3386
+ },
3387
+ typography: {
3388
+ primaryFont: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
3389
+ displayFont: "Syne, Outfit, -apple-system, sans-serif"
3390
+ },
3391
+ rules: [
3392
+ "Use relatable, friendly design suitable for everyday business owners.",
3393
+ "Every layout wireframe must be structurally distinct (e.g. editorial split lookbook, bento stage, daily ritual arch, department deal columns, bakehouse batch cards).",
3394
+ "Never clobber existing websites \u2014 always check whether to publish companion storefronts (/store.html, /products.html) or standalone sites."
3395
+ ]
3396
+ },
3397
+ null,
3398
+ 2
3399
+ )
3400
+ }
3401
+ ]
3402
+ };
3403
+ }
3404
+ );
3405
+ server.resource(
3406
+ "taghost-docs-editing-scope",
3407
+ "taghost://docs/editing-scope",
3408
+ async (uri) => {
3409
+ return {
3410
+ contents: [
3411
+ {
3412
+ uri: uri.href,
3413
+ text: `# TagHost Editing Scope & Best Practices
3414
+
3415
+ 1. Non-Destructive File Publishing:
3416
+ - Use 'taghost_publish_files' to update specific files (such as adding /store.html and /products.html) while carrying forward all other deployment assets untouched.
3417
+ - Preserves customer websites and prevents 404s.
3418
+
3419
+ 2. Companion vs Standalone Stores:
3420
+ - 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.
3421
+ - Standalone Store: For brand-new stores. Generates index.html, store.html, products.html, about.html, and contact.html.
3422
+
3423
+ 3. Live Edge Content (data-tag):
3424
+ - Elements tagged with data-tag="key" can be patched in <1ms via 'taghost_content_patch' without triggering redeploys or cache invalidation delays.
3425
+
3426
+ 4. Serverless D1 SQL:
3427
+ - Strictly read-only queries (SELECT, PRAGMA, EXPLAIN, WITH CTE).
3428
+ - Direct DDL/DML mutations are blocked to protect tenant data isolation.
3429
+ `
3430
+ }
3431
+ ]
3432
+ };
3433
+ }
3434
+ );
3435
+ }
3436
+
3437
+ // src/prompts/index.ts
3438
+ import { z as z12 } from "zod";
3439
+ function registerPrompts(server) {
3440
+ server.prompt(
3441
+ "taghost-setup-ecommerce-store",
3442
+ "Guided autonomous workflow for AI agents to set up an e-commerce storefront, seed product collections, and configure payments.",
3443
+ {
3444
+ storeName: z12.string().describe('Business or store name (e.g. "Lumi\xE8re Atelier")'),
3445
+ storeType: z12.enum(["modern_home", "fashion_boutique", "beauty_wellness", "everyday_retail", "gourmet_artisan"]).describe("Store design style and layout template"),
3446
+ mode: z12.enum(["companion", "standalone"]).describe("Whether to accompany an existing website or build a standalone store"),
3447
+ currency: z12.string().optional().describe("Store currency (e.g. USD, EUR, GBP, NGN)")
3448
+ },
3449
+ async ({ storeName, storeType, mode, currency }) => {
3450
+ return {
3451
+ messages: [
3452
+ {
3453
+ role: "user",
3454
+ content: {
3455
+ type: "text",
3456
+ text: `Please set up an e-commerce store for "${storeName}".
3457
+
3458
+ Specifications:
3459
+ - Template Layout: ${storeType}
3460
+ - 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"})
3461
+ - Store Currency: ${currency || "USD"}
3462
+
3463
+ Instructions for Autonomous AI Agent:
3464
+ 1. Use 'taghost_project_get' or check the active project binding.
3465
+ 2. If in companion mode, call 'taghost_publish_files' with 'store.html' and 'products.html' so existing website files are carried forward non-destructively.
3466
+ 3. Call 'taghost_collection_create' for 'products' collection if not already created.
3467
+ 4. Add 3 to 5 realistic, relatable sample products using 'taghost_collection_item_upsert' with name, price, description, and images.
3468
+ 5. Configure store currency and gateway using 'taghost_commerce_config'.
3469
+ 6. Confirm the live store URL and summary.`
3470
+ }
3471
+ }
3472
+ ]
3473
+ };
3474
+ }
3475
+ );
3476
+ server.prompt(
3477
+ "taghost-setup-business-mail",
3478
+ "Guided workflow to search/purchase a custom domain, configure DNS records, and provision professional business mailboxes (TagMail).",
3479
+ {
3480
+ domainName: z12.string().describe('The domain name to check, register, or attach (e.g. "acmebrands.com")'),
3481
+ mailboxUser: z12.string().describe('The primary mailbox username (e.g. "hello", "support", "orders")')
3482
+ },
3483
+ async ({ domainName, mailboxUser }) => {
3484
+ return {
3485
+ messages: [
3486
+ {
3487
+ role: "user",
3488
+ content: {
3489
+ type: "text",
3490
+ text: `Please configure custom business email for domain "${domainName}" with mailbox "${mailboxUser}@${domainName}".
3491
+
3492
+ Instructions for Autonomous AI Agent:
3493
+ 1. Call 'taghost_domain_check' to check domain registration status or price.
3494
+ 2. If the user owns the domain, call 'taghost_domain_attach'. If registering new, call 'taghost_domain_checkout'.
3495
+ 3. Call 'taghost_mail_domain_verify' to retrieve required MX, SPF, DKIM, and DMARC DNS records.
3496
+ 4. Call 'taghost_mail_create_mailbox' with localPart: "${mailboxUser}" and domain: "${domainName}".
3497
+ 5. Return instructions and mailbox status to the user.`
3498
+ }
3499
+ }
3500
+ ]
3501
+ };
3502
+ }
3503
+ );
3504
+ server.prompt(
3505
+ "taghost-scaffold-and-ship",
3506
+ "Guided workflow to create a new project, write high-converting HTML/CSS, and deploy it to the TagHost edge CDN.",
3507
+ {
3508
+ projectName: z12.string().describe("Name of the project to create"),
3509
+ businessType: z12.string().describe('Industry or business type (e.g. "Artisan Bakery", "Dental Clinic", "SaaS Platform")')
3510
+ },
3511
+ async ({ projectName, businessType }) => {
3512
+ return {
3513
+ messages: [
3514
+ {
3515
+ role: "user",
3516
+ content: {
3517
+ type: "text",
3518
+ text: `Please create and deploy a modern website for "${projectName}" (${businessType}).
3519
+
3520
+ Instructions for Autonomous AI Agent:
3521
+ 1. Call 'taghost_project_create' with name: "${projectName}".
3522
+ 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.
3523
+ 3. Call 'taghost_publish_files' to deploy the initial files directly to the edge CDN.
3524
+ 4. Output the preview URL and live edge status.`
3525
+ }
3526
+ }
3527
+ ]
3528
+ };
3529
+ }
3530
+ );
3531
+ }
3532
+
3533
+ // src/server.ts
3534
+ dotenv.config();
3535
+ function createTagHostMcpServer(options = {}) {
3536
+ const server = new McpServer({
3537
+ name: options.name || "taghost-mcp",
3538
+ version: options.version || "1.0.0"
3539
+ });
3540
+ const client = new TagHostClient(options);
3541
+ const scopes = options.scopes ?? null;
3542
+ if (hasMcpScope(scopes, "projects:read") || hasMcpScope(scopes, "deployments:write")) {
3543
+ registerProjectTools(server, client, scopes);
3544
+ }
3545
+ if (hasMcpScope(scopes, "deployments:write")) {
3546
+ registerDeploymentTools(server, client);
3547
+ }
3548
+ if (hasMcpScope(scopes, "mail:read") || hasMcpScope(scopes, "mail:send")) {
3549
+ registerMailTools(server, client, scopes);
3550
+ }
3551
+ if (hasMcpScope(scopes, "domains:write")) {
3552
+ registerDomainTools(server, client);
3553
+ }
3554
+ if (hasMcpScope(scopes, "commerce:write")) {
3555
+ registerCommerceTools(server, client);
3556
+ }
3557
+ if (hasMcpScope(scopes, "content:write")) {
3558
+ registerCollectionTools(server, client);
3559
+ registerContentTools(server, client);
3560
+ }
3561
+ if (hasMcpScope(scopes, "forms:read")) {
3562
+ registerFormsCrmTools(server, client);
3563
+ }
3564
+ if (hasMcpScope(scopes, "sql:read")) {
3565
+ registerSqlTools(server, client);
3566
+ }
3567
+ if (hasMcpScope(scopes, "projects:read")) {
3568
+ registerObservabilityTools(server, client);
3569
+ }
3570
+ if (hasMcpScope(scopes, "workspace:collaborate")) {
3571
+ registerTasksCollaborationTools(server, client);
3572
+ }
3573
+ if (hasMcpScope(scopes, "projects:read")) {
3574
+ registerResources(server, client);
3575
+ }
3576
+ registerPrompts(server);
3577
+ return { server, client };
3578
+ }
3579
+ async function startServer(options = {}) {
3580
+ const { server } = createTagHostMcpServer(options);
3581
+ const transport = new StdioServerTransport();
3582
+ await server.connect(transport);
3583
+ return server;
3584
+ }
3585
+ if (typeof process !== "undefined" && process.argv[1] && (process.argv[1].endsWith("server.js") || process.argv[1].endsWith("taghost-mcp.js"))) {
3586
+ startServer().catch((err) => {
3587
+ console.error("Fatal error starting TagHost MCP server:", err);
3588
+ process.exit(1);
3589
+ });
3590
+ }
3591
+
3592
+ export {
3593
+ getApiUrl,
3594
+ sanitizeAuthToken,
3595
+ resolveAuthToken,
3596
+ findProjectBinding,
3597
+ TagHostClient,
3598
+ MCP_SCOPES,
3599
+ ALL_MCP_SCOPES,
3600
+ normalizeMcpScopes,
3601
+ hasMcpScope,
3602
+ bundleDirectory,
3603
+ bundleVirtualFiles,
3604
+ validateReadOnlySql,
3605
+ createTagHostMcpServer,
3606
+ startServer
3607
+ };