-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtaxonomy.test.ts
More file actions
943 lines (841 loc) · 33.2 KB
/
Copy pathtaxonomy.test.ts
File metadata and controls
943 lines (841 loc) · 33.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
/**
* MCP taxonomy tools — comprehensive integration tests.
*
* Covers:
* - taxonomy_list
* - taxonomy_list_terms
* - taxonomy_create_term
*
* Plus regression coverage for:
* - bug #7 (orphan taxonomy collection inconsistency)
* - bug #13 (no delete/update term tool — gap test)
*/
import { Role } from "@emdash-cms/auth";
import type { Kysely } from "kysely";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { handleTaxonomyCreate } from "../../../src/api/handlers/taxonomies.js";
import { TaxonomyRepository as TaxonomyRepo } from "../../../src/database/repositories/taxonomy.js";
import { encodeCursor } from "../../../src/database/repositories/types.js";
import type { Database } from "../../../src/database/types.js";
import { SchemaRegistry } from "../../../src/schema/registry.js";
import { decodeBase64, encodeBase64 } from "../../../src/utils/base64.js";
import {
connectMcpHarness,
extractJson,
extractText,
type McpHarness,
} from "../../utils/mcp-runtime.js";
import { setupTestDatabase, teardownTestDatabase } from "../../utils/test-db.js";
const ADMIN_ID = "user_admin";
const AUTHOR_ID = "user_author";
const SUBSCRIBER_ID = "user_subscriber";
async function setupTaxonomy(
db: Kysely<Database>,
input: { name: string; label: string; hierarchical?: boolean; collections?: string[] },
): Promise<void> {
const result = await handleTaxonomyCreate(db, input);
if (!result.success) {
throw new Error(`Failed to set up taxonomy: ${result.error?.message}`);
}
}
// ---------------------------------------------------------------------------
// taxonomy_list
// ---------------------------------------------------------------------------
describe("taxonomy_list", () => {
let db: Kysely<Database>;
let harness: McpHarness;
beforeEach(async () => {
db = await setupTestDatabase();
});
afterEach(async () => {
if (harness) await harness.cleanup();
await teardownTestDatabase(db);
});
it("returns only the seeded defaults when no extra taxonomies are added", async () => {
// Migration 006 seeds two default taxonomies: 'category' (hierarchical)
// and 'tag' (flat), both linked to the 'posts' collection. A fresh
// install always has these.
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_list",
arguments: {},
});
expect(result.isError, extractText(result)).toBeFalsy();
const { taxonomies } = extractJson<{
taxonomies: Array<{ name: string }>;
}>(result);
const names = taxonomies.map((t) => t.name).toSorted();
expect(names).toEqual(["category", "tag"]);
});
it("lists user-created taxonomies alongside the defaults", async () => {
const registry = new SchemaRegistry(db);
await registry.createCollection({ slug: "post", label: "Posts" });
// Use names that don't collide with the seeded `category` / `tag`.
await setupTaxonomy(db, {
name: "section",
label: "Sections",
hierarchical: true,
collections: ["post"],
});
await setupTaxonomy(db, {
name: "topic",
label: "Topics",
collections: ["post"],
});
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_list",
arguments: {},
});
const { taxonomies } = extractJson<{
taxonomies: Array<{ name: string; hierarchical?: boolean; collections?: string[] }>;
}>(result);
const names = taxonomies.map((t) => t.name).toSorted();
expect(names).toEqual(["category", "section", "tag", "topic"]);
const section = taxonomies.find((t) => t.name === "section");
expect(section?.hierarchical).toBe(true);
expect(section?.collections).toEqual(["post"]);
});
it("any logged-in user (SUBSCRIBER) can read taxonomies", async () => {
harness = await connectMcpHarness({ db, userId: SUBSCRIBER_ID, userRole: Role.SUBSCRIBER });
const result = await harness.client.callTool({
name: "taxonomy_list",
arguments: {},
});
expect(result.isError, extractText(result)).toBeFalsy();
});
it("bug #7: orphaned collection slugs are filtered from taxonomy_list output", async () => {
// The seed taxonomies (category, tag) both reference 'posts' — a
// collection that doesn't exist in this test DB (no auto-seed). After
// the bug #7 fix, `taxonomy_list` filters those orphans out. We don't
// need to manufacture an orphan; the seed already gives us one.
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const taxResult = await harness.client.callTool({
name: "taxonomy_list",
arguments: {},
});
const { taxonomies } = extractJson<{
taxonomies: Array<{ name: string; collections?: string[] }>;
}>(taxResult);
// Each seeded taxonomy referenced 'posts'. After filtering, that
// orphan slug is gone — the array should be empty for both seeds.
for (const t of taxonomies) {
expect(t.collections).not.toContain("posts");
}
// And schema_list_collections agrees: there is no 'posts' collection.
const collResult = await harness.client.callTool({
name: "schema_list_collections",
arguments: {},
});
const { items } = extractJson<{ items: Array<{ slug: string }> }>(collResult);
expect(items.find((c) => c.slug === "posts")).toBeUndefined();
});
});
// ---------------------------------------------------------------------------
// taxonomy_list_terms
// ---------------------------------------------------------------------------
describe("taxonomy_list_terms", () => {
let db: Kysely<Database>;
let harness: McpHarness;
beforeEach(async () => {
db = await setupTestDatabase();
await setupTaxonomy(db, { name: "categories", label: "Categories", hierarchical: true });
});
afterEach(async () => {
if (harness) await harness.cleanup();
await teardownTestDatabase(db);
});
it("returns empty list when taxonomy has no terms", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories" },
});
expect(result.isError, extractText(result)).toBeFalsy();
const { items } = extractJson<{ items: unknown[] }>(result);
expect(items).toEqual([]);
});
it("returns terms after creation", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "tech", label: "Tech" },
});
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "design", label: "Design" },
});
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories" },
});
const { items } = extractJson<{
items: Array<{ slug: string; label: string; parentId: string | null }>;
}>(result);
const slugs = items.map((t) => t.slug).toSorted();
expect(slugs).toEqual(["design", "tech"]);
});
it("returns clear error for missing taxonomy name", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "nonexistent" },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/\bNOT_FOUND\b|\bnot found\b/i);
expect(extractText(result)).toContain("nonexistent");
});
it("paginates with limit + cursor", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
// Insert 5 terms — labels chosen so alphabetical ordering is predictable
for (const label of ["alpha", "bravo", "charlie", "delta", "echo"]) {
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: label, label },
});
}
const page1 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 2 },
});
const p1 = extractJson<{ items: Array<{ slug: string; id: string }>; nextCursor?: string }>(
page1,
);
expect(p1.items).toHaveLength(2);
expect(p1.nextCursor).toBeTruthy();
const page2 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 2, cursor: p1.nextCursor },
});
const p2 = extractJson<{ items: Array<{ slug: string }>; nextCursor?: string }>(page2);
expect(p2.items).toHaveLength(2);
// No overlap
const p1Slugs = p1.items.map((i) => i.slug);
for (const t of p2.items) expect(p1Slugs).not.toContain(t.slug);
});
it("paginates in manual term order", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
for (const [slug, label] of [
["first", "Zulu"],
["second", "Alpha"],
] as const) {
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug, label },
});
}
const page1 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 1 },
});
const p1 = extractJson<{ items: Array<{ slug: string }>; nextCursor?: string }>(page1);
expect(p1.items.map((item) => item.slug)).toEqual(["first"]);
expect(p1.nextCursor).toBeTruthy();
const page2 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 1, cursor: p1.nextCursor },
});
const p2 = extractJson<{ items: Array<{ slug: string }> }>(page2);
expect(p2.items.map((item) => item.slug)).toEqual(["second"]);
});
it("paginates correctly when multiple terms share the same label", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const slugs = ["shared-1", "shared-2", "shared-3", "unique-a"];
for (const slug of slugs) {
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: {
taxonomy: "categories",
slug,
label: slug.startsWith("shared") ? "shared" : slug,
},
});
}
const collected: string[] = [];
let cursor: string | undefined;
for (let i = 0; i < 10; i++) {
const page = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 1, ...(cursor ? { cursor } : {}) },
});
const data = extractJson<{
items: Array<{ slug: string; id: string }>;
nextCursor?: string;
}>(page);
if (data.items.length === 0) break;
for (const item of data.items) collected.push(item.slug);
if (!data.nextCursor) break;
cursor = data.nextCursor;
}
expect(collected.toSorted()).toEqual(slugs.toSorted());
});
it("rejects a current cursor after its term is deleted", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
for (const slug of ["alpha", "bravo", "charlie", "delta"]) {
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug, label: slug },
});
}
const page1 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 2 },
});
const p1 = extractJson<{
items: Array<{ id: string; slug: string }>;
nextCursor?: string;
}>(page1);
expect(p1.items.map((i) => i.slug)).toEqual(["alpha", "bravo"]);
expect(p1.nextCursor).toBeTruthy();
expect(JSON.parse(decodeBase64(p1.nextCursor!))).toEqual({
v: 2,
id: p1.items[1]!.id,
});
const repo = new TaxonomyRepo(db);
const bravo = await repo.findBySlug("categories", "bravo");
if (!bravo) throw new Error("bravo fixture is missing");
await db.deleteFrom("taxonomies").where("id", "=", bravo.id).execute();
const page2 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 2, cursor: p1.nextCursor },
});
expect(page2.isError).toBe(true);
expect((page2 as { _meta?: { code?: string } })._meta?.code).toBe("INVALID_CURSOR");
});
it("rejects a cursor from another taxonomy", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const repo = new TaxonomyRepo(db);
const tag = await repo.create({ name: "tags", slug: "tag", label: "Tag" });
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: {
taxonomy: "categories",
cursor: encodeBase64(JSON.stringify({ v: 2, id: tag.id })),
},
});
expect(result.isError).toBe(true);
expect((result as { _meta?: { code?: string } })._meta?.code).toBe("INVALID_CURSOR");
});
it("rejects a cursor from another locale", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const repo = new TaxonomyRepo(db);
const french = await repo.create({
name: "categories",
slug: "bonjour",
label: "Bonjour",
locale: "fr",
});
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: {
taxonomy: "categories",
locale: "en",
cursor: encodeBase64(JSON.stringify({ v: 2, id: french.id })),
},
});
expect(result.isError).toBe(true);
expect((result as { _meta?: { code?: string } })._meta?.code).toBe("INVALID_CURSOR");
});
it("resumes a legacy cursor in manual term order", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
for (const [slug, label] of [
["charlie", "Charlie"],
["alpha", "Alpha"],
["bravo", "Bravo"],
] as const) {
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug, label },
});
}
const repo = new TaxonomyRepo(db);
const alpha = await repo.findBySlug("categories", "alpha");
if (!alpha) throw new Error("alpha fixture is missing");
const page1 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: {
taxonomy: "categories",
limit: 2,
cursor: encodeCursor(alpha.label, alpha.id),
},
});
const p1 = extractJson<{ items: Array<{ slug: string }>; nextCursor?: string }>(page1);
expect(p1.items.map((item) => item.slug)).toEqual(["bravo"]);
expect(p1.nextCursor).toBeUndefined();
});
it("rejects a legacy cursor after its term is deleted", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
for (const slug of ["alpha", "bravo"]) {
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug, label: slug },
});
}
const repo = new TaxonomyRepo(db);
const alpha = await repo.findBySlug("categories", "alpha");
if (!alpha) throw new Error("alpha fixture is missing");
const cursor = encodeCursor(alpha.label, alpha.id);
await db.deleteFrom("taxonomies").where("id", "=", alpha.id).execute();
const page2 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 1, cursor },
});
expect(page2.isError).toBe(true);
expect((page2 as { _meta?: { code?: string } })._meta?.code).toBe("INVALID_CURSOR");
});
it("accepts every cursor it emits for a long term label", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "long", label: "x".repeat(1_500) },
});
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "last", label: "Last" },
});
const page1 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 1 },
});
const p1 = extractJson<{ items: Array<{ slug: string }>; nextCursor?: string }>(page1);
expect(p1.items.map((item) => item.slug)).toEqual(["long"]);
expect(p1.nextCursor).toBeTruthy();
const page2 = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", limit: 1, cursor: p1.nextCursor },
});
expect(page2.isError, extractText(page2)).toBeFalsy();
const p2 = extractJson<{ items: Array<{ slug: string }> }>(page2);
expect(p2.items.map((item) => item.slug)).toEqual(["last"]);
});
it("malformed cursor returns INVALID_CURSOR", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "t1", label: "T1" },
});
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", cursor: "garbage_cursor_xyz" },
});
expect(result.isError).toBe(true);
const meta = (result as { _meta?: { code?: string } })._meta;
expect(meta?.code).toBe("INVALID_CURSOR");
});
it.each([
["unknown version", { v: 3, id: "term-1" }],
["missing id", { v: 2 }],
["non-string id", { v: 2, id: 1 }],
["empty id", { v: 2, id: "" }],
["NUL id", { v: 2, id: "term\0" }],
])("rejects a cursor with %s", async (_name, payload) => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: {
taxonomy: "categories",
cursor: encodeBase64(JSON.stringify(payload)),
},
});
expect(result.isError).toBe(true);
expect((result as { _meta?: { code?: string } })._meta?.code).toBe("INVALID_CURSOR");
});
it.each([
["NUL label", encodeCursor("T\0", "term-1")],
["NUL id", encodeCursor("T1", "term\0")],
])("rejects a legacy cursor with %s", async (_name, cursor) => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories", cursor },
});
expect(result.isError).toBe(true);
expect((result as { _meta?: { code?: string } })._meta?.code).toBe("INVALID_CURSOR");
});
it("any logged-in user (SUBSCRIBER) can read terms", async () => {
harness = await connectMcpHarness({ db, userId: SUBSCRIBER_ID, userRole: Role.SUBSCRIBER });
const result = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "categories" },
});
expect(result.isError, extractText(result)).toBeFalsy();
});
});
// ---------------------------------------------------------------------------
// taxonomy_create_term
// ---------------------------------------------------------------------------
describe("taxonomy_create_term", () => {
let db: Kysely<Database>;
let harness: McpHarness;
beforeEach(async () => {
db = await setupTestDatabase();
await setupTaxonomy(db, { name: "categories", label: "Categories", hierarchical: true });
await setupTaxonomy(db, { name: "tags", label: "Tags" });
});
afterEach(async () => {
if (harness) await harness.cleanup();
await teardownTestDatabase(db);
});
it("creates a term with minimal arguments", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "tech", label: "Tech" },
});
expect(result.isError, extractText(result)).toBeFalsy();
const { term } = extractJson<{ term: { slug: string; label: string } }>(result);
expect(term.slug).toBe("tech");
expect(term.label).toBe("Tech");
});
it("derives a Unicode slug when omitted", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", label: "音楽" },
});
expect(result.isError, extractText(result)).toBeFalsy();
const { term } = extractJson<{ term: { slug: string } }>(result);
expect(term.slug).toBe("音楽");
});
it("creates a child term with parentId", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const parent = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "tech", label: "Tech" },
});
const parentId = extractJson<{ term: { id: string } }>(parent).term.id;
const child = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: {
taxonomy: "categories",
slug: "ai",
label: "AI",
parentId,
},
});
expect(child.isError, extractText(child)).toBeFalsy();
const { term } = extractJson<{ term: { parentId: string | null } }>(child);
expect(term.parentId).toBe(parentId);
});
it("rejects duplicate slug within the same taxonomy", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "tech", label: "Tech" },
});
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "tech", label: "Tech 2" },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/exist|duplicate|conflict|unique|already/i);
});
it("allows same slug across different taxonomies", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const a = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "shared", label: "Shared" },
});
const b = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "shared", label: "Shared" },
});
expect(a.isError, extractText(a)).toBeFalsy();
expect(b.isError, extractText(b)).toBeFalsy();
});
it("rejects creating a term in a non-existent taxonomy", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "ghost", slug: "x", label: "X" },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/\bNOT_FOUND\b|\bnot found\b/i);
expect(extractText(result)).toContain("ghost");
});
it("rejects parentId pointing to a different taxonomy", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const tag = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "stuff", label: "Stuff" },
});
const tagId = extractJson<{ term: { id: string } }>(tag).term.id;
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: {
taxonomy: "categories",
slug: "child",
label: "Child",
parentId: tagId,
},
});
expect(result.isError).toBe(true);
});
it("rejects parentId pointing to a non-existent term", async () => {
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: {
taxonomy: "categories",
slug: "orphan",
label: "Orphan",
parentId: "01NEVEREXISTED",
},
});
expect(result.isError).toBe(true);
});
it("requires EDITOR role (AUTHOR is blocked)", async () => {
harness = await connectMcpHarness({ db, userId: AUTHOR_ID, userRole: Role.AUTHOR });
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "categories", slug: "x", label: "X" },
});
expect(result.isError).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Bug #13 / F2 / F3 / F12 — happy paths for taxonomy_update_term and
// taxonomy_delete_term, plus parent validation, cycle detection, and
// empty-string rejection.
// ---------------------------------------------------------------------------
describe("taxonomy_update_term (bug #13 / F2 / F12)", () => {
let db: Kysely<Database>;
let harness: McpHarness;
async function createTerm(
taxonomy: string,
slug: string,
label: string,
parentId?: string,
): Promise<string> {
const args: Record<string, unknown> = { taxonomy, slug, label };
if (parentId) args.parentId = parentId;
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: args,
});
expect(result.isError, extractText(result)).toBeFalsy();
const { term } = extractJson<{ term: { id: string } }>(result);
return term.id;
}
beforeEach(async () => {
db = await setupTestDatabase();
await setupTaxonomy(db, { name: "tags", label: "Tags" });
await setupTaxonomy(db, { name: "sections", label: "Sections" });
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
});
afterEach(async () => {
if (harness) await harness.cleanup();
await teardownTestDatabase(db);
});
it("MCP exposes taxonomy_update_term and taxonomy_delete_term", async () => {
const tools = await harness.client.listTools();
const names = tools.tools.map((t) => t.name);
expect(names).toContain("taxonomy_update_term");
expect(names).toContain("taxonomy_delete_term");
});
it("renames the slug when the new slug is free", async () => {
await createTerm("tags", "old-slug", "Original");
const result = await harness.client.callTool({
name: "taxonomy_update_term",
arguments: { taxonomy: "tags", termSlug: "old-slug", slug: "new-slug" },
});
expect(result.isError, extractText(result)).toBeFalsy();
const { term } = extractJson<{ term: { slug: string } }>(result);
expect(term.slug).toBe("new-slug");
});
it("changes the label", async () => {
await createTerm("tags", "x", "Old Label");
const result = await harness.client.callTool({
name: "taxonomy_update_term",
arguments: { taxonomy: "tags", termSlug: "x", label: "New Label" },
});
expect(result.isError, extractText(result)).toBeFalsy();
const { term } = extractJson<{ term: { label: string } }>(result);
expect(term.label).toBe("New Label");
});
it("reparents a term and detaches via parentId: null", async () => {
const parentId = await createTerm("tags", "parent", "Parent");
await createTerm("tags", "child", "Child");
const reparent = await harness.client.callTool({
name: "taxonomy_update_term",
arguments: { taxonomy: "tags", termSlug: "child", parentId },
});
expect(reparent.isError, extractText(reparent)).toBeFalsy();
const reparented = extractJson<{ term: { parentId: string | null } }>(reparent);
expect(reparented.term.parentId).toBe(parentId);
const detach = await harness.client.callTool({
name: "taxonomy_update_term",
arguments: { taxonomy: "tags", termSlug: "child", parentId: null },
});
expect(detach.isError, extractText(detach)).toBeFalsy();
const detached = extractJson<{ term: { parentId: string | null } }>(detach);
expect(detached.term.parentId).toBeNull();
});
it("rejects parents from a different taxonomy", async () => {
const sectionId = await createTerm("sections", "news", "News");
await createTerm("tags", "alpha", "Alpha");
const result = await harness.client.callTool({
name: "taxonomy_update_term",
arguments: { taxonomy: "tags", termSlug: "alpha", parentId: sectionId },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/VALIDATION_ERROR/);
});
it("rejects self-parent", async () => {
const id = await createTerm("tags", "loop", "Loop");
const result = await harness.client.callTool({
name: "taxonomy_update_term",
arguments: { taxonomy: "tags", termSlug: "loop", parentId: id },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/own parent|VALIDATION_ERROR/i);
});
it("rejects a 2-cycle (descendant becoming ancestor)", async () => {
// A is parent of B. Now try to make B the parent of A — that's a cycle.
const aId = await createTerm("tags", "a", "A");
const bId = await createTerm("tags", "b", "B", aId);
const result = await harness.client.callTool({
name: "taxonomy_update_term",
arguments: { taxonomy: "tags", termSlug: "a", parentId: bId },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/cycle|VALIDATION_ERROR/i);
});
it("rejects empty-string parentId on create", async () => {
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "x", label: "X", parentId: "" },
});
// Either returns a validation error, or treats it as no-parent.
// We choose strict: empty string is normalized to undefined so it
// succeeds with parentId === null (no parent attached). That's the
// behavior we documented.
if (result.isError) {
expect(extractText(result)).toMatch(/VALIDATION_ERROR/);
} else {
const { term } = extractJson<{ term: { parentId: string | null } }>(result);
expect(term.parentId).toBeNull();
}
});
// ----- MAX_DEPTH boundary -----
// validateParentTerm walks up the parent chain bounded by MAX_DEPTH=100
// to prevent a pathological pre-existing cycle from hanging the
// validator. The boundary is "more than 100 ancestors": exactly-100 is
// accepted, 101+ is rejected.
it("accepts a chain of exactly MAX_DEPTH (100) ancestors", async () => {
const { TaxonomyRepository } = await import("../../../src/database/repositories/taxonomy.js");
const repo = new TaxonomyRepository(db);
// Build root → 1 → 2 → ... → 100. 101 terms total. The deepest
// term has 100 ancestors; setting it as parent of a new term means
// validateParentTerm walks 100 hops up before exhausting the chain.
let parentId: string | undefined;
const ids: string[] = [];
for (let i = 0; i < 101; i++) {
const term = await repo.create({
name: "tags",
slug: `chain-${i}`,
label: `Chain ${i}`,
parentId,
});
ids.push(term.id);
parentId = term.id;
}
const deepest = ids.at(-1);
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "leaf", label: "Leaf", parentId: deepest },
});
// New term's parent is the 100-deep tail. Walking up from there
// reaches the root after exactly 100 hops; cursor becomes null,
// the depth-exceeded check does NOT fire.
expect(result.isError, extractText(result)).toBeFalsy();
});
it("rejects a chain that exceeds MAX_DEPTH", async () => {
const { TaxonomyRepository } = await import("../../../src/database/repositories/taxonomy.js");
const repo = new TaxonomyRepository(db);
// Build a 102-term chain. The deepest term has 101 ancestors —
// one more than MAX_DEPTH allows.
let parentId: string | undefined;
const ids: string[] = [];
for (let i = 0; i < 102; i++) {
const term = await repo.create({
name: "tags",
slug: `chain-${i}`,
label: `Chain ${i}`,
parentId,
});
ids.push(term.id);
parentId = term.id;
}
const deepest = ids.at(-1);
const result = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "leaf", label: "Leaf", parentId: deepest },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/maximum depth/i);
const meta = (result as { _meta?: { code?: string } })._meta;
expect(meta?.code).toBe("VALIDATION_ERROR");
});
});
describe("taxonomy_delete_term (bug #13 / F12)", () => {
let db: Kysely<Database>;
let harness: McpHarness;
beforeEach(async () => {
db = await setupTestDatabase();
await setupTaxonomy(db, { name: "tags", label: "Tags" });
harness = await connectMcpHarness({ db, userId: ADMIN_ID, userRole: Role.ADMIN });
});
afterEach(async () => {
if (harness) await harness.cleanup();
await teardownTestDatabase(db);
});
it("rejects deletion when children exist (matches handler behavior)", async () => {
const parent = await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "parent", label: "Parent" },
});
const { term } = extractJson<{ term: { id: string } }>(parent);
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "child", label: "Child", parentId: term.id },
});
const result = await harness.client.callTool({
name: "taxonomy_delete_term",
arguments: { taxonomy: "tags", termSlug: "parent" },
});
expect(result.isError).toBe(true);
expect(extractText(result)).toMatch(/VALIDATION_ERROR|children/i);
});
it("deletes a leaf term and the row is actually gone", async () => {
await harness.client.callTool({
name: "taxonomy_create_term",
arguments: { taxonomy: "tags", slug: "leaf", label: "Leaf" },
});
// Pre-condition: the term is listable.
const before = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "tags" },
});
const beforeSlugs = extractJson<{ items: Array<{ slug: string }> }>(before).items.map(
(t) => t.slug,
);
expect(beforeSlugs).toContain("leaf");
const result = await harness.client.callTool({
name: "taxonomy_delete_term",
arguments: { taxonomy: "tags", termSlug: "leaf" },
});
expect(result.isError, extractText(result)).toBeFalsy();
// Post-condition: the term is no longer listable. A regression where
// the handler returns success: true without actually deleting the row
// fails this assertion.
const after = await harness.client.callTool({
name: "taxonomy_list_terms",
arguments: { taxonomy: "tags" },
});
const afterSlugs = extractJson<{ items: Array<{ slug: string }> }>(after).items.map(
(t) => t.slug,
);
expect(afterSlugs).not.toContain("leaf");
});
});