@kidecms/core 0.16.3 → 0.17.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.
- package/admin/components/BlockEditor.tsx +8 -2
- package/admin/components/ContentEditor.tsx +64 -32
- package/admin/components/RichTextEditor.tsx +11 -0
- package/admin/components/UnsavedGuard.tsx +12 -0
- package/admin/components/block-fields.tsx +8 -1
- package/admin/components/ui/command.tsx +1 -1
- package/client/preview.ts +5 -0
- package/internals/integration.ts +42 -21
- package/internals/mcp-worker-boot.mjs +6 -0
- package/internals/mcp-worker.ts +201 -0
- package/internals/mcp.ts +163 -151
- package/package.json +1 -1
|
@@ -302,10 +302,16 @@ export default function BlockEditor({
|
|
|
302
302
|
}
|
|
303
303
|
}, []);
|
|
304
304
|
|
|
305
|
-
// Live preview: broadcast block data for server-side rendering
|
|
305
|
+
// Live preview: broadcast block data for server-side rendering. Also replay the
|
|
306
|
+
// current value when a preview tab opened after edits announces itself.
|
|
306
307
|
useEffect(() => {
|
|
307
308
|
if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
|
|
308
|
-
previewChannelRef.current
|
|
309
|
+
const channel = previewChannelRef.current;
|
|
310
|
+
const broadcast = () => channel.postMessage({ field: name, value: serializeBlocks(blocks), render: "blocks" });
|
|
311
|
+
broadcast();
|
|
312
|
+
channel.onmessage = (e: MessageEvent) => {
|
|
313
|
+
if (e.data?.type === "preview-ready") broadcast();
|
|
314
|
+
};
|
|
309
315
|
}, [blocks, name]);
|
|
310
316
|
|
|
311
317
|
const updateBlocks = useCallback(
|
|
@@ -66,16 +66,22 @@ const contentToTiptap = (doc: ContentDocument | null | undefined): any => {
|
|
|
66
66
|
return { type: "doc", content: content.length > 0 ? content : [{ type: "paragraph" }] };
|
|
67
67
|
};
|
|
68
68
|
|
|
69
|
-
const
|
|
70
|
-
type
|
|
71
|
-
|
|
69
|
+
const isEmptyParagraph = (node: ContentNode | undefined) =>
|
|
70
|
+
node?.type === "paragraph" && !(node as { children?: unknown[] }).children?.length;
|
|
71
|
+
|
|
72
|
+
const tiptapToContent = (json: any): ContentDocument => {
|
|
73
|
+
const children: ContentNode[] = (json.content ?? [])
|
|
72
74
|
.map((node: any): ContentNode | null =>
|
|
73
75
|
node.type === BLOCK_NODE_NAME
|
|
74
76
|
? { type: "block", blockType: node.attrs?.blockType ?? "", fields: node.attrs?.fields ?? {} }
|
|
75
77
|
: (tiptapNodeToCms(node) as ContentNode | null),
|
|
76
78
|
)
|
|
77
|
-
.filter(Boolean)
|
|
78
|
-
|
|
79
|
+
.filter(Boolean);
|
|
80
|
+
// The editor keeps a paragraph after a trailing block so the cursor can get
|
|
81
|
+
// there — don't store it; it would render as visible empty space.
|
|
82
|
+
while (isEmptyParagraph(children[children.length - 1])) children.pop();
|
|
83
|
+
return { type: "root", children };
|
|
84
|
+
};
|
|
79
85
|
|
|
80
86
|
// -----------------------------------------------
|
|
81
87
|
// Inline block node view
|
|
@@ -87,7 +93,7 @@ function isBlankFieldValue(value: unknown): boolean {
|
|
|
87
93
|
}
|
|
88
94
|
|
|
89
95
|
function BlockNodeView(props: NodeViewProps) {
|
|
90
|
-
const { node, updateAttributes, deleteNode, extension
|
|
96
|
+
const { node, updateAttributes, deleteNode, extension } = props;
|
|
91
97
|
const options = extension.options as BlockNodeOptions;
|
|
92
98
|
const blockType = String(node.attrs.blockType ?? "");
|
|
93
99
|
const fields = (node.attrs.fields ?? {}) as Record<string, unknown>;
|
|
@@ -172,40 +178,48 @@ function BlockNodeView(props: NodeViewProps) {
|
|
|
172
178
|
})();
|
|
173
179
|
|
|
174
180
|
return (
|
|
175
|
-
<NodeViewWrapper
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
181
|
+
<NodeViewWrapper className="bg-card my-3 overflow-hidden rounded-lg border">
|
|
182
|
+
{/* Header — entire row is clickable to expand/collapse, same as BlockEditor */}
|
|
183
|
+
<div
|
|
184
|
+
className="group/row bg-muted-strong/50 hover:bg-muted-strong/70 flex items-center gap-2 px-3 py-2 transition-colors select-none"
|
|
185
|
+
contentEditable={false}
|
|
186
|
+
onClick={() => setExpanded((v) => !v)}
|
|
187
|
+
>
|
|
179
188
|
<span
|
|
180
189
|
data-drag-handle
|
|
181
190
|
draggable="true"
|
|
182
191
|
className="text-muted-foreground/50 hover:text-muted-foreground -ml-1 cursor-grab rounded p-1 transition-colors active:cursor-grabbing"
|
|
183
192
|
title="Drag to reorder"
|
|
193
|
+
onClick={(e) => e.stopPropagation()}
|
|
184
194
|
>
|
|
185
195
|
<GripVertical className="size-4" />
|
|
186
196
|
</span>
|
|
187
197
|
|
|
188
|
-
<
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
/>
|
|
195
|
-
<span
|
|
196
|
-
className={cn(
|
|
197
|
-
"rounded px-2 py-0.5 text-xs font-medium",
|
|
198
|
-
isShared
|
|
199
|
-
? "bg-primary/10 text-primary border-primary/20 border"
|
|
200
|
-
: "bg-secondary text-secondary-foreground",
|
|
201
|
-
)}
|
|
202
|
-
>
|
|
203
|
-
{isShared ? "Shared" : humanize(blockType)}
|
|
204
|
-
</span>
|
|
205
|
-
{isShared && sharedType && <span className="text-foreground/70 text-xs">{humanize(sharedType)}</span>}
|
|
206
|
-
</button>
|
|
198
|
+
<ChevronRight
|
|
199
|
+
className={cn(
|
|
200
|
+
"text-muted-foreground group-hover/row:text-foreground/70 size-4 shrink-0 transition-[color,transform]",
|
|
201
|
+
expanded && "rotate-90",
|
|
202
|
+
)}
|
|
203
|
+
/>
|
|
207
204
|
|
|
208
|
-
|
|
205
|
+
<span
|
|
206
|
+
className={cn(
|
|
207
|
+
"rounded px-2 py-0.5 text-xs font-medium",
|
|
208
|
+
isShared
|
|
209
|
+
? "bg-primary/10 text-primary border-primary/20 border"
|
|
210
|
+
: "bg-card text-secondary-foreground border",
|
|
211
|
+
)}
|
|
212
|
+
>
|
|
213
|
+
{isShared ? "Shared" : humanize(blockType)}
|
|
214
|
+
</span>
|
|
215
|
+
|
|
216
|
+
{isShared && sharedType && <span className="text-foreground/70 text-xs">{humanize(sharedType)}</span>}
|
|
217
|
+
|
|
218
|
+
{!expanded && preview && (
|
|
219
|
+
<span className="text-foreground/70 group-hover/row:text-foreground/85 min-w-0 truncate text-sm transition-colors">
|
|
220
|
+
{preview}
|
|
221
|
+
</span>
|
|
222
|
+
)}
|
|
209
223
|
|
|
210
224
|
<div className="ml-auto flex shrink-0 items-center">
|
|
211
225
|
<Button
|
|
@@ -214,7 +228,11 @@ function BlockNodeView(props: NodeViewProps) {
|
|
|
214
228
|
size="icon"
|
|
215
229
|
title={isShared ? "Detach shared section" : "Save as shared section"}
|
|
216
230
|
className="text-muted-foreground hover:text-foreground size-7"
|
|
217
|
-
onClick={() =>
|
|
231
|
+
onClick={(e) => {
|
|
232
|
+
e.stopPropagation();
|
|
233
|
+
if (isShared) detach();
|
|
234
|
+
else openSaveDialog();
|
|
235
|
+
}}
|
|
218
236
|
>
|
|
219
237
|
{isShared ? <Unlink className="size-3.5" /> : <Save className="size-3.5" />}
|
|
220
238
|
</Button>
|
|
@@ -224,7 +242,10 @@ function BlockNodeView(props: NodeViewProps) {
|
|
|
224
242
|
size="icon"
|
|
225
243
|
title="Remove block"
|
|
226
244
|
className="text-muted-foreground hover:text-destructive size-7"
|
|
227
|
-
onClick={() =>
|
|
245
|
+
onClick={(e) => {
|
|
246
|
+
e.stopPropagation();
|
|
247
|
+
deleteNode();
|
|
248
|
+
}}
|
|
228
249
|
>
|
|
229
250
|
<Trash2 className="size-3.5" />
|
|
230
251
|
</Button>
|
|
@@ -422,6 +443,17 @@ export default function ContentEditor({
|
|
|
422
443
|
}
|
|
423
444
|
}, [cmsJson]);
|
|
424
445
|
|
|
446
|
+
// Replay the current value when a preview tab opened after edits announces itself
|
|
447
|
+
useEffect(() => {
|
|
448
|
+
if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
|
|
449
|
+
const channel = previewChannelRef.current;
|
|
450
|
+
channel.onmessage = (e: MessageEvent) => {
|
|
451
|
+
if (e.data?.type === "preview-ready") {
|
|
452
|
+
channel.postMessage({ field: name, value: cmsJson, render: "content" });
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
}, [cmsJson, name]);
|
|
456
|
+
|
|
425
457
|
const editor = useEditor({
|
|
426
458
|
immediatelyRender: false,
|
|
427
459
|
extensions: [
|
|
@@ -432,6 +432,17 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
|
|
|
432
432
|
}
|
|
433
433
|
}, [cmsJson]);
|
|
434
434
|
|
|
435
|
+
// Replay the current value when a preview tab opened after edits announces itself
|
|
436
|
+
useEffect(() => {
|
|
437
|
+
if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
|
|
438
|
+
const channel = previewChannelRef.current;
|
|
439
|
+
channel.onmessage = (e: MessageEvent) => {
|
|
440
|
+
if (e.data?.type === "preview-ready") {
|
|
441
|
+
channel.postMessage({ field: name, value: cmsJson, render: "richText" });
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
}, [cmsJson, name]);
|
|
445
|
+
|
|
435
446
|
const editor = useEditor({
|
|
436
447
|
immediatelyRender: false,
|
|
437
448
|
extensions: [
|
|
@@ -77,6 +77,18 @@ export default function UnsavedGuard({
|
|
|
77
77
|
previewChannel.postMessage({ field: target.name, value: target.value });
|
|
78
78
|
};
|
|
79
79
|
|
|
80
|
+
// A preview tab opened after edits were made announces itself; replay the
|
|
81
|
+
// current value of every simple field so it doesn't miss unsaved changes.
|
|
82
|
+
previewChannel.onmessage = (e: MessageEvent) => {
|
|
83
|
+
if (e.data?.type !== "preview-ready") return;
|
|
84
|
+
for (const el of Array.from(form.elements)) {
|
|
85
|
+
const input = el as HTMLInputElement;
|
|
86
|
+
if (!input.name || input.name.startsWith("_") || input.name === "redirectTo") continue;
|
|
87
|
+
if (input.type === "hidden" || input.type === "submit" || input.type === "button") continue;
|
|
88
|
+
previewChannel.postMessage({ field: input.name, value: input.value });
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
80
92
|
form.addEventListener("input", checkDirty);
|
|
81
93
|
form.addEventListener("input", broadcastField);
|
|
82
94
|
form.addEventListener("change", checkDirty);
|
|
@@ -616,8 +616,15 @@ export function RepeaterField({
|
|
|
616
616
|
});
|
|
617
617
|
});
|
|
618
618
|
|
|
619
|
+
// `_key` is editor-internal — never include it in the emitted value, and don't
|
|
620
|
+
// emit on mount (the initial value came from the form; re-emitting would mark it dirty).
|
|
621
|
+
const mountedRef = useRef(false);
|
|
619
622
|
useEffect(() => {
|
|
620
|
-
|
|
623
|
+
if (!mountedRef.current) {
|
|
624
|
+
mountedRef.current = true;
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
onChange(items.map(({ _key, ...rest }) => rest));
|
|
621
628
|
}, [items]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
622
629
|
|
|
623
630
|
// Typed rows use the declared itemFields; legacy rows auto-detect string keys.
|
|
@@ -77,7 +77,7 @@ function CommandItem({ className, ...props }: React.ComponentProps<typeof Comman
|
|
|
77
77
|
<CommandPrimitive.Item
|
|
78
78
|
data-slot="command-item"
|
|
79
79
|
className={cn(
|
|
80
|
-
"data-[selected=true]:bg-
|
|
80
|
+
"data-[selected=true]:bg-muted-strong/70 data-[selected=true]:text-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
|
81
81
|
className,
|
|
82
82
|
)}
|
|
83
83
|
{...props}
|
package/client/preview.ts
CHANGED
|
@@ -9,6 +9,7 @@ if (new URLSearchParams(location.search).has("preview")) {
|
|
|
9
9
|
location.reload();
|
|
10
10
|
return;
|
|
11
11
|
}
|
|
12
|
+
if (!d.field) return;
|
|
12
13
|
|
|
13
14
|
const els = document.querySelectorAll<HTMLElement>(`[data-cms="${d.field}"]`);
|
|
14
15
|
if (!els.length) return;
|
|
@@ -32,6 +33,10 @@ if (new URLSearchParams(location.search).has("preview")) {
|
|
|
32
33
|
els.forEach((el) => (el.textContent = d.value));
|
|
33
34
|
}
|
|
34
35
|
};
|
|
36
|
+
|
|
37
|
+
// Ask any open admin tab to replay its current (possibly unsaved) field values,
|
|
38
|
+
// so a preview opened after edits were made still shows them.
|
|
39
|
+
ch.postMessage({ type: "preview-ready" });
|
|
35
40
|
}
|
|
36
41
|
|
|
37
42
|
// --- Edit bar: "Edit this page" chip on public pages for logged-in editors ---
|
package/internals/integration.ts
CHANGED
|
@@ -429,30 +429,44 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
|
|
|
429
429
|
}
|
|
430
430
|
|
|
431
431
|
const configFilePath = path.join(root, configPath.replace(/\/?$/, ".ts"));
|
|
432
|
+
const collectionsDir = path.join(path.dirname(configFilePath), "collections");
|
|
432
433
|
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
|
433
|
-
// macOS fs.watch
|
|
434
|
-
//
|
|
435
|
-
//
|
|
436
|
-
//
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
} catch {
|
|
441
|
-
/* watch still registers; first event will populate it */
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
watch(configFilePath, () => {
|
|
445
|
-
if (debounceTimer) clearTimeout(debounceTimer);
|
|
446
|
-
debounceTimer = setTimeout(() => {
|
|
447
|
-
let content: string;
|
|
434
|
+
// macOS fs.watch also fires for sibling writes in the same directory
|
|
435
|
+
// tree — including the generator's own .generated/* output, which
|
|
436
|
+
// would loop regeneration forever. Only act when the content of a
|
|
437
|
+
// watched schema file actually changed.
|
|
438
|
+
const readSchemaFiles = () => {
|
|
439
|
+
const contents = new Map<string, string>();
|
|
440
|
+
const record = (filePath: string) => {
|
|
448
441
|
try {
|
|
449
|
-
|
|
442
|
+
contents.set(filePath, readFileSync(filePath, "utf-8"));
|
|
450
443
|
} catch {
|
|
451
|
-
|
|
444
|
+
/* deleted or unreadable — absence is the recorded state */
|
|
452
445
|
}
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
446
|
+
};
|
|
447
|
+
record(configFilePath);
|
|
448
|
+
let collectionFiles: string[] = [];
|
|
449
|
+
try {
|
|
450
|
+
collectionFiles = readdirSync(collectionsDir);
|
|
451
|
+
} catch {
|
|
452
|
+
/* no collections directory */
|
|
453
|
+
}
|
|
454
|
+
for (const name of collectionFiles) {
|
|
455
|
+
if (name.endsWith(".ts")) record(path.join(collectionsDir, name));
|
|
456
|
+
}
|
|
457
|
+
return contents;
|
|
458
|
+
};
|
|
459
|
+
const sameContents = (a: Map<string, string>, b: Map<string, string>) =>
|
|
460
|
+
a.size === b.size && [...a].every(([key, value]) => b.get(key) === value);
|
|
461
|
+
let lastSchemaContents = readSchemaFiles();
|
|
462
|
+
|
|
463
|
+
const onSchemaFileEvent = () => {
|
|
464
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
465
|
+
debounceTimer = setTimeout(() => {
|
|
466
|
+
const contents = readSchemaFiles();
|
|
467
|
+
if (sameContents(lastSchemaContents, contents)) return;
|
|
468
|
+
lastSchemaContents = contents;
|
|
469
|
+
console.log(" [cms] Schema changed, regenerating...");
|
|
456
470
|
try {
|
|
457
471
|
runScript(root, generatorPath);
|
|
458
472
|
pushSchema(root, useD1);
|
|
@@ -461,7 +475,14 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
|
|
|
461
475
|
console.error(" [cms] Regeneration failed:", (error as Error).message);
|
|
462
476
|
}
|
|
463
477
|
}, 500);
|
|
464
|
-
}
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
watch(configFilePath, onSchemaFileEvent);
|
|
481
|
+
try {
|
|
482
|
+
watch(collectionsDir, onSchemaFileEvent);
|
|
483
|
+
} catch {
|
|
484
|
+
/* no collections directory — the config watch still covers registrations */
|
|
485
|
+
}
|
|
465
486
|
}
|
|
466
487
|
},
|
|
467
488
|
"astro:server:start": ({ address }) => {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Bootstraps the MCP worker child process: registers tsx, then imports the
|
|
2
|
+
// TypeScript worker — same pattern as cli.mjs, works in embedded and package mode.
|
|
3
|
+
import { register } from "tsx/esm/api";
|
|
4
|
+
|
|
5
|
+
register();
|
|
6
|
+
await import(new URL("./mcp-worker.ts", import.meta.url).href);
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child-process half of the MCP server (see mcp.ts). Loads the project modules
|
|
3
|
+
* (cms.config, generated API, adapters) and executes named ops against them.
|
|
4
|
+
* mcp.ts respawns this process when the schema changes on disk — a fresh
|
|
5
|
+
* process gets a fresh ESM module registry, which is what makes hot-reload
|
|
6
|
+
* possible.
|
|
7
|
+
*/
|
|
8
|
+
import { assets, closeDb, describeModel, folders } from "../core";
|
|
9
|
+
import type { CollectionConfig } from "../core";
|
|
10
|
+
import { loadGeneratedApi, loadProjectConfig } from "./project";
|
|
11
|
+
|
|
12
|
+
if (!process.send) throw new Error("mcp-worker.ts must be forked with an IPC channel by mcp.ts");
|
|
13
|
+
const sendToParent = process.send.bind(process);
|
|
14
|
+
|
|
15
|
+
const { cms } = await loadGeneratedApi();
|
|
16
|
+
const config = await loadProjectConfig();
|
|
17
|
+
|
|
18
|
+
const cmsRuntime = cms as Record<string, any> & { meta: typeof cms.meta };
|
|
19
|
+
const model = describeModel(config);
|
|
20
|
+
|
|
21
|
+
const actor = {
|
|
22
|
+
id: process.env.KIDE_MCP_USER_ID || "mcp-local",
|
|
23
|
+
role: process.env.KIDE_MCP_USER_ROLE || "admin",
|
|
24
|
+
email: process.env.KIDE_MCP_USER_EMAIL || "mcp@local",
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const runtimeContext = () => ({ user: actor });
|
|
28
|
+
|
|
29
|
+
const getCollection = (slug: string): CollectionConfig => {
|
|
30
|
+
const collection = config.collections.find((entry) => entry.slug === slug);
|
|
31
|
+
if (!collection) {
|
|
32
|
+
const available = config.collections.map((entry) => entry.slug).join(", ");
|
|
33
|
+
throw new Error(`Unknown collection "${slug}". Available collections: ${available}`);
|
|
34
|
+
}
|
|
35
|
+
return collection;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const getCollectionApi = (slug: string) => {
|
|
39
|
+
getCollection(slug);
|
|
40
|
+
const collectionApi = cmsRuntime[slug];
|
|
41
|
+
if (!collectionApi) throw new Error(`No API found for collection "${slug}".`);
|
|
42
|
+
return collectionApi;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const ensureMutableCollection = (collection: CollectionConfig) => {
|
|
46
|
+
if (collection.auth && process.env.KIDE_MCP_ALLOW_AUTH_COLLECTIONS !== "true") {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`Collection "${collection.slug}" is an auth collection. Set KIDE_MCP_ALLOW_AUTH_COLLECTIONS=true to allow MCP mutations.`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const pickCollectionFields = (collection: CollectionConfig, input: Record<string, unknown>) => {
|
|
54
|
+
const allowed = new Set(Object.keys(collection.fields));
|
|
55
|
+
return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const pickTranslatableFields = (collection: CollectionConfig, input: Record<string, unknown>) => {
|
|
59
|
+
return Object.fromEntries(
|
|
60
|
+
Object.entries(input).filter(([key]) => cms.meta.isTranslatableField(collection.slug, key)),
|
|
61
|
+
);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const collectionModel = (slug: string) => {
|
|
65
|
+
getCollection(slug);
|
|
66
|
+
const described = model.collections.find((collection) => collection.slug === slug);
|
|
67
|
+
if (!described) throw new Error(`No model manifest found for collection "${slug}".`);
|
|
68
|
+
return described;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
type OpArgs = Record<string, any>;
|
|
72
|
+
|
|
73
|
+
const ops: Record<string, (args: OpArgs) => unknown> = {
|
|
74
|
+
model: () => model,
|
|
75
|
+
|
|
76
|
+
listCollections: () => cms.meta.getCollections(),
|
|
77
|
+
|
|
78
|
+
describeCollection: ({ collection }) => collectionModel(collection),
|
|
79
|
+
|
|
80
|
+
listDocuments: async ({ collection, where, search, sort, limit, offset, status, locale }) => {
|
|
81
|
+
const collectionApi = getCollectionApi(collection);
|
|
82
|
+
const options = { where, search, sort, limit, offset, status, locale };
|
|
83
|
+
const [docs, totalDocs] = await Promise.all([
|
|
84
|
+
collectionApi.find(options, runtimeContext()),
|
|
85
|
+
collectionApi.count({ where, search, status, locale }, runtimeContext()),
|
|
86
|
+
]);
|
|
87
|
+
return { docs, totalDocs, limit, offset };
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
countDocuments: async ({ collection, where, search, status, locale }) => {
|
|
91
|
+
const collectionApi = getCollectionApi(collection);
|
|
92
|
+
const totalDocs = await collectionApi.count({ where, search, status, locale }, runtimeContext());
|
|
93
|
+
return { totalDocs };
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
getDocument: async ({ collection, id, status, locale }) => {
|
|
97
|
+
const collectionApi = getCollectionApi(collection);
|
|
98
|
+
const doc = await collectionApi.findById(id, { status, locale }, runtimeContext());
|
|
99
|
+
if (!doc) throw new Error(`No document found for "${collection}/${id}".`);
|
|
100
|
+
return doc;
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
createDocument: async ({ collection, data }) => {
|
|
104
|
+
const collectionConfig = getCollection(collection);
|
|
105
|
+
ensureMutableCollection(collectionConfig);
|
|
106
|
+
const collectionApi = getCollectionApi(collection);
|
|
107
|
+
const cleaned = pickCollectionFields(collectionConfig, data);
|
|
108
|
+
return collectionApi.create(cleaned, runtimeContext());
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
updateDocument: async ({ collection, id, data }) => {
|
|
112
|
+
const collectionConfig = getCollection(collection);
|
|
113
|
+
ensureMutableCollection(collectionConfig);
|
|
114
|
+
const collectionApi = getCollectionApi(collection);
|
|
115
|
+
const cleaned = pickCollectionFields(collectionConfig, data);
|
|
116
|
+
if (Object.keys(cleaned).length === 0) throw new Error("No declared collection fields were provided.");
|
|
117
|
+
return collectionApi.update(id, cleaned, runtimeContext());
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
publishDocument: async ({ collection, id }) => {
|
|
121
|
+
ensureMutableCollection(getCollection(collection));
|
|
122
|
+
return getCollectionApi(collection).publish(id, runtimeContext());
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
unpublishDocument: async ({ collection, id }) => {
|
|
126
|
+
ensureMutableCollection(getCollection(collection));
|
|
127
|
+
return getCollectionApi(collection).unpublish(id, runtimeContext());
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
scheduleDocument: async ({ collection, id, publishAt, unpublishAt }) => {
|
|
131
|
+
ensureMutableCollection(getCollection(collection));
|
|
132
|
+
return getCollectionApi(collection).schedule(id, publishAt, unpublishAt ?? null, runtimeContext());
|
|
133
|
+
},
|
|
134
|
+
|
|
135
|
+
getTranslations: ({ collection, id }) => getCollectionApi(collection).getTranslations(id),
|
|
136
|
+
|
|
137
|
+
upsertTranslation: async ({ collection, id, locale, data }) => {
|
|
138
|
+
const collectionConfig = getCollection(collection);
|
|
139
|
+
ensureMutableCollection(collectionConfig);
|
|
140
|
+
const cleaned = pickTranslatableFields(collectionConfig, data);
|
|
141
|
+
if (Object.keys(cleaned).length === 0) throw new Error("No translatable fields were provided.");
|
|
142
|
+
return getCollectionApi(collection).upsertTranslation(id, locale, cleaned, runtimeContext());
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
listAssets: async ({ limit, offset, folder, search }) => {
|
|
146
|
+
const items = await assets.find({ limit, offset, folder, search });
|
|
147
|
+
const totalAssets = await assets.count({ folder, search });
|
|
148
|
+
return { items, totalAssets, limit, offset };
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
updateAsset: async ({ id, alt, filename, folder, focalX, focalY }) => {
|
|
152
|
+
const updated = await assets.update(
|
|
153
|
+
id,
|
|
154
|
+
{
|
|
155
|
+
...(alt !== undefined ? { alt } : {}),
|
|
156
|
+
...(filename !== undefined ? { filename } : {}),
|
|
157
|
+
...(folder !== undefined ? { folder } : {}),
|
|
158
|
+
...(focalX !== undefined ? { focalX } : {}),
|
|
159
|
+
...(focalY !== undefined ? { focalY } : {}),
|
|
160
|
+
},
|
|
161
|
+
{ actor },
|
|
162
|
+
);
|
|
163
|
+
if (!updated) throw new Error(`No asset found for "${id}".`);
|
|
164
|
+
return updated;
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
listAssetFolders: () => folders.findAll(),
|
|
168
|
+
|
|
169
|
+
dispose: async () => {
|
|
170
|
+
await closeDb();
|
|
171
|
+
// Exit after the reply flushes; the parent's kill() is only a backup.
|
|
172
|
+
setImmediate(() => process.exit(0));
|
|
173
|
+
return null;
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// A missing cms_* table means the config declares a collection the database
|
|
178
|
+
// doesn't have yet — the one sync step MCP can't do for the agent. Say so.
|
|
179
|
+
const withSchemaHint = (message: string) =>
|
|
180
|
+
/no such table: cms_/i.test(message)
|
|
181
|
+
? `${message}. The database schema is out of sync with the CMS config — run "pnpm cms:push" (or start the dev server, which pushes on boot), then retry.`
|
|
182
|
+
: message;
|
|
183
|
+
|
|
184
|
+
process.on("message", (message: { id: number; op: string; args?: OpArgs }) => {
|
|
185
|
+
void (async () => {
|
|
186
|
+
try {
|
|
187
|
+
const run = ops[message.op];
|
|
188
|
+
if (!run) throw new Error(`Unknown MCP worker op "${message.op}".`);
|
|
189
|
+
const result = await run(message.args ?? {});
|
|
190
|
+
sendToParent({ id: message.id, ok: true, result: result ?? null });
|
|
191
|
+
} catch (error) {
|
|
192
|
+
sendToParent({
|
|
193
|
+
id: message.id,
|
|
194
|
+
ok: false,
|
|
195
|
+
error: withSchemaHint(error instanceof Error ? error.message : String(error)),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
})();
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
sendToParent({ ready: true });
|
package/internals/mcp.ts
CHANGED
|
@@ -1,21 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local stdio MCP server. This process owns the transport and the (static)
|
|
3
|
+
* tool list and never restarts; the project modules (cms.config, generated
|
|
4
|
+
* API, DB) load inside a child process (mcp-worker.ts). When the schema
|
|
5
|
+
* changes on disk, the next tool call respawns the worker — a fresh process
|
|
6
|
+
* gets a fresh ESM module registry — so agents pick up new collections
|
|
7
|
+
* without reconnecting the client. An in-process reload is not possible (the
|
|
8
|
+
* ESM module cache cannot be invalidated), and worker threads don't inherit
|
|
9
|
+
* tsx's resolver, so a forked process it is.
|
|
10
|
+
*/
|
|
11
|
+
import { fork } from "node:child_process";
|
|
12
|
+
import { readdirSync, statSync } from "node:fs";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
|
|
1
15
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
16
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
17
|
import { z } from "zod";
|
|
4
18
|
|
|
5
|
-
import {
|
|
6
|
-
import type { CollectionConfig } from "../core";
|
|
7
|
-
import { loadGeneratedApi, loadProjectConfig } from "./project";
|
|
8
|
-
|
|
9
|
-
const { cms } = await loadGeneratedApi();
|
|
10
|
-
const config = await loadProjectConfig();
|
|
19
|
+
import { projectPath } from "./project";
|
|
11
20
|
|
|
12
21
|
const server = new McpServer({
|
|
13
22
|
name: "kide-cms",
|
|
14
23
|
version: "0.1.0",
|
|
15
24
|
});
|
|
16
25
|
|
|
17
|
-
const
|
|
18
|
-
const
|
|
26
|
+
const WATCHED_FILES = ["src/cms/cms.config.ts", "src/cms/.generated/api.ts"];
|
|
27
|
+
const COLLECTIONS_DIR = "src/cms/collections";
|
|
28
|
+
|
|
29
|
+
const takeSnapshot = () => {
|
|
30
|
+
const entries = new Map<string, number | null>();
|
|
31
|
+
const record = (...segments: string[]) => {
|
|
32
|
+
try {
|
|
33
|
+
entries.set(segments.join("/"), statSync(projectPath(...segments)).mtimeMs);
|
|
34
|
+
} catch {
|
|
35
|
+
entries.set(segments.join("/"), null);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
for (const file of WATCHED_FILES) record(file);
|
|
39
|
+
let collectionFiles: string[] = [];
|
|
40
|
+
try {
|
|
41
|
+
collectionFiles = readdirSync(projectPath(COLLECTIONS_DIR));
|
|
42
|
+
} catch {
|
|
43
|
+
// no collections directory
|
|
44
|
+
}
|
|
45
|
+
for (const name of collectionFiles) record(COLLECTIONS_DIR, name);
|
|
46
|
+
return entries;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const sameSnapshot = (a: Map<string, number | null>, b: Map<string, number | null>) =>
|
|
50
|
+
a.size === b.size && [...a].every(([key, value]) => b.get(key) === value);
|
|
51
|
+
|
|
52
|
+
type WorkerResponse = { ready: true } | { id: number; ok: boolean; result?: unknown; error?: string };
|
|
53
|
+
|
|
54
|
+
type WorkerHandle = {
|
|
55
|
+
call: (op: string, args?: Record<string, unknown>) => Promise<unknown>;
|
|
56
|
+
dispose: () => Promise<void>;
|
|
57
|
+
isDead: () => boolean;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const spawnWorker = (): Promise<WorkerHandle> =>
|
|
61
|
+
new Promise((resolve, reject) => {
|
|
62
|
+
const child = fork(fileURLToPath(new URL("./mcp-worker-boot.mjs", import.meta.url)), [], {
|
|
63
|
+
// stdout belongs to the MCP transport — route the child's output to stderr.
|
|
64
|
+
stdio: ["ignore", 2, 2, "ipc"],
|
|
65
|
+
});
|
|
66
|
+
// Don't let the worker keep this process alive once the client closes stdio.
|
|
67
|
+
child.unref();
|
|
68
|
+
child.channel?.unref();
|
|
69
|
+
const calls = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
|
|
70
|
+
let counter = 0;
|
|
71
|
+
let ready = false;
|
|
72
|
+
let dead: Error | null = null;
|
|
73
|
+
|
|
74
|
+
const handle: WorkerHandle = {
|
|
75
|
+
isDead: () => dead !== null,
|
|
76
|
+
call: (op, args) => {
|
|
77
|
+
if (dead) return Promise.reject(dead);
|
|
78
|
+
return new Promise((resolveCall, rejectCall) => {
|
|
79
|
+
const id = counter++;
|
|
80
|
+
calls.set(id, { resolve: resolveCall, reject: rejectCall });
|
|
81
|
+
child.send({ id, op, args });
|
|
82
|
+
});
|
|
83
|
+
},
|
|
84
|
+
dispose: async () => {
|
|
85
|
+
if (!dead) {
|
|
86
|
+
// Let the worker close the DB, but never hang a swap on it.
|
|
87
|
+
await Promise.race([handle.call("dispose"), new Promise((r) => setTimeout(r, 2000))]).catch(() => {});
|
|
88
|
+
dead = new Error("kide MCP worker was replaced.");
|
|
89
|
+
}
|
|
90
|
+
child.kill();
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const die = (error: Error) => {
|
|
95
|
+
if (dead) return;
|
|
96
|
+
dead = error;
|
|
97
|
+
for (const entry of calls.values()) entry.reject(error);
|
|
98
|
+
calls.clear();
|
|
99
|
+
if (!ready) reject(error);
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
child.on("message", (message: WorkerResponse) => {
|
|
103
|
+
if ("ready" in message) {
|
|
104
|
+
ready = true;
|
|
105
|
+
resolve(handle);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const entry = calls.get(message.id);
|
|
109
|
+
if (!entry) return;
|
|
110
|
+
calls.delete(message.id);
|
|
111
|
+
if (message.ok) entry.resolve(message.result);
|
|
112
|
+
else entry.reject(new Error(message.error ?? "kide MCP worker call failed."));
|
|
113
|
+
});
|
|
114
|
+
child.on("error", (error) => die(error instanceof Error ? error : new Error(String(error))));
|
|
115
|
+
child.on("exit", (code) => die(new Error(`kide MCP worker exited unexpectedly (code ${code}).`)));
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
let active: WorkerHandle | null = null;
|
|
119
|
+
let snapshot = takeSnapshot();
|
|
120
|
+
let swapping: Promise<void> | null = null;
|
|
121
|
+
|
|
122
|
+
const refreshWorker = (): Promise<void> => {
|
|
123
|
+
swapping ??= (async () => {
|
|
124
|
+
const previous = active;
|
|
125
|
+
active = null;
|
|
126
|
+
if (previous) {
|
|
127
|
+
console.error("[kide:mcp] schema change detected — reloading project modules");
|
|
128
|
+
await previous.dispose();
|
|
129
|
+
}
|
|
130
|
+
// Snapshot before spawning: a file that changes while the worker loads
|
|
131
|
+
// stays stale in the snapshot and triggers another reload on the next call.
|
|
132
|
+
snapshot = takeSnapshot();
|
|
133
|
+
active = await spawnWorker();
|
|
134
|
+
})().finally(() => {
|
|
135
|
+
swapping = null;
|
|
136
|
+
});
|
|
137
|
+
return swapping;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const workerCall = async (op: string, args?: Record<string, unknown>) => {
|
|
141
|
+
if (swapping) await swapping;
|
|
142
|
+
if (!active || active.isDead() || !sameSnapshot(snapshot, takeSnapshot())) await refreshWorker();
|
|
143
|
+
if (!active) throw new Error("kide MCP worker failed to start.");
|
|
144
|
+
return active.call(op, args);
|
|
145
|
+
};
|
|
19
146
|
|
|
20
147
|
const statusSchema = z.enum(["draft", "published", "scheduled", "any"]);
|
|
21
148
|
const sortSchema = z.object({
|
|
@@ -24,61 +151,11 @@ const sortSchema = z.object({
|
|
|
24
151
|
});
|
|
25
152
|
const jsonObjectSchema = z.record(z.string(), z.unknown());
|
|
26
153
|
|
|
27
|
-
const actor = {
|
|
28
|
-
id: process.env.KIDE_MCP_USER_ID || "mcp-local",
|
|
29
|
-
role: process.env.KIDE_MCP_USER_ROLE || "admin",
|
|
30
|
-
email: process.env.KIDE_MCP_USER_EMAIL || "mcp@local",
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
const runtimeContext = () => ({ user: actor });
|
|
34
|
-
|
|
35
154
|
const toResult = (value: unknown) => ({
|
|
36
155
|
structuredContent: { result: value },
|
|
37
156
|
content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }],
|
|
38
157
|
});
|
|
39
158
|
|
|
40
|
-
const getCollection = (slug: string): CollectionConfig => {
|
|
41
|
-
const collection = config.collections.find((entry) => entry.slug === slug);
|
|
42
|
-
if (!collection) {
|
|
43
|
-
const available = config.collections.map((entry) => entry.slug).join(", ");
|
|
44
|
-
throw new Error(`Unknown collection "${slug}". Available collections: ${available}`);
|
|
45
|
-
}
|
|
46
|
-
return collection;
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
const getCollectionApi = (slug: string) => {
|
|
50
|
-
getCollection(slug);
|
|
51
|
-
const collectionApi = cmsRuntime[slug];
|
|
52
|
-
if (!collectionApi) throw new Error(`No API found for collection "${slug}".`);
|
|
53
|
-
return collectionApi;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
const ensureMutableCollection = (collection: CollectionConfig) => {
|
|
57
|
-
if (collection.auth && process.env.KIDE_MCP_ALLOW_AUTH_COLLECTIONS !== "true") {
|
|
58
|
-
throw new Error(
|
|
59
|
-
`Collection "${collection.slug}" is an auth collection. Set KIDE_MCP_ALLOW_AUTH_COLLECTIONS=true to allow MCP mutations.`,
|
|
60
|
-
);
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
const pickCollectionFields = (collection: CollectionConfig, input: Record<string, unknown>) => {
|
|
65
|
-
const allowed = new Set(Object.keys(collection.fields));
|
|
66
|
-
return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
const pickTranslatableFields = (collection: CollectionConfig, input: Record<string, unknown>) => {
|
|
70
|
-
return Object.fromEntries(
|
|
71
|
-
Object.entries(input).filter(([key]) => cms.meta.isTranslatableField(collection.slug, key)),
|
|
72
|
-
);
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
const collectionModel = (slug: string) => {
|
|
76
|
-
getCollection(slug);
|
|
77
|
-
const described = model.collections.find((collection) => collection.slug === slug);
|
|
78
|
-
if (!described) throw new Error(`No model manifest found for collection "${slug}".`);
|
|
79
|
-
return described;
|
|
80
|
-
};
|
|
81
|
-
|
|
82
159
|
server.registerResource(
|
|
83
160
|
"kide-model",
|
|
84
161
|
"kide://model",
|
|
@@ -88,7 +165,9 @@ server.registerResource(
|
|
|
88
165
|
mimeType: "application/json",
|
|
89
166
|
},
|
|
90
167
|
async (uri) => ({
|
|
91
|
-
contents: [
|
|
168
|
+
contents: [
|
|
169
|
+
{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(await workerCall("model"), null, 2) },
|
|
170
|
+
],
|
|
92
171
|
}),
|
|
93
172
|
);
|
|
94
173
|
|
|
@@ -99,7 +178,7 @@ server.registerTool(
|
|
|
99
178
|
description: "List all Kide collections and their high-level metadata.",
|
|
100
179
|
inputSchema: {},
|
|
101
180
|
},
|
|
102
|
-
async () => toResult(
|
|
181
|
+
async () => toResult(await workerCall("listCollections")),
|
|
103
182
|
);
|
|
104
183
|
|
|
105
184
|
server.registerTool(
|
|
@@ -112,7 +191,7 @@ server.registerTool(
|
|
|
112
191
|
collection: z.string().min(1),
|
|
113
192
|
},
|
|
114
193
|
},
|
|
115
|
-
async (
|
|
194
|
+
async (args) => toResult(await workerCall("describeCollection", args)),
|
|
116
195
|
);
|
|
117
196
|
|
|
118
197
|
server.registerTool(
|
|
@@ -132,16 +211,7 @@ server.registerTool(
|
|
|
132
211
|
locale: z.string().min(1).optional(),
|
|
133
212
|
},
|
|
134
213
|
},
|
|
135
|
-
async (
|
|
136
|
-
const collectionApi = getCollectionApi(collection);
|
|
137
|
-
const options = { where, search, sort, limit, offset, status, locale };
|
|
138
|
-
const [docs, totalDocs] = await Promise.all([
|
|
139
|
-
collectionApi.find(options, runtimeContext()),
|
|
140
|
-
collectionApi.count({ where, search, status, locale }, runtimeContext()),
|
|
141
|
-
]);
|
|
142
|
-
|
|
143
|
-
return toResult({ docs, totalDocs, limit, offset });
|
|
144
|
-
},
|
|
214
|
+
async (args) => toResult(await workerCall("listDocuments", args)),
|
|
145
215
|
);
|
|
146
216
|
|
|
147
217
|
server.registerTool(
|
|
@@ -157,11 +227,7 @@ server.registerTool(
|
|
|
157
227
|
locale: z.string().min(1).optional(),
|
|
158
228
|
},
|
|
159
229
|
},
|
|
160
|
-
async (
|
|
161
|
-
const collectionApi = getCollectionApi(collection);
|
|
162
|
-
const totalDocs = await collectionApi.count({ where, search, status, locale }, runtimeContext());
|
|
163
|
-
return toResult({ totalDocs });
|
|
164
|
-
},
|
|
230
|
+
async (args) => toResult(await workerCall("countDocuments", args)),
|
|
165
231
|
);
|
|
166
232
|
|
|
167
233
|
server.registerTool(
|
|
@@ -176,12 +242,7 @@ server.registerTool(
|
|
|
176
242
|
locale: z.string().min(1).optional(),
|
|
177
243
|
},
|
|
178
244
|
},
|
|
179
|
-
async (
|
|
180
|
-
const collectionApi = getCollectionApi(collection);
|
|
181
|
-
const doc = await collectionApi.findById(id, { status, locale }, runtimeContext());
|
|
182
|
-
if (!doc) throw new Error(`No document found for "${collection}/${id}".`);
|
|
183
|
-
return toResult(doc);
|
|
184
|
-
},
|
|
245
|
+
async (args) => toResult(await workerCall("getDocument", args)),
|
|
185
246
|
);
|
|
186
247
|
|
|
187
248
|
server.registerTool(
|
|
@@ -195,14 +256,7 @@ server.registerTool(
|
|
|
195
256
|
data: jsonObjectSchema,
|
|
196
257
|
},
|
|
197
258
|
},
|
|
198
|
-
async (
|
|
199
|
-
const collectionConfig = getCollection(collection);
|
|
200
|
-
ensureMutableCollection(collectionConfig);
|
|
201
|
-
const collectionApi = getCollectionApi(collection);
|
|
202
|
-
const cleaned = pickCollectionFields(collectionConfig, data);
|
|
203
|
-
const doc = await collectionApi.create(cleaned, runtimeContext());
|
|
204
|
-
return toResult(doc);
|
|
205
|
-
},
|
|
259
|
+
async (args) => toResult(await workerCall("createDocument", args)),
|
|
206
260
|
);
|
|
207
261
|
|
|
208
262
|
server.registerTool(
|
|
@@ -217,15 +271,7 @@ server.registerTool(
|
|
|
217
271
|
data: jsonObjectSchema,
|
|
218
272
|
},
|
|
219
273
|
},
|
|
220
|
-
async (
|
|
221
|
-
const collectionConfig = getCollection(collection);
|
|
222
|
-
ensureMutableCollection(collectionConfig);
|
|
223
|
-
const collectionApi = getCollectionApi(collection);
|
|
224
|
-
const cleaned = pickCollectionFields(collectionConfig, data);
|
|
225
|
-
if (Object.keys(cleaned).length === 0) throw new Error("No declared collection fields were provided.");
|
|
226
|
-
const doc = await collectionApi.update(id, cleaned, runtimeContext());
|
|
227
|
-
return toResult(doc);
|
|
228
|
-
},
|
|
274
|
+
async (args) => toResult(await workerCall("updateDocument", args)),
|
|
229
275
|
);
|
|
230
276
|
|
|
231
277
|
server.registerTool(
|
|
@@ -238,12 +284,7 @@ server.registerTool(
|
|
|
238
284
|
id: z.string().min(1),
|
|
239
285
|
},
|
|
240
286
|
},
|
|
241
|
-
async (
|
|
242
|
-
const collectionConfig = getCollection(collection);
|
|
243
|
-
ensureMutableCollection(collectionConfig);
|
|
244
|
-
const doc = await getCollectionApi(collection).publish(id, runtimeContext());
|
|
245
|
-
return toResult(doc);
|
|
246
|
-
},
|
|
287
|
+
async (args) => toResult(await workerCall("publishDocument", args)),
|
|
247
288
|
);
|
|
248
289
|
|
|
249
290
|
server.registerTool(
|
|
@@ -256,12 +297,7 @@ server.registerTool(
|
|
|
256
297
|
id: z.string().min(1),
|
|
257
298
|
},
|
|
258
299
|
},
|
|
259
|
-
async (
|
|
260
|
-
const collectionConfig = getCollection(collection);
|
|
261
|
-
ensureMutableCollection(collectionConfig);
|
|
262
|
-
const doc = await getCollectionApi(collection).unpublish(id, runtimeContext());
|
|
263
|
-
return toResult(doc);
|
|
264
|
-
},
|
|
300
|
+
async (args) => toResult(await workerCall("unpublishDocument", args)),
|
|
265
301
|
);
|
|
266
302
|
|
|
267
303
|
server.registerTool(
|
|
@@ -276,12 +312,7 @@ server.registerTool(
|
|
|
276
312
|
unpublishAt: z.string().min(1).nullable().optional(),
|
|
277
313
|
},
|
|
278
314
|
},
|
|
279
|
-
async (
|
|
280
|
-
const collectionConfig = getCollection(collection);
|
|
281
|
-
ensureMutableCollection(collectionConfig);
|
|
282
|
-
const doc = await getCollectionApi(collection).schedule(id, publishAt, unpublishAt ?? null, runtimeContext());
|
|
283
|
-
return toResult(doc);
|
|
284
|
-
},
|
|
315
|
+
async (args) => toResult(await workerCall("scheduleDocument", args)),
|
|
285
316
|
);
|
|
286
317
|
|
|
287
318
|
server.registerTool(
|
|
@@ -294,10 +325,7 @@ server.registerTool(
|
|
|
294
325
|
id: z.string().min(1),
|
|
295
326
|
},
|
|
296
327
|
},
|
|
297
|
-
async (
|
|
298
|
-
const translations = await getCollectionApi(collection).getTranslations(id);
|
|
299
|
-
return toResult(translations);
|
|
300
|
-
},
|
|
328
|
+
async (args) => toResult(await workerCall("getTranslations", args)),
|
|
301
329
|
);
|
|
302
330
|
|
|
303
331
|
server.registerTool(
|
|
@@ -312,14 +340,7 @@ server.registerTool(
|
|
|
312
340
|
data: jsonObjectSchema,
|
|
313
341
|
},
|
|
314
342
|
},
|
|
315
|
-
async (
|
|
316
|
-
const collectionConfig = getCollection(collection);
|
|
317
|
-
ensureMutableCollection(collectionConfig);
|
|
318
|
-
const cleaned = pickTranslatableFields(collectionConfig, data);
|
|
319
|
-
if (Object.keys(cleaned).length === 0) throw new Error("No translatable fields were provided.");
|
|
320
|
-
const doc = await getCollectionApi(collection).upsertTranslation(id, locale, cleaned, runtimeContext());
|
|
321
|
-
return toResult(doc);
|
|
322
|
-
},
|
|
343
|
+
async (args) => toResult(await workerCall("upsertTranslation", args)),
|
|
323
344
|
);
|
|
324
345
|
|
|
325
346
|
server.registerTool(
|
|
@@ -334,11 +355,7 @@ server.registerTool(
|
|
|
334
355
|
search: z.string().optional(),
|
|
335
356
|
},
|
|
336
357
|
},
|
|
337
|
-
async (
|
|
338
|
-
const items = await assets.find({ limit, offset, folder, search });
|
|
339
|
-
const totalAssets = await assets.count({ folder, search });
|
|
340
|
-
return toResult({ items, totalAssets, limit, offset });
|
|
341
|
-
},
|
|
358
|
+
async (args) => toResult(await workerCall("listAssets", args)),
|
|
342
359
|
);
|
|
343
360
|
|
|
344
361
|
server.registerTool(
|
|
@@ -355,21 +372,7 @@ server.registerTool(
|
|
|
355
372
|
focalY: z.number().nullable().optional(),
|
|
356
373
|
},
|
|
357
374
|
},
|
|
358
|
-
async (
|
|
359
|
-
const updated = await assets.update(
|
|
360
|
-
id,
|
|
361
|
-
{
|
|
362
|
-
...(alt !== undefined ? { alt } : {}),
|
|
363
|
-
...(filename !== undefined ? { filename } : {}),
|
|
364
|
-
...(folder !== undefined ? { folder } : {}),
|
|
365
|
-
...(focalX !== undefined ? { focalX } : {}),
|
|
366
|
-
...(focalY !== undefined ? { focalY } : {}),
|
|
367
|
-
},
|
|
368
|
-
{ actor },
|
|
369
|
-
);
|
|
370
|
-
if (!updated) throw new Error(`No asset found for "${id}".`);
|
|
371
|
-
return toResult(updated);
|
|
372
|
-
},
|
|
375
|
+
async (args) => toResult(await workerCall("updateAsset", args)),
|
|
373
376
|
);
|
|
374
377
|
|
|
375
378
|
server.registerTool(
|
|
@@ -379,11 +382,13 @@ server.registerTool(
|
|
|
379
382
|
description: "List Kide asset folders.",
|
|
380
383
|
inputSchema: {},
|
|
381
384
|
},
|
|
382
|
-
async () => toResult(await
|
|
385
|
+
async () => toResult(await workerCall("listAssetFolders")),
|
|
383
386
|
);
|
|
384
387
|
|
|
385
388
|
const shutdown = async () => {
|
|
386
|
-
|
|
389
|
+
const current = active;
|
|
390
|
+
active = null;
|
|
391
|
+
if (current) await current.dispose();
|
|
387
392
|
};
|
|
388
393
|
|
|
389
394
|
process.on("SIGINT", () => {
|
|
@@ -393,5 +398,12 @@ process.on("SIGTERM", () => {
|
|
|
393
398
|
void shutdown().finally(() => process.exit(0));
|
|
394
399
|
});
|
|
395
400
|
|
|
401
|
+
// Load the project eagerly so the first tool call is fast; a failure (e.g. a
|
|
402
|
+
// type error in cms.config.ts) is reported per tool call and retried there,
|
|
403
|
+
// instead of preventing the server from starting.
|
|
404
|
+
void refreshWorker().catch((error: unknown) => {
|
|
405
|
+
console.error(`[kide:mcp] project load failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
406
|
+
});
|
|
407
|
+
|
|
396
408
|
await server.connect(new StdioServerTransport());
|
|
397
409
|
console.error("[kide:mcp] local MCP server started");
|