@contentrain/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1488 @@
1
+ #!/usr/bin/env node
2
+ import { a as removeDir, i as listJsonFiles, n as fileExists, o as removeFile, t as ensureDir } from "./fs-D83-Ii_y.mjs";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { dirname, join } from "node:path";
6
+ import { cp, mkdtemp, readFile, rename, stat, writeFile } from "node:fs/promises";
7
+ import { tmpdir } from "node:os";
8
+ import { randomBytes, randomUUID } from "node:crypto";
9
+ import { simpleGit } from "simple-git";
10
+ import { z } from "zod";
11
+ //#region src/util/json.ts
12
+ /**
13
+ * Read and parse a JSON file. Returns empty array if file doesn't exist.
14
+ */
15
+ async function readJsonFile(filePath) {
16
+ try {
17
+ const raw = await readFile(filePath, "utf-8");
18
+ return JSON.parse(raw);
19
+ } catch (err) {
20
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") return [];
21
+ throw err;
22
+ }
23
+ }
24
+ /**
25
+ * Write JSON to file atomically (temp file + rename).
26
+ */
27
+ async function writeJsonFile(filePath, data) {
28
+ await ensureDir(dirname(filePath));
29
+ const tmpPath = join(dirname(filePath), `.tmp-${randomBytes(4).toString("hex")}.json`);
30
+ await writeFile(tmpPath, JSON.stringify(data, null, 2) + "\n", "utf-8");
31
+ await rename(tmpPath, filePath);
32
+ }
33
+ //#endregion
34
+ //#region src/errors.ts
35
+ var ContentrainError = class extends Error {
36
+ code;
37
+ context;
38
+ constructor(message, code, context = {}) {
39
+ super(message);
40
+ this.name = "ContentrainError";
41
+ this.code = code;
42
+ this.context = context;
43
+ }
44
+ };
45
+ var ModelNotFoundError = class extends ContentrainError {
46
+ constructor(modelId) {
47
+ super(`Model not found: ${modelId}`, "MODEL_NOT_FOUND", { modelId });
48
+ this.name = "ModelNotFoundError";
49
+ }
50
+ };
51
+ var EntryNotFoundError = class extends ContentrainError {
52
+ constructor(modelId, entryId) {
53
+ super(`Entry not found: ${entryId} in model ${modelId}`, "ENTRY_NOT_FOUND", {
54
+ modelId,
55
+ entryId
56
+ });
57
+ this.name = "EntryNotFoundError";
58
+ }
59
+ };
60
+ var GitSyncError = class extends ContentrainError {
61
+ constructor(message, context = {}) {
62
+ super(message, "GIT_SYNC_ERROR", context);
63
+ this.name = "GitSyncError";
64
+ }
65
+ };
66
+ var PushRejectedError = class extends GitSyncError {
67
+ attemptsExhausted;
68
+ constructor(attemptsExhausted) {
69
+ super(attemptsExhausted ? "Push rejected: all retry attempts exhausted" : "Push rejected by remote", { attemptsExhausted });
70
+ this.name = "PushRejectedError";
71
+ this.attemptsExhausted = attemptsExhausted;
72
+ }
73
+ };
74
+ var AssetNotFoundError = class extends ContentrainError {
75
+ constructor(assetPath) {
76
+ super(`Asset not found in registry: ${assetPath}`, "ASSET_NOT_FOUND", { assetPath });
77
+ this.name = "AssetNotFoundError";
78
+ }
79
+ };
80
+ //#endregion
81
+ //#region src/core/model/system-fields.ts
82
+ /**
83
+ * Generate the 4 required system fields for a model.
84
+ */
85
+ function createSystemFields(modelId) {
86
+ return [
87
+ {
88
+ name: "createdAt",
89
+ fieldId: "createdAt",
90
+ componentId: "date",
91
+ options: {},
92
+ validations: { "required-field": { value: true } },
93
+ fieldType: "date",
94
+ system: true,
95
+ defaultField: false,
96
+ modelId
97
+ },
98
+ {
99
+ name: "updatedAt",
100
+ fieldId: "updatedAt",
101
+ componentId: "date",
102
+ options: {},
103
+ validations: { "required-field": { value: true } },
104
+ fieldType: "date",
105
+ system: true,
106
+ defaultField: false,
107
+ modelId
108
+ },
109
+ {
110
+ name: "ID",
111
+ fieldId: "ID",
112
+ componentId: "single-line-text",
113
+ options: {},
114
+ validations: { "required-field": { value: true } },
115
+ fieldType: "string",
116
+ system: true,
117
+ defaultField: false,
118
+ modelId
119
+ },
120
+ {
121
+ name: "status",
122
+ fieldId: "status",
123
+ componentId: "single-line-text",
124
+ options: {},
125
+ validations: { "required-field": { value: true } },
126
+ fieldType: "string",
127
+ system: true,
128
+ defaultField: false,
129
+ modelId
130
+ }
131
+ ];
132
+ }
133
+ /**
134
+ * Generate MD/MDX default fields (slug + content).
135
+ */
136
+ function createMdDefaultFields(modelId) {
137
+ return [{
138
+ name: "slug",
139
+ fieldId: "slug",
140
+ componentId: "slug",
141
+ options: {},
142
+ validations: {
143
+ "required-field": { value: true },
144
+ "unique-field": { value: true }
145
+ },
146
+ fieldType: "string",
147
+ system: false,
148
+ defaultField: true,
149
+ modelId
150
+ }, {
151
+ name: "content",
152
+ fieldId: "content",
153
+ componentId: "md-editor",
154
+ options: {},
155
+ validations: { "required-field": { value: false } },
156
+ fieldType: "string",
157
+ system: false,
158
+ defaultField: true,
159
+ modelId
160
+ }];
161
+ }
162
+ //#endregion
163
+ //#region src/core/model/manager.ts
164
+ var ModelManager = class {
165
+ constructor(basePath) {
166
+ this.basePath = basePath;
167
+ }
168
+ get modelsDir() {
169
+ return join(this.basePath, "models");
170
+ }
171
+ get metadataPath() {
172
+ return join(this.modelsDir, "metadata.json");
173
+ }
174
+ async list() {
175
+ return readJsonFile(this.metadataPath);
176
+ }
177
+ async get(modelId) {
178
+ const model = (await this.list()).find((m) => m.modelId === modelId);
179
+ if (!model) throw new ModelNotFoundError(modelId);
180
+ return model;
181
+ }
182
+ async getFields(modelId) {
183
+ await this.get(modelId);
184
+ return readJsonFile(join(this.modelsDir, `${modelId}.json`));
185
+ }
186
+ async describe(modelId) {
187
+ const model = await this.get(modelId);
188
+ const fields = await this.getFields(modelId);
189
+ return {
190
+ model,
191
+ fields,
192
+ customFields: fields.filter((f) => !f.system && !f.defaultField)
193
+ };
194
+ }
195
+ async create(input) {
196
+ const models = await this.list();
197
+ if (models.some((m) => m.modelId === input.modelId)) throw new Error(`Model already exists: ${input.modelId}`);
198
+ const metadata = {
199
+ name: input.name,
200
+ description: input.description,
201
+ modelId: input.modelId,
202
+ path: input.path,
203
+ localization: input.localization,
204
+ type: input.type,
205
+ createdBy: "user",
206
+ isServerless: false
207
+ };
208
+ models.push(metadata);
209
+ await writeJsonFile(this.metadataPath, models);
210
+ const systemFields = createSystemFields(input.modelId);
211
+ const mdFields = input.type === "MD" || input.type === "MDX" ? createMdDefaultFields(input.modelId) : [];
212
+ const customFields = (input.fields || []).map((f) => ({
213
+ ...f,
214
+ modelId: input.modelId,
215
+ system: false,
216
+ defaultField: false
217
+ }));
218
+ const allFields = [
219
+ ...systemFields,
220
+ ...mdFields,
221
+ ...customFields
222
+ ];
223
+ await ensureDir(this.modelsDir);
224
+ await writeJsonFile(join(this.modelsDir, `${input.modelId}.json`), allFields);
225
+ const contentDir = join(this.basePath, input.modelId);
226
+ await ensureDir(contentDir);
227
+ if (input.localization) {} else await writeJsonFile(join(contentDir, `${input.modelId}.json`), []);
228
+ return metadata;
229
+ }
230
+ async addField(modelId, field) {
231
+ const fields = await this.getFields(modelId);
232
+ if (fields.some((f) => f.fieldId === field.fieldId)) throw new Error(`Field already exists: ${field.fieldId} in model ${modelId}`);
233
+ const newField = {
234
+ ...field,
235
+ modelId,
236
+ system: false,
237
+ defaultField: false
238
+ };
239
+ fields.push(newField);
240
+ await writeJsonFile(join(this.modelsDir, `${modelId}.json`), fields);
241
+ return newField;
242
+ }
243
+ async removeField(modelId, fieldId) {
244
+ const fields = await this.getFields(modelId);
245
+ const field = fields.find((f) => f.fieldId === fieldId);
246
+ if (!field) throw new Error(`Field not found: ${fieldId} in model ${modelId}`);
247
+ if (field.system) throw new Error(`Cannot remove system field: ${fieldId}`);
248
+ const filtered = fields.filter((f) => f.fieldId !== fieldId);
249
+ await writeJsonFile(join(this.modelsDir, `${modelId}.json`), filtered);
250
+ }
251
+ async delete(modelId) {
252
+ const models = await this.list();
253
+ const filtered = models.filter((m) => m.modelId !== modelId);
254
+ if (filtered.length === models.length) throw new ModelNotFoundError(modelId);
255
+ await writeJsonFile(this.metadataPath, filtered);
256
+ const { removeFile, removeDir } = await import("./fs-D83-Ii_y.mjs").then((n) => n.r);
257
+ await removeFile(join(this.modelsDir, `${modelId}.json`));
258
+ await removeDir(join(this.basePath, modelId));
259
+ }
260
+ };
261
+ //#endregion
262
+ //#region src/util/id.ts
263
+ const ID_PATTERN = /^[a-f0-9]{12}$/;
264
+ /**
265
+ * Generate a 12-character lowercase hexadecimal ID.
266
+ * Matches the Contentrain platform: crypto.randomUUID().split('-').pop()
267
+ */
268
+ function generateId() {
269
+ return randomUUID().split("-").pop();
270
+ }
271
+ /**
272
+ * Validate that a string matches the Contentrain ID format.
273
+ */
274
+ function isValidId(id) {
275
+ return ID_PATTERN.test(id);
276
+ }
277
+ //#endregion
278
+ //#region src/core/content/markdown.ts
279
+ /**
280
+ * Build frontmatter string from entry data (excluding 'content' field).
281
+ */
282
+ function buildFrontmatter(entry) {
283
+ const lines = ["---"];
284
+ for (const [key, value] of Object.entries(entry)) {
285
+ if (key === "content") continue;
286
+ if (typeof value === "string") lines.push(`${key}: '${value}'`);
287
+ else if (typeof value === "boolean" || typeof value === "number") lines.push(`${key}: ${value}`);
288
+ else if (Array.isArray(value)) lines.push(`${key}: ${JSON.stringify(value)}`);
289
+ }
290
+ lines.push("---");
291
+ return lines.join("\n");
292
+ }
293
+ /**
294
+ * Get the markdown file extension based on model type.
295
+ */
296
+ function getExtension(type) {
297
+ return type === "MDX" ? ".mdx" : ".md";
298
+ }
299
+ /**
300
+ * Resolve the markdown file path for an entry.
301
+ */
302
+ function resolveMarkdownPath(repoPath, model, entry, locale) {
303
+ const basePath = entry.path || model.path || "";
304
+ const ext = getExtension(model.type);
305
+ if (locale) return join(repoPath, basePath, locale, `${entry.slug}${ext}`);
306
+ return join(repoPath, basePath, `${entry.slug}${ext}`);
307
+ }
308
+ var MarkdownSync = class {
309
+ constructor(repoPath) {
310
+ this.repoPath = repoPath;
311
+ }
312
+ /**
313
+ * Write a markdown file for an MD/MDX entry.
314
+ */
315
+ async write(model, entry, content, locale) {
316
+ const filePath = resolveMarkdownPath(this.repoPath, model, entry, locale);
317
+ await ensureDir(join(filePath, ".."));
318
+ await writeFile(filePath, `${buildFrontmatter(entry)}\n\n${content || ""}\n`, "utf-8");
319
+ return filePath;
320
+ }
321
+ /**
322
+ * Read markdown content from a file.
323
+ */
324
+ async read(model, entry, locale) {
325
+ const filePath = resolveMarkdownPath(this.repoPath, model, entry, locale);
326
+ try {
327
+ const match = (await readFile(filePath, "utf-8")).match(/^---\n[\s\S]*?\n---\n\n?([\s\S]*)$/);
328
+ return match ? match[1].trim() : "";
329
+ } catch {
330
+ return "";
331
+ }
332
+ }
333
+ /**
334
+ * Delete a markdown file for an entry.
335
+ */
336
+ async delete(model, entry, locale) {
337
+ await removeFile(resolveMarkdownPath(this.repoPath, model, entry, locale));
338
+ }
339
+ };
340
+ //#endregion
341
+ //#region src/core/content/manager.ts
342
+ var ContentManager = class {
343
+ modelManager;
344
+ markdownSync;
345
+ constructor(basePath, repoPath) {
346
+ this.basePath = basePath;
347
+ this.repoPath = repoPath;
348
+ this.modelManager = new ModelManager(basePath);
349
+ this.markdownSync = new MarkdownSync(repoPath);
350
+ }
351
+ contentDir(modelId) {
352
+ return join(this.basePath, modelId);
353
+ }
354
+ contentFilePath(modelId, locale) {
355
+ const dir = this.contentDir(modelId);
356
+ return locale ? join(dir, `${locale}.json`) : join(dir, `${modelId}.json`);
357
+ }
358
+ async list(modelId, locale) {
359
+ const model = await this.modelManager.get(modelId);
360
+ return readJsonFile(this.resolveContentPath(model, locale));
361
+ }
362
+ async get(modelId, entryId, locale) {
363
+ const entry = (await this.list(modelId, locale)).find((e) => e.ID === entryId);
364
+ if (!entry) throw new EntryNotFoundError(modelId, entryId);
365
+ return entry;
366
+ }
367
+ async getLocales(modelId) {
368
+ if (!(await this.modelManager.get(modelId)).localization) return [];
369
+ return (await listJsonFiles(this.contentDir(modelId))).filter((f) => f !== modelId);
370
+ }
371
+ async create(modelId, data, options) {
372
+ const model = await this.modelManager.get(modelId);
373
+ const id = options?.id || generateId();
374
+ const now = (/* @__PURE__ */ new Date()).toISOString();
375
+ const entry = {
376
+ ID: id,
377
+ createdAt: now,
378
+ updatedAt: now,
379
+ status: options?.status || "draft",
380
+ scheduled: false,
381
+ ...data
382
+ };
383
+ if (model.localization) await this.createLocalized(model, entry, options?.locale, options?.content);
384
+ else await this.appendEntry(model, entry, void 0, options?.content);
385
+ return id;
386
+ }
387
+ async update(modelId, entryId, data, options) {
388
+ const model = await this.modelManager.get(modelId);
389
+ const locale = model.localization ? options?.locale : void 0;
390
+ const filePath = this.resolveContentPath(model, locale);
391
+ const entries = await readJsonFile(filePath);
392
+ const index = entries.findIndex((e) => e.ID === entryId);
393
+ if (index === -1) throw new EntryNotFoundError(modelId, entryId);
394
+ const updated = {
395
+ ...entries[index],
396
+ ...data,
397
+ ID: entryId,
398
+ createdAt: entries[index].createdAt,
399
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
400
+ };
401
+ entries[index] = updated;
402
+ await writeJsonFile(filePath, entries);
403
+ if ((model.type === "MD" || model.type === "MDX") && "slug" in updated) {
404
+ const mdContent = options?.content ?? await this.markdownSync.read(model, updated, locale);
405
+ await this.markdownSync.write(model, updated, mdContent, locale);
406
+ }
407
+ return updated;
408
+ }
409
+ async delete(modelId, entryId) {
410
+ const model = await this.modelManager.get(modelId);
411
+ if (model.localization) {
412
+ const locales = await this.getLocales(modelId);
413
+ for (const locale of locales) await this.deleteFromFile(model, entryId, locale);
414
+ } else await this.deleteFromFile(model, entryId);
415
+ }
416
+ resolveContentPath(model, locale) {
417
+ if (model.localization && locale) return this.contentFilePath(model.modelId, locale);
418
+ if (model.localization && !locale) return this.contentFilePath(model.modelId, model.modelId);
419
+ return this.contentFilePath(model.modelId);
420
+ }
421
+ async createLocalized(model, entry, locale, content) {
422
+ if (locale) await this.appendEntry(model, entry, locale, content);
423
+ else {
424
+ const locales = await this.getLocales(model.modelId);
425
+ if (locales.length === 0) throw new Error(`Model "${model.modelId}" is localized but no locale files exist. Specify a locale (e.g., locale: "en") to create the first entry.`);
426
+ for (const loc of locales) await this.appendEntry(model, entry, loc, content);
427
+ }
428
+ }
429
+ async appendEntry(model, entry, locale, content) {
430
+ const filePath = this.resolveContentPath(model, locale);
431
+ await ensureDir(join(filePath, ".."));
432
+ const entries = await readJsonFile(filePath);
433
+ if (entries.some((e) => e.ID === entry.ID)) throw new Error(`Duplicate ID: ${entry.ID} already exists in ${model.modelId}`);
434
+ entries.push(entry);
435
+ await writeJsonFile(filePath, entries);
436
+ if ((model.type === "MD" || model.type === "MDX") && "slug" in entry) await this.markdownSync.write(model, entry, content || "", locale);
437
+ }
438
+ async deleteFromFile(model, entryId, locale) {
439
+ const filePath = this.resolveContentPath(model, locale);
440
+ const entries = await readJsonFile(filePath);
441
+ const entry = entries.find((e) => e.ID === entryId);
442
+ if (!entry) return;
443
+ await writeJsonFile(filePath, entries.filter((e) => e.ID !== entryId));
444
+ if ((model.type === "MD" || model.type === "MDX") && "slug" in entry) await this.markdownSync.delete(model, entry, locale);
445
+ }
446
+ };
447
+ //#endregion
448
+ //#region src/core/asset/manager.ts
449
+ var AssetManager = class {
450
+ assetsPath;
451
+ constructor(basePath, repoPath, config) {
452
+ this.basePath = basePath;
453
+ this.repoPath = repoPath;
454
+ this.config = config;
455
+ this.assetsPath = join(basePath, "assets.json");
456
+ }
457
+ async list() {
458
+ return readJsonFile(this.assetsPath);
459
+ }
460
+ async get(assetPath) {
461
+ return (await this.list()).find((a) => a.path === assetPath);
462
+ }
463
+ async register(input) {
464
+ const fullPath = join(this.repoPath, input.path);
465
+ if (!await fileExists(fullPath)) throw new Error(`Asset file does not exist at: ${input.path}`);
466
+ const assets = await this.list();
467
+ if (assets.some((a) => a.path === input.path)) throw new Error(`Asset already registered: ${input.path}`);
468
+ const stats = await stat(fullPath);
469
+ const now = (/* @__PURE__ */ new Date()).toISOString();
470
+ const entry = {
471
+ path: input.path,
472
+ mimetype: input.mimetype,
473
+ size: stats.size,
474
+ alt: input.alt || "",
475
+ meta: {
476
+ user: {
477
+ name: this.config.author?.name || "AI Agent",
478
+ email: this.config.author?.email || "agent@contentrain.io"
479
+ },
480
+ createdAt: now,
481
+ updatedAt: now
482
+ }
483
+ };
484
+ assets.push(entry);
485
+ await writeJsonFile(this.assetsPath, assets);
486
+ return entry;
487
+ }
488
+ async deregister(assetPath) {
489
+ const assets = await this.list();
490
+ const filtered = assets.filter((a) => a.path !== assetPath);
491
+ if (filtered.length === assets.length) throw new AssetNotFoundError(assetPath);
492
+ await writeJsonFile(this.assetsPath, filtered);
493
+ }
494
+ async update(assetPath, updates) {
495
+ const assets = await this.list();
496
+ const index = assets.findIndex((a) => a.path === assetPath);
497
+ if (index === -1) throw new AssetNotFoundError(assetPath);
498
+ if (updates.alt !== void 0) assets[index].alt = updates.alt;
499
+ if (updates.mimetype !== void 0) assets[index].mimetype = updates.mimetype;
500
+ if (assets[index].meta) assets[index].meta.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
501
+ await writeJsonFile(this.assetsPath, assets);
502
+ return assets[index];
503
+ }
504
+ };
505
+ //#endregion
506
+ //#region src/core/validation/rules.ts
507
+ const VALID_STATUSES = [
508
+ "draft",
509
+ "publish",
510
+ "changed"
511
+ ];
512
+ /**
513
+ * Map componentId to expected runtime JS type.
514
+ */
515
+ function getExpectedType(componentId, fieldType) {
516
+ switch (componentId) {
517
+ case "single-line-text":
518
+ case "multi-line-text":
519
+ case "email":
520
+ case "url":
521
+ case "slug":
522
+ case "color":
523
+ case "json":
524
+ case "md-editor":
525
+ case "rich-text-editor":
526
+ case "phone-number": return "string";
527
+ case "integer":
528
+ case "decimal":
529
+ case "rating":
530
+ case "percent": return "number";
531
+ case "checkbox":
532
+ case "switch": return "boolean";
533
+ case "date":
534
+ case "date-time": return "string";
535
+ case "media": return "string";
536
+ case "one-to-one": return "string";
537
+ case "one-to-many": return "array";
538
+ default: return fieldType === "array" ? "array" : "string";
539
+ }
540
+ }
541
+ /**
542
+ * Validate an ID matches Contentrain format (12-char lowercase hex).
543
+ */
544
+ function validateId(id) {
545
+ if (typeof id !== "string") return "ID must be a string";
546
+ if (!isValidId(id)) return "ID must be 12-character lowercase hexadecimal";
547
+ return null;
548
+ }
549
+ /**
550
+ * Validate a status value.
551
+ */
552
+ function validateStatus(status) {
553
+ if (typeof status !== "string") return "status must be a string";
554
+ if (!VALID_STATUSES.includes(status)) return `status must be one of: ${VALID_STATUSES.join(", ")}`;
555
+ return null;
556
+ }
557
+ /**
558
+ * Validate a value matches the expected runtime type.
559
+ */
560
+ function validateFieldValue(value, expectedType, fieldId) {
561
+ if (value === null || value === void 0) return null;
562
+ switch (expectedType) {
563
+ case "string":
564
+ if (typeof value !== "string") return `${fieldId} must be a string`;
565
+ break;
566
+ case "number":
567
+ if (typeof value !== "number") return `${fieldId} must be a number`;
568
+ break;
569
+ case "boolean":
570
+ if (typeof value !== "boolean") return `${fieldId} must be a boolean`;
571
+ break;
572
+ case "array":
573
+ if (!Array.isArray(value)) return `${fieldId} must be an array`;
574
+ break;
575
+ }
576
+ return null;
577
+ }
578
+ /**
579
+ * Validate integer specifically.
580
+ */
581
+ function validateInteger(value, fieldId) {
582
+ if (typeof value === "number" && !Number.isInteger(value)) return `${fieldId} must be an integer`;
583
+ return null;
584
+ }
585
+ //#endregion
586
+ //#region src/core/validation/validator.ts
587
+ var Validator = class {
588
+ modelManager;
589
+ constructor(basePath) {
590
+ this.basePath = basePath;
591
+ this.modelManager = new ModelManager(basePath);
592
+ }
593
+ /**
594
+ * Validate content data against model field definitions.
595
+ */
596
+ async validate(modelId, data, options) {
597
+ const errors = [];
598
+ const { fields, model } = await this.modelManager.describe(modelId);
599
+ const nonSystemFields = fields.filter((f) => !f.system);
600
+ for (const field of nonSystemFields) {
601
+ const value = data[field.fieldId];
602
+ if (field.validations?.["required-field"]?.value) {
603
+ if (!options?.isUpdate && (value === void 0 || value === null || value === "")) {
604
+ if (field.fieldId === "content" && (model.type === "MD" || model.type === "MDX")) continue;
605
+ errors.push({
606
+ fieldId: field.fieldId,
607
+ message: `${field.name} is required`,
608
+ rule: "required-field"
609
+ });
610
+ continue;
611
+ }
612
+ }
613
+ if (value === void 0 || value === null) continue;
614
+ const typeError = validateFieldValue(value, getExpectedType(field.componentId, field.fieldType), field.fieldId);
615
+ if (typeError) {
616
+ errors.push({
617
+ fieldId: field.fieldId,
618
+ message: typeError,
619
+ rule: "type-check"
620
+ });
621
+ continue;
622
+ }
623
+ if (field.componentId === "integer") {
624
+ const intError = validateInteger(value, field.fieldId);
625
+ if (intError) errors.push({
626
+ fieldId: field.fieldId,
627
+ message: intError,
628
+ rule: "integer-check"
629
+ });
630
+ }
631
+ if (field.componentId === "one-to-one" && typeof value === "string") {
632
+ const refModel = field.options?.reference?.form?.reference?.value;
633
+ if (refModel) {
634
+ const integrityError = await this.checkRelationIntegrity(refModel, value);
635
+ if (integrityError) errors.push({
636
+ fieldId: field.fieldId,
637
+ message: integrityError,
638
+ rule: "relation-integrity"
639
+ });
640
+ }
641
+ }
642
+ if (field.componentId === "one-to-many" && Array.isArray(value)) {
643
+ const refModel = field.options?.reference?.form?.reference?.value;
644
+ if (refModel) {
645
+ for (const refId of value) if (typeof refId === "string") {
646
+ const integrityError = await this.checkRelationIntegrity(refModel, refId);
647
+ if (integrityError) errors.push({
648
+ fieldId: field.fieldId,
649
+ message: integrityError,
650
+ rule: "relation-integrity"
651
+ });
652
+ }
653
+ }
654
+ }
655
+ if (field.componentId === "media" && typeof value === "string" && value !== "") {
656
+ const assetError = await this.checkAssetExists(value);
657
+ if (assetError) errors.push({
658
+ fieldId: field.fieldId,
659
+ message: assetError,
660
+ rule: "asset-exists"
661
+ });
662
+ }
663
+ }
664
+ if (!options?.isUpdate) {
665
+ const uniqueFields = nonSystemFields.filter((f) => f.validations?.["unique-field"]?.value);
666
+ for (const field of uniqueFields) {
667
+ const value = data[field.fieldId];
668
+ if (value === void 0 || value === null) continue;
669
+ const uniqueError = await this.checkUniqueness(modelId, field.fieldId, value);
670
+ if (uniqueError) errors.push({
671
+ fieldId: field.fieldId,
672
+ message: uniqueError,
673
+ rule: "unique-field"
674
+ });
675
+ }
676
+ }
677
+ return {
678
+ valid: errors.length === 0,
679
+ errors
680
+ };
681
+ }
682
+ /**
683
+ * Validate ID format.
684
+ */
685
+ validateId(id) {
686
+ const error = validateId(id);
687
+ if (error) return {
688
+ valid: false,
689
+ errors: [{
690
+ fieldId: "ID",
691
+ message: error,
692
+ rule: "id-format"
693
+ }]
694
+ };
695
+ return {
696
+ valid: true,
697
+ errors: []
698
+ };
699
+ }
700
+ /**
701
+ * Validate status value.
702
+ */
703
+ validateStatus(status) {
704
+ const error = validateStatus(status);
705
+ if (error) return {
706
+ valid: false,
707
+ errors: [{
708
+ fieldId: "status",
709
+ message: error,
710
+ rule: "status-value"
711
+ }]
712
+ };
713
+ return {
714
+ valid: true,
715
+ errors: []
716
+ };
717
+ }
718
+ async checkRelationIntegrity(refModelId, refEntryId) {
719
+ try {
720
+ await this.modelManager.get(refModelId);
721
+ const contentDir = join(this.basePath, refModelId);
722
+ const { listJsonFiles } = await import("./fs-D83-Ii_y.mjs").then((n) => n.r);
723
+ const files = await listJsonFiles(contentDir);
724
+ for (const file of files) if ((await readJsonFile(join(contentDir, `${file}.json`))).some((e) => e.ID === refEntryId)) return null;
725
+ return `Referenced entry ${refEntryId} not found in model ${refModelId}`;
726
+ } catch {
727
+ return `Referenced model ${refModelId} not found`;
728
+ }
729
+ }
730
+ async checkAssetExists(assetPath) {
731
+ try {
732
+ if ((await readJsonFile(join(this.basePath, "assets.json"))).some((a) => a.path === assetPath)) return null;
733
+ return `Asset not found in registry: ${assetPath}`;
734
+ } catch {
735
+ return `Could not read assets.json`;
736
+ }
737
+ }
738
+ async checkUniqueness(modelId, fieldId, value) {
739
+ try {
740
+ const contentDir = join(this.basePath, modelId);
741
+ const { listJsonFiles } = await import("./fs-D83-Ii_y.mjs").then((n) => n.r);
742
+ const files = await listJsonFiles(contentDir);
743
+ for (const file of files) if ((await readJsonFile(join(contentDir, `${file}.json`))).some((e) => e[fieldId] === value)) return `${fieldId} value "${value}" already exists — must be unique`;
744
+ return null;
745
+ } catch {
746
+ return null;
747
+ }
748
+ }
749
+ };
750
+ //#endregion
751
+ //#region src/core/git/merge.ts
752
+ /**
753
+ * Three-way structural merge for JSON arrays indexed by ID.
754
+ *
755
+ * Strategy:
756
+ * - New entries (in ours but not base): APPEND to result
757
+ * - Deleted entries (in base but not in ours): REMOVE from result
758
+ * - Modified entries (same ID, different fields): apply our field-level changes over theirs
759
+ * - Entries only in theirs (added by another writer): KEEP
760
+ */
761
+ function structuralMerge(base, ours, theirs) {
762
+ const baseMap = indexById(base);
763
+ const oursMap = indexById(ours);
764
+ const result = [];
765
+ const processedIds = /* @__PURE__ */ new Set();
766
+ for (const theirEntry of theirs) {
767
+ const id = theirEntry.ID;
768
+ processedIds.add(id);
769
+ const baseEntry = baseMap.get(id);
770
+ const ourEntry = oursMap.get(id);
771
+ if (!ourEntry && baseEntry) continue;
772
+ if (ourEntry && baseEntry) result.push(mergeEntry(baseEntry, ourEntry, theirEntry));
773
+ else result.push(theirEntry);
774
+ }
775
+ for (const ourEntry of ours) if (!processedIds.has(ourEntry.ID)) result.push(ourEntry);
776
+ return result;
777
+ }
778
+ /**
779
+ * Merge a single entry using three-way field comparison.
780
+ * Our changes take precedence over theirs when both modified the same field.
781
+ */
782
+ function mergeEntry(base, ours, theirs) {
783
+ const merged = { ...theirs };
784
+ for (const key of Object.keys(ours)) {
785
+ const baseVal = JSON.stringify(base[key]);
786
+ const ourVal = JSON.stringify(ours[key]);
787
+ const theirVal = JSON.stringify(theirs[key]);
788
+ if (ourVal !== baseVal && theirVal === baseVal) merged[key] = ours[key];
789
+ else if (ourVal !== baseVal && theirVal !== baseVal) merged[key] = ours[key];
790
+ }
791
+ return merged;
792
+ }
793
+ function indexById(entries) {
794
+ const map = /* @__PURE__ */ new Map();
795
+ for (const entry of entries) map.set(entry.ID, entry);
796
+ return map;
797
+ }
798
+ //#endregion
799
+ //#region src/core/git/sync.ts
800
+ var GitSyncManager = class {
801
+ config;
802
+ constructor(config) {
803
+ this.config = {
804
+ ...config,
805
+ remote: config.remote || "origin",
806
+ retryAttempts: config.retryAttempts || 3,
807
+ commitPrefix: config.commitPrefix || "[contentrain]"
808
+ };
809
+ }
810
+ /**
811
+ * Create an isolated git worktree for safe operations.
812
+ */
813
+ async createWorktree() {
814
+ const id = randomBytes(4).toString("hex");
815
+ const worktreePath = join(tmpdir(), `contentrain-mcp-${id}`);
816
+ const git = simpleGit(this.config.repoPath);
817
+ try {
818
+ await git.fetch(this.config.remote, this.config.branch);
819
+ const remoteBranch = `${this.config.remote}/${this.config.branch}`;
820
+ const localBranch = `contentrain-work-${id}`;
821
+ await git.raw([
822
+ "worktree",
823
+ "add",
824
+ "-b",
825
+ localBranch,
826
+ worktreePath,
827
+ remoteBranch
828
+ ]);
829
+ return {
830
+ path: worktreePath,
831
+ branch: localBranch,
832
+ id
833
+ };
834
+ } catch (err) {
835
+ throw new GitSyncError(`Failed to create worktree: ${err}`, {
836
+ branch: this.config.branch,
837
+ worktreePath
838
+ });
839
+ }
840
+ }
841
+ /**
842
+ * Commit all changes in the worktree.
843
+ */
844
+ async commit(ctx, message) {
845
+ const git = simpleGit(ctx.path);
846
+ const fullMessage = `${this.config.commitPrefix} ${message}`;
847
+ await git.add("-A");
848
+ if ((await git.status()).files.length === 0) return "";
849
+ const authorArgs = [];
850
+ if (this.config.author) authorArgs.push("--author", `${this.config.author.name} <${this.config.author.email}>`);
851
+ return (await git.commit(fullMessage, void 0, Object.fromEntries(authorArgs.length ? [["--author", `${this.config.author.name} <${this.config.author.email}>`]] : []))).commit;
852
+ }
853
+ /**
854
+ * Push with rebase-retry on conflict.
855
+ */
856
+ async pushWithRetry(ctx) {
857
+ const git = simpleGit(ctx.path);
858
+ const maxAttempts = this.config.retryAttempts;
859
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
860
+ await git.push(this.config.remote, `${ctx.branch}:${this.config.branch}`);
861
+ return;
862
+ } catch {
863
+ if (attempt === maxAttempts) throw new PushRejectedError(true);
864
+ try {
865
+ await this.resolveAndRetry(ctx);
866
+ } catch (mergeErr) {
867
+ if (attempt === maxAttempts) throw new GitSyncError(`Failed to resolve conflicts after ${maxAttempts} attempts`, { originalError: String(mergeErr) });
868
+ }
869
+ }
870
+ }
871
+ /**
872
+ * Cleanup: remove the worktree.
873
+ */
874
+ async cleanup(ctx) {
875
+ try {
876
+ await simpleGit(this.config.repoPath).raw([
877
+ "worktree",
878
+ "remove",
879
+ ctx.path,
880
+ "--force"
881
+ ]);
882
+ } catch {
883
+ await removeDir(ctx.path);
884
+ }
885
+ try {
886
+ await simpleGit(this.config.repoPath).raw([
887
+ "branch",
888
+ "-D",
889
+ ctx.branch
890
+ ]);
891
+ } catch {}
892
+ }
893
+ /**
894
+ * Run a full transaction: worktree → execute → commit → push → cleanup.
895
+ */
896
+ async transaction(fn, message) {
897
+ const ctx = await this.createWorktree();
898
+ try {
899
+ const result = await fn(ctx.path);
900
+ if (await this.commit(ctx, message)) await this.pushWithRetry(ctx);
901
+ return result;
902
+ } finally {
903
+ await this.cleanup(ctx);
904
+ }
905
+ }
906
+ /**
907
+ * Resolve push conflicts via structural JSON merge.
908
+ */
909
+ async resolveAndRetry(ctx) {
910
+ const git = simpleGit(ctx.path);
911
+ const remoteBranch = `${this.config.remote}/${this.config.branch}`;
912
+ await git.fetch(this.config.remote, this.config.branch);
913
+ const baseCommit = (await git.raw([
914
+ "merge-base",
915
+ ctx.branch,
916
+ remoteBranch
917
+ ])).trim();
918
+ const changedFiles = (await git.raw([
919
+ "diff",
920
+ "--name-only",
921
+ `${remoteBranch}...${ctx.branch}`
922
+ ])).trim().split("\n").filter((f) => f.endsWith(".json"));
923
+ for (const file of changedFiles) {
924
+ if (!file.includes("contentrain/") && !file.startsWith("contentrain/")) continue;
925
+ try {
926
+ const basePath = join(ctx.path, file);
927
+ const base = await this.readGitVersion(git, baseCommit, file);
928
+ const ours = await readJsonFile(basePath);
929
+ const theirsRaw = await git.raw(["show", `${remoteBranch}:${file}`]);
930
+ await writeJsonFile(basePath, structuralMerge(base, ours, JSON.parse(theirsRaw)));
931
+ } catch {}
932
+ }
933
+ await git.raw([
934
+ "reset",
935
+ "--soft",
936
+ remoteBranch
937
+ ]);
938
+ await git.add("-A");
939
+ if ((await git.status()).files.length > 0) await git.commit(`${this.config.commitPrefix} merge: resolve concurrent changes`);
940
+ }
941
+ async readGitVersion(git, commit, filePath) {
942
+ try {
943
+ const raw = await git.raw(["show", `${commit}:${filePath}`]);
944
+ return JSON.parse(raw);
945
+ } catch {
946
+ return [];
947
+ }
948
+ }
949
+ };
950
+ //#endregion
951
+ //#region src/core/writer.ts
952
+ /**
953
+ * Main orchestrator — coordinates all managers and git sync.
954
+ *
955
+ * Three modes:
956
+ * 1. Read mode: reads from repoPath directly (no git sync)
957
+ * 2. Transaction mode: creates a worktree, applies changes, commits + pushes
958
+ * 3. Dry-run mode: copies contentrain dir to temp, applies changes there, then discards
959
+ */
960
+ var ContentrainWriter = class {
961
+ config;
962
+ contentrainDir;
963
+ model;
964
+ content;
965
+ asset;
966
+ validator;
967
+ gitSync;
968
+ constructor(config) {
969
+ this.config = config;
970
+ this.contentrainDir = config.contentrainDir || "contentrain";
971
+ const basePath = join(config.repoPath, this.contentrainDir);
972
+ this.model = new ModelManager(basePath);
973
+ this.content = new ContentManager(basePath, config.repoPath);
974
+ this.asset = new AssetManager(basePath, config.repoPath, config);
975
+ this.validator = new Validator(basePath);
976
+ this.gitSync = new GitSyncManager(config);
977
+ }
978
+ /**
979
+ * Execute operations in a git-synced transaction.
980
+ * Creates worktree → runs operations → validates → commits → pushes.
981
+ * In dry-run mode, copies to a temp directory and discards after execution.
982
+ */
983
+ async transaction(fn, options) {
984
+ if (this.config.dryRun) return this.dryRunTransaction(fn);
985
+ return this.gitSync.transaction(async (worktreePath) => {
986
+ return fn(this.createManagers(worktreePath));
987
+ }, options?.message || "content update");
988
+ }
989
+ /**
990
+ * Dry-run: copy contentrain dir to temp, run operations there, then discard.
991
+ * The original repository is never modified.
992
+ */
993
+ async dryRunTransaction(fn) {
994
+ const tempRepoPath = await mkdtemp(join(tmpdir(), "contentrain-dry-"));
995
+ const tempContentrainDir = join(tempRepoPath, this.contentrainDir);
996
+ const sourceContentrainDir = join(this.config.repoPath, this.contentrainDir);
997
+ try {
998
+ await cp(sourceContentrainDir, tempContentrainDir, { recursive: true });
999
+ return await fn(this.createManagers(tempRepoPath));
1000
+ } finally {
1001
+ await removeDir(tempRepoPath);
1002
+ }
1003
+ }
1004
+ /**
1005
+ * Create managers for a specific repo path (used in transactions).
1006
+ */
1007
+ createManagers(repoPath) {
1008
+ const basePath = join(repoPath, this.contentrainDir);
1009
+ return {
1010
+ model: new ModelManager(basePath),
1011
+ content: new ContentManager(basePath, repoPath),
1012
+ asset: new AssetManager(basePath, repoPath, this.config),
1013
+ validator: new Validator(basePath)
1014
+ };
1015
+ }
1016
+ };
1017
+ //#endregion
1018
+ //#region src/tools/model.ts
1019
+ function registerModelTools(server, writer) {
1020
+ server.registerTool("contentrain_list_models", { description: "List all Contentrain models with their metadata (type, localization, etc.)" }, async () => {
1021
+ try {
1022
+ const models = await writer.model.list();
1023
+ return { content: [{
1024
+ type: "text",
1025
+ text: JSON.stringify(models, null, 2)
1026
+ }] };
1027
+ } catch (err) {
1028
+ return {
1029
+ content: [{
1030
+ type: "text",
1031
+ text: `Error: ${err}`
1032
+ }],
1033
+ isError: true
1034
+ };
1035
+ }
1036
+ });
1037
+ server.registerTool("contentrain_describe_model", {
1038
+ description: "Get detailed schema for a model including all field definitions, types, validations, and options. Call this BEFORE creating or updating content to understand required fields.",
1039
+ inputSchema: { modelId: z.string().describe("The model ID to describe") }
1040
+ }, async ({ modelId }) => {
1041
+ try {
1042
+ const desc = await writer.model.describe(modelId);
1043
+ return { content: [{
1044
+ type: "text",
1045
+ text: JSON.stringify(desc, null, 2)
1046
+ }] };
1047
+ } catch (err) {
1048
+ return {
1049
+ content: [{
1050
+ type: "text",
1051
+ text: `Error: ${err}`
1052
+ }],
1053
+ isError: true
1054
+ };
1055
+ }
1056
+ });
1057
+ server.registerTool("contentrain_create_model", {
1058
+ description: "Create a new Contentrain model with field definitions. System fields (ID, createdAt, updatedAt, status) are auto-added. For MD/MDX models, slug and content fields are also auto-added.",
1059
+ inputSchema: {
1060
+ name: z.string().describe("Display name of the model"),
1061
+ modelId: z.string().regex(/^[a-z0-9-]+$/).describe("Unique model ID in kebab-case"),
1062
+ type: z.enum([
1063
+ "JSON",
1064
+ "MD",
1065
+ "MDX"
1066
+ ]).describe("Content type"),
1067
+ localization: z.boolean().describe("Whether the model supports multiple languages"),
1068
+ description: z.string().optional().describe("Model description"),
1069
+ path: z.string().optional().describe("Base path for MD/MDX files"),
1070
+ fields: z.array(z.object({
1071
+ name: z.string(),
1072
+ fieldId: z.string(),
1073
+ componentId: z.string(),
1074
+ fieldType: z.string(),
1075
+ options: z.record(z.unknown()).optional(),
1076
+ validations: z.record(z.unknown()).optional()
1077
+ })).optional().describe("Custom field definitions (system fields are auto-added)")
1078
+ }
1079
+ }, async (params) => {
1080
+ try {
1081
+ const result = await writer.transaction(async (tx) => {
1082
+ return tx.model.create({
1083
+ name: params.name,
1084
+ modelId: params.modelId,
1085
+ type: params.type,
1086
+ localization: params.localization,
1087
+ description: params.description,
1088
+ path: params.path,
1089
+ fields: params.fields
1090
+ });
1091
+ }, { message: `create model: ${params.modelId}` });
1092
+ return { content: [{
1093
+ type: "text",
1094
+ text: JSON.stringify({
1095
+ success: true,
1096
+ model: result
1097
+ }, null, 2)
1098
+ }] };
1099
+ } catch (err) {
1100
+ return {
1101
+ content: [{
1102
+ type: "text",
1103
+ text: `Error: ${err}`
1104
+ }],
1105
+ isError: true
1106
+ };
1107
+ }
1108
+ });
1109
+ server.registerTool("contentrain_add_field", {
1110
+ description: "Add a new field to an existing model.",
1111
+ inputSchema: {
1112
+ modelId: z.string().describe("Target model ID"),
1113
+ name: z.string().describe("Display name of the field"),
1114
+ fieldId: z.string().describe("Unique field identifier"),
1115
+ componentId: z.string().describe("UI component (single-line-text, integer, one-to-one, media, etc.)"),
1116
+ fieldType: z.string().describe("Data type (string, number, boolean, relation, media, date, array)"),
1117
+ options: z.record(z.unknown()).optional().describe("Field options (title-field, default-value, reference, etc.)"),
1118
+ validations: z.record(z.unknown()).optional().describe("Field validations (required-field, unique-field)")
1119
+ }
1120
+ }, async (params) => {
1121
+ try {
1122
+ const result = await writer.transaction(async (tx) => {
1123
+ return tx.model.addField(params.modelId, {
1124
+ name: params.name,
1125
+ fieldId: params.fieldId,
1126
+ componentId: params.componentId,
1127
+ fieldType: params.fieldType,
1128
+ options: params.options || {},
1129
+ validations: params.validations || {}
1130
+ });
1131
+ }, { message: `add field ${params.fieldId} to ${params.modelId}` });
1132
+ return { content: [{
1133
+ type: "text",
1134
+ text: JSON.stringify({
1135
+ success: true,
1136
+ field: result
1137
+ }, null, 2)
1138
+ }] };
1139
+ } catch (err) {
1140
+ return {
1141
+ content: [{
1142
+ type: "text",
1143
+ text: `Error: ${err}`
1144
+ }],
1145
+ isError: true
1146
+ };
1147
+ }
1148
+ });
1149
+ server.registerTool("contentrain_delete_model", {
1150
+ description: "Delete a model and all its content. WARNING: This is destructive and cannot be undone.",
1151
+ annotations: { destructiveHint: true },
1152
+ inputSchema: { modelId: z.string().describe("Model ID to delete") }
1153
+ }, async ({ modelId }) => {
1154
+ try {
1155
+ await writer.transaction(async (tx) => {
1156
+ await tx.model.delete(modelId);
1157
+ }, { message: `delete model: ${modelId}` });
1158
+ return { content: [{
1159
+ type: "text",
1160
+ text: JSON.stringify({
1161
+ success: true,
1162
+ deleted: modelId
1163
+ })
1164
+ }] };
1165
+ } catch (err) {
1166
+ return {
1167
+ content: [{
1168
+ type: "text",
1169
+ text: `Error: ${err}`
1170
+ }],
1171
+ isError: true
1172
+ };
1173
+ }
1174
+ });
1175
+ }
1176
+ //#endregion
1177
+ //#region src/tools/content.ts
1178
+ function registerContentTools(server, writer) {
1179
+ server.registerTool("contentrain_list_content", {
1180
+ description: "List all content entries for a model. For localized models, specify a locale.",
1181
+ annotations: { readOnlyHint: true },
1182
+ inputSchema: {
1183
+ modelId: z.string().describe("Model ID to list content from"),
1184
+ locale: z.string().optional().describe("Locale code (e.g., \"en\", \"tr\") for localized models")
1185
+ }
1186
+ }, async ({ modelId, locale }) => {
1187
+ try {
1188
+ const entries = await writer.content.list(modelId, locale);
1189
+ return { content: [{
1190
+ type: "text",
1191
+ text: JSON.stringify({
1192
+ total: entries.length,
1193
+ entries
1194
+ }, null, 2)
1195
+ }] };
1196
+ } catch (err) {
1197
+ return {
1198
+ content: [{
1199
+ type: "text",
1200
+ text: `Error: ${err}`
1201
+ }],
1202
+ isError: true
1203
+ };
1204
+ }
1205
+ });
1206
+ server.registerTool("contentrain_get_content", {
1207
+ description: "Get a single content entry by ID.",
1208
+ annotations: { readOnlyHint: true },
1209
+ inputSchema: {
1210
+ modelId: z.string().describe("Model ID"),
1211
+ entryId: z.string().describe("Entry ID (12-char hex)"),
1212
+ locale: z.string().optional().describe("Locale code for localized models")
1213
+ }
1214
+ }, async ({ modelId, entryId, locale }) => {
1215
+ try {
1216
+ const entry = await writer.content.get(modelId, entryId, locale);
1217
+ return { content: [{
1218
+ type: "text",
1219
+ text: JSON.stringify(entry, null, 2)
1220
+ }] };
1221
+ } catch (err) {
1222
+ return {
1223
+ content: [{
1224
+ type: "text",
1225
+ text: `Error: ${err}`
1226
+ }],
1227
+ isError: true
1228
+ };
1229
+ }
1230
+ });
1231
+ server.registerTool("contentrain_create_content", {
1232
+ description: "Create a new content entry. System fields (ID, createdAt, updatedAt, status) are auto-generated. For localized models, specify locale to create in that language. Call contentrain_describe_model first to know required fields.",
1233
+ inputSchema: {
1234
+ modelId: z.string().describe("Target model ID"),
1235
+ data: z.record(z.unknown()).describe("Content data object with field values matching model schema"),
1236
+ locale: z.string().optional().describe("Locale code (e.g., \"en\") — required for localized models"),
1237
+ status: z.enum(["draft", "publish"]).optional().describe("Entry status (default: \"draft\")"),
1238
+ content: z.string().optional().describe("Markdown body content (only for MD/MDX models)")
1239
+ }
1240
+ }, async (params) => {
1241
+ try {
1242
+ const result = await writer.transaction(async (tx) => {
1243
+ const validation = await tx.validator.validate(params.modelId, params.data);
1244
+ if (!validation.valid) throw new Error(`Validation failed:\n${validation.errors.map((e) => ` - ${e.fieldId}: ${e.message}`).join("\n")}`);
1245
+ return tx.content.create(params.modelId, params.data, {
1246
+ locale: params.locale,
1247
+ status: params.status,
1248
+ content: params.content
1249
+ });
1250
+ }, { message: `create ${params.modelId} entry` });
1251
+ return { content: [{
1252
+ type: "text",
1253
+ text: JSON.stringify({
1254
+ success: true,
1255
+ id: result
1256
+ }, null, 2)
1257
+ }] };
1258
+ } catch (err) {
1259
+ return {
1260
+ content: [{
1261
+ type: "text",
1262
+ text: `Error: ${err}`
1263
+ }],
1264
+ isError: true
1265
+ };
1266
+ }
1267
+ });
1268
+ server.registerTool("contentrain_update_content", {
1269
+ description: "Update an existing content entry. Only provide fields you want to change. updatedAt is auto-set.",
1270
+ inputSchema: {
1271
+ modelId: z.string().describe("Model ID"),
1272
+ entryId: z.string().describe("Entry ID to update (12-char hex)"),
1273
+ data: z.record(z.unknown()).describe("Fields to update"),
1274
+ locale: z.string().optional().describe("Locale code for localized models"),
1275
+ content: z.string().optional().describe("Updated markdown body (only for MD/MDX models)")
1276
+ }
1277
+ }, async (params) => {
1278
+ try {
1279
+ const result = await writer.transaction(async (tx) => {
1280
+ const validation = await tx.validator.validate(params.modelId, params.data, { isUpdate: true });
1281
+ if (!validation.valid) throw new Error(`Validation failed:\n${validation.errors.map((e) => ` - ${e.fieldId}: ${e.message}`).join("\n")}`);
1282
+ return tx.content.update(params.modelId, params.entryId, params.data, {
1283
+ locale: params.locale,
1284
+ content: params.content
1285
+ });
1286
+ }, { message: `update ${params.modelId}/${params.entryId}` });
1287
+ return { content: [{
1288
+ type: "text",
1289
+ text: JSON.stringify({
1290
+ success: true,
1291
+ entry: result
1292
+ }, null, 2)
1293
+ }] };
1294
+ } catch (err) {
1295
+ return {
1296
+ content: [{
1297
+ type: "text",
1298
+ text: `Error: ${err}`
1299
+ }],
1300
+ isError: true
1301
+ };
1302
+ }
1303
+ });
1304
+ server.registerTool("contentrain_delete_content", {
1305
+ description: "Delete a content entry by ID. For localized models, removes from all locale files. For MD/MDX, also deletes markdown files.",
1306
+ annotations: { destructiveHint: true },
1307
+ inputSchema: {
1308
+ modelId: z.string().describe("Model ID"),
1309
+ entryId: z.string().describe("Entry ID to delete (12-char hex)")
1310
+ }
1311
+ }, async ({ modelId, entryId }) => {
1312
+ try {
1313
+ await writer.transaction(async (tx) => {
1314
+ await tx.content.delete(modelId, entryId);
1315
+ }, { message: `delete ${modelId}/${entryId}` });
1316
+ return { content: [{
1317
+ type: "text",
1318
+ text: JSON.stringify({
1319
+ success: true,
1320
+ deleted: entryId
1321
+ })
1322
+ }] };
1323
+ } catch (err) {
1324
+ return {
1325
+ content: [{
1326
+ type: "text",
1327
+ text: `Error: ${err}`
1328
+ }],
1329
+ isError: true
1330
+ };
1331
+ }
1332
+ });
1333
+ server.registerTool("contentrain_validate", {
1334
+ description: "Validate content data against model schema without writing. Use for dry-run checks.",
1335
+ annotations: { readOnlyHint: true },
1336
+ inputSchema: {
1337
+ modelId: z.string().describe("Model ID to validate against"),
1338
+ data: z.record(z.unknown()).describe("Content data to validate")
1339
+ }
1340
+ }, async ({ modelId, data }) => {
1341
+ try {
1342
+ const result = await writer.validator.validate(modelId, data);
1343
+ return { content: [{
1344
+ type: "text",
1345
+ text: JSON.stringify(result, null, 2)
1346
+ }] };
1347
+ } catch (err) {
1348
+ return {
1349
+ content: [{
1350
+ type: "text",
1351
+ text: `Error: ${err}`
1352
+ }],
1353
+ isError: true
1354
+ };
1355
+ }
1356
+ });
1357
+ }
1358
+ //#endregion
1359
+ //#region src/tools/asset.ts
1360
+ function registerAssetTools(server, writer) {
1361
+ server.registerTool("contentrain_list_assets", {
1362
+ description: "List all registered assets in assets.json.",
1363
+ annotations: { readOnlyHint: true }
1364
+ }, async () => {
1365
+ try {
1366
+ const assets = await writer.asset.list();
1367
+ return { content: [{
1368
+ type: "text",
1369
+ text: JSON.stringify({
1370
+ total: assets.length,
1371
+ assets
1372
+ }, null, 2)
1373
+ }] };
1374
+ } catch (err) {
1375
+ return {
1376
+ content: [{
1377
+ type: "text",
1378
+ text: `Error: ${err}`
1379
+ }],
1380
+ isError: true
1381
+ };
1382
+ }
1383
+ });
1384
+ server.registerTool("contentrain_register_asset", {
1385
+ description: "Register a new asset in assets.json. The file must already exist at the specified path in the repository.",
1386
+ inputSchema: {
1387
+ path: z.string().describe("Relative path to the asset file (e.g., \"contentrain/static/hero.png\")"),
1388
+ mimetype: z.string().describe("MIME type (e.g., \"image/png\", \"image/jpeg\", \"application/pdf\")"),
1389
+ alt: z.string().optional().describe("Alt text for the asset")
1390
+ }
1391
+ }, async (params) => {
1392
+ try {
1393
+ const result = await writer.transaction(async (tx) => {
1394
+ return tx.asset.register({
1395
+ path: params.path,
1396
+ mimetype: params.mimetype,
1397
+ alt: params.alt
1398
+ });
1399
+ }, { message: `register asset: ${params.path}` });
1400
+ return { content: [{
1401
+ type: "text",
1402
+ text: JSON.stringify({
1403
+ success: true,
1404
+ asset: result
1405
+ }, null, 2)
1406
+ }] };
1407
+ } catch (err) {
1408
+ return {
1409
+ content: [{
1410
+ type: "text",
1411
+ text: `Error: ${err}`
1412
+ }],
1413
+ isError: true
1414
+ };
1415
+ }
1416
+ });
1417
+ server.registerTool("contentrain_deregister_asset", {
1418
+ description: "Remove an asset from assets.json registry. Does NOT delete the physical file.",
1419
+ annotations: { destructiveHint: true },
1420
+ inputSchema: { path: z.string().describe("Asset path to deregister") }
1421
+ }, async ({ path }) => {
1422
+ try {
1423
+ await writer.transaction(async (tx) => {
1424
+ await tx.asset.deregister(path);
1425
+ }, { message: `deregister asset: ${path}` });
1426
+ return { content: [{
1427
+ type: "text",
1428
+ text: JSON.stringify({
1429
+ success: true,
1430
+ deregistered: path
1431
+ })
1432
+ }] };
1433
+ } catch (err) {
1434
+ return {
1435
+ content: [{
1436
+ type: "text",
1437
+ text: `Error: ${err}`
1438
+ }],
1439
+ isError: true
1440
+ };
1441
+ }
1442
+ });
1443
+ }
1444
+ //#endregion
1445
+ //#region src/server.ts
1446
+ function createServer(config) {
1447
+ const server = new McpServer({
1448
+ name: "contentrain",
1449
+ version: "0.1.0"
1450
+ });
1451
+ const writer = new ContentrainWriter(config);
1452
+ registerModelTools(server, writer);
1453
+ registerContentTools(server, writer);
1454
+ registerAssetTools(server, writer);
1455
+ return server;
1456
+ }
1457
+ //#endregion
1458
+ //#region src/index.ts
1459
+ const repoPath = process.env.CONTENTRAIN_REPO_PATH || process.cwd();
1460
+ const branch = process.env.CONTENTRAIN_BRANCH || "contentrain";
1461
+ const remote = process.env.CONTENTRAIN_REMOTE || "origin";
1462
+ const contentrainDir = process.env.CONTENTRAIN_DIR || "contentrain";
1463
+ const dryRun = process.env.CONTENTRAIN_DRY_RUN === "true";
1464
+ const authorName = process.env.CONTENTRAIN_AUTHOR_NAME;
1465
+ const authorEmail = process.env.CONTENTRAIN_AUTHOR_EMAIL;
1466
+ const server = createServer({
1467
+ repoPath,
1468
+ branch,
1469
+ remote,
1470
+ contentrainDir,
1471
+ dryRun,
1472
+ author: authorName && authorEmail ? {
1473
+ name: authorName,
1474
+ email: authorEmail
1475
+ } : void 0
1476
+ });
1477
+ async function main() {
1478
+ const transport = new StdioServerTransport();
1479
+ await server.connect(transport);
1480
+ }
1481
+ main().catch((err) => {
1482
+ console.error("Failed to start Contentrain MCP server:", err);
1483
+ process.exit(1);
1484
+ });
1485
+ //#endregion
1486
+ export { ContentrainWriter, createServer };
1487
+
1488
+ //# sourceMappingURL=index.mjs.map