-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsite-mcp-server.ts
More file actions
1127 lines (1045 loc) · 35.9 KB
/
website-mcp-server.ts
File metadata and controls
1127 lines (1045 loc) · 35.9 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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Minimal MCP server for this website repo
// Provides site-aware tools: list/search/get content, build helpers
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
CallToolResultSchema,
ListToolsRequestSchema,
ListToolsResultSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
import matter from "gray-matter";
import { spawn } from "child_process";
// Optional pinyin import (lazy) to transliterate Chinese titles to ASCII slugs
let pinyinFn: ((input: string, opts?: any) => string) | null = null;
async function ensurePinyin() {
if (pinyinFn) return pinyinFn;
try {
const mod = await import("pinyin-pro");
pinyinFn = (mod as any).pinyin || (mod as any).default || null;
} catch {
pinyinFn = null; // acceptable; we'll fallback to basic kebab
}
return pinyinFn;
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Resolve repo root: env override -> CWD two levels up from tools/mcp -> process.cwd()
const REPO_ROOT = process.env.WEBSITE_ROOT
|| path.resolve(__dirname, "../../")
|| process.cwd();
const CONTENT_DIR = path.join(REPO_ROOT, "content");
type PageInfo = {
file: string; // absolute path
rel: string; // repo-relative path
url: string; // site-relative URL (best-effort)
lang?: string;
type?: string;
title?: string;
date?: string;
lastmod?: string;
};
function toRepoRel(abs: string): string {
return path.relative(REPO_ROOT, abs);
}
function toSiteUrl(rel: string): string {
// Convert content file path to site URL, e.g.
// content/zh/blog/slug/index.md -> /zh/blog/slug/
// content/en/book/book-name/ch1.md -> /en/book/book-name/ch1/
const noPrefix = rel.replace(/^content\//, "");
const parts = noPrefix.split(path.sep);
if (parts.length === 0) return "/";
// Drop filename and replace with trailing slash
const file = parts.pop() || "";
const withoutExt = file.replace(/\.(md|markdown)$/i, "");
// If index.md -> drop; else keep filename segment
if (!/^index\.(md|markdown)$/i.test(file) && withoutExt) parts.push(withoutExt);
return "/" + parts.join("/") + "/";
}
async function readFrontmatter(abs: string) {
try {
const raw = await fs.readFile(abs, "utf8");
const fm = matter(raw);
return fm.data || {};
} catch {
return {} as Record<string, unknown>;
}
}
async function walkMarkdown(dir: string, max = 5000): Promise<string[]> {
const out: string[] = [];
async function walk(d: string) {
const entries = await fs.readdir(d, { withFileTypes: true });
for (const e of entries) {
if (out.length >= max) return;
const p = path.join(d, e.name);
if (e.isDirectory()) {
// Skip build and cache dirs
if (["public", "node_modules", ".git", "resources", ".hugo_build"].includes(e.name)) continue;
await walk(p);
} else if (/\.(md|markdown)$/i.test(e.name)) {
out.push(p);
}
}
}
await walk(dir);
return out;
}
async function indexPages(filter?: { lang?: string; type?: string; limit?: number; base?: string }) {
const base = filter?.base || CONTENT_DIR;
let root = base;
if (filter?.lang) root = path.join(root, filter.lang);
if (filter?.type) root = path.join(root, filter.type);
const files = await walkMarkdown(root, filter?.limit || 5000);
const pages: PageInfo[] = [];
for (const f of files) {
const rel = toRepoRel(f);
const url = toSiteUrl(rel);
const fm = await readFrontmatter(f);
// Infer lang/type from path
const relParts = rel.split(path.sep);
const lang = relParts[1];
const type = relParts[2];
pages.push({
file: f,
rel,
url,
lang,
type,
title: typeof fm.title === "string" ? (fm.title as string) : undefined,
date: typeof fm.date === "string" ? (fm.date as string) : undefined,
lastmod: typeof fm.lastmod === "string" ? (fm.lastmod as string) : undefined,
});
}
return pages;
}
async function searchInFile(abs: string, query: string): Promise<{ count: number; firstLine?: number; snippet?: string }>
{
try {
const raw = await fs.readFile(abs, "utf8");
const idx = raw.toLowerCase().indexOf(query.toLowerCase());
if (idx < 0) return { count: 0 };
// crude count
const count = raw.toLowerCase().split(query.toLowerCase()).length - 1;
// snippet
const start = Math.max(0, idx - 80);
const end = Math.min(raw.length, idx + 200);
const snippet = raw.slice(start, end).replace(/\n/g, " ");
const firstLine = raw.slice(0, idx).split(/\n/).length;
return { count, firstLine, snippet };
} catch {
return { count: 0 };
}
}
async function runNpm(script: string, args: string[] = [], cwd = REPO_ROOT) {
return new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve) => {
const child = spawn("npm", ["run", script, "--", ...args], { cwd, shell: process.platform === "win32" });
let stdout = "";
let stderr = "";
child.stdout.on("data", (d) => (stdout += d.toString()));
child.stderr.on("data", (d) => (stderr += d.toString()));
child.on("close", (code) => resolve({ code, stdout, stderr }));
});
}
async function runHugo(args: string[], cwd = REPO_ROOT) {
return new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve) => {
const child = spawn("hugo", args, { cwd, shell: process.platform === "win32" });
let stdout = "";
let stderr = "";
child.stdout.on("data", (d) => (stdout += d.toString()));
child.stderr.on("data", (d) => (stderr += d.toString()));
child.on("close", (code) => resolve({ code, stdout, stderr }));
});
}
function hasCJK(str: string) {
return /[\u3400-\u9FFF]/.test(str);
}
function kebab(str: string) {
return str
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^A-Za-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.replace(/-{2,}/g, "-")
.toLowerCase();
}
function mergeAsciiRunsFromTitleIntoSlug(title: string, slug: string): string {
// Preserve ASCII alnum runs (e.g., AI, GPU, K8s) as contiguous tokens in the slug
const asciiRuns = Array.from(title.matchAll(/[A-Za-z0-9]{2,}/g)).map((m) => m[0].toLowerCase());
let out = slug;
for (const run of asciiRuns) {
const hyphenated = run.split("").join("-"); // e.g., a-i or g-p-u
out = out.replace(new RegExp(`(^|-)${hyphenated}(-|$)`, "g"), `$1${run}$2`);
}
return out;
}
// Enhanced CN->EN term dictionary for slugs with semantic understanding
const EN_TERM_MAP: Record<string, string> = {
// Companies & Products
"阿里云": "aliyun",
"腾讯云": "tencent-cloud",
"华为云": "huawei-cloud",
"百度云": "baidu-cloud",
"字节跳动": "bytedance",
"微软": "microsoft",
"谷歌": "google",
"苹果": "apple",
"亚马逊": "amazon",
"阿里巴巴": "alibaba",
"腾讯": "tencent",
"无影": "wuying",
"光冈": "mitsuoka",
"光冈汽车": "mitsuoka-motor",
// Content Types
"介绍": "intro",
"简介": "intro",
"概述": "overview",
"教程": "tutorial",
"指南": "guide",
"手册": "handbook",
"演示": "demo",
"示例": "examples",
"案例": "case-study",
"对比": "comparison",
"比较": "comparison",
"评测": "review",
"测评": "review",
"评估": "evaluation",
"分析": "analysis",
"实战": "practical",
"实践": "practice",
"体验": "experience",
"总结": "summary",
"小结": "summary",
"参考": "reference",
"参考资料": "references",
"常见问题": "faq",
"问答": "qna",
"帮助": "help",
// Technical Terms
"架构": "architecture",
"设计": "design",
"原理": "concepts",
"理论": "theory",
"算法": "algorithm",
"协议": "protocol",
"标准": "standard",
"规范": "specification",
"模式": "pattern",
"方法": "method",
"策略": "strategy",
"方案": "solution",
"解决方案": "solution",
"技术": "technology",
"技巧": "tips",
"最佳实践": "best-practices",
"实用技巧": "practical-tips",
// Operations
"部署": "deployment",
"安装": "installation",
"配置": "configuration",
"设置": "setup",
"启动": "startup",
"运行": "running",
"管理": "management",
"维护": "maintenance",
"更新": "update",
"升级": "upgrade",
"迁移": "migration",
"备份": "backup",
"恢复": "recovery",
"发布": "release",
"变更": "changes",
"修复": "fix",
"故障排除": "troubleshooting",
"调试": "debugging",
// Cloud Native & DevOps
"云原生": "cloud-native",
"容器": "containers",
"容器化": "containerization",
"服务网格": "service-mesh",
"微服务": "microservices",
"可观测性": "observability",
"监控": "monitoring",
"日志": "logging",
"追踪": "tracing",
"度量": "metrics",
"性能": "performance",
"优化": "optimization",
"扩展": "scaling",
"弹性": "elasticity",
"高可用": "high-availability",
"负载均衡": "load-balancing",
"自动化": "automation",
"持续集成": "ci",
"持续部署": "cd",
"流水线": "pipeline",
// Security
"安全": "security",
"认证": "authentication",
"授权": "authorization",
"加密": "encryption",
"证书": "certificate",
"密钥": "key",
"令牌": "token",
"防火墙": "firewall",
"网关": "gateway",
// Development
"开发": "development",
"编程": "programming",
"代码": "code",
"框架": "framework",
"库": "library",
"工具": "tools",
"工具链": "toolchain",
"平台": "platform",
"环境": "environment",
"测试": "testing",
"单元测试": "unit-testing",
"集成测试": "integration-testing",
"版本控制": "version-control",
// Business & General
"公告": "announcement",
"通知": "notice",
"新闻": "news",
"动态": "updates",
"趋势": "trends",
"预测": "prediction",
"未来": "future",
"创新": "innovation",
"生态": "ecosystem",
"生态系统": "ecosystem",
"社区": "community",
"合作": "collaboration",
"伙伴": "partner",
"客户": "customer",
"用户": "user",
"市场": "market",
"行业": "industry",
"企业": "enterprise",
"商业": "business",
"产品": "product",
"服务": "service",
"项目": "project",
"计划": "plan",
"目标": "goal",
"成果": "result",
"效果": "effect",
"影响": "impact",
// Time & Events
"年度": "annual",
"月度": "monthly",
"周报": "weekly",
"日报": "daily",
"报告": "report",
"回顾": "review",
"展望": "outlook",
"会议": "conference",
"峰会": "summit",
"活动": "event",
"发布会": "launch",
// Automotive (for the car blog example)
"汽车": "automotive",
"车型": "models",
"品牌": "brand",
"制造商": "manufacturer",
"厂商": "vendor",
"跑车": "sports-car",
"轿车": "sedan",
"SUV": "suv",
"电动车": "electric-vehicle",
"混合动力": "hybrid",
"发动机": "engine",
"变速箱": "transmission",
"底盘": "chassis",
"外观": "exterior",
"内饰": "interior",
"配件": "accessories",
"改装": "modification",
"定制": "customization",
"复古": "retro",
"经典": "classic",
"豪华": "luxury",
"驾驶": "driving",
"试驾": "test-drive",
"选购": "buying-guide",
"保养": "maintenance",
"维修": "repair",
// Digital & AI
"数字化": "digitalization",
"数字": "digital",
"信息": "information",
"获取": "acquisition",
"数据": "data",
"人工智能": "artificial-intelligence",
"机器学习": "machine-learning",
"深度学习": "deep-learning",
"神经网络": "neural-network",
"模型": "model",
"训练": "training",
"推理": "inference",
"分类": "classification",
"聚类": "clustering",
"自然语言处理": "natural-language-processing",
"计算机视觉": "computer-vision",
"语音识别": "speech-recognition",
"图像识别": "image-recognition",
"推荐系统": "recommendation-system",
"搜索": "search",
"检索": "retrieval",
"索引": "indexing",
"排序": "ranking",
"过滤": "filtering",
"统计": "statistics",
"可视化": "visualization",
"仪表板": "dashboard",
"报表": "report",
// Countries & Locations
"日本": "japan",
"中国": "china",
"美国": "usa",
"欧洲": "europe",
"亚洲": "asia",
// Common tech terms (case-sensitive for proper nouns)
"Kubernetes": "kubernetes",
"Docker": "docker",
"Istio": "istio",
"Helm": "helm",
"Prometheus": "prometheus",
"Grafana": "grafana",
"Jenkins": "jenkins",
"GitLab": "gitlab",
"GitHub": "github",
"Redis": "redis",
"MySQL": "mysql",
"PostgreSQL": "postgresql",
"MongoDB": "mongodb",
"Elasticsearch": "elasticsearch",
"Kafka": "kafka",
"RabbitMQ": "rabbitmq",
"Nginx": "nginx",
"Apache": "apache",
"Linux": "linux",
"Ubuntu": "ubuntu",
"CentOS": "centos",
"RHEL": "rhel",
"AWS": "aws",
"Azure": "azure",
"GCP": "gcp",
};
const EN_TERM_KEYS_DESC = Object.keys(EN_TERM_MAP).sort((a, b) => b.length - a.length);
function toEnglishSlugFromDict(title: string): string {
const tokens: string[] = [];
let i = 0;
// Preprocess: normalize punctuation and whitespace
const normalized = title
.replace(/[::]/g, " ")
.replace(/[,,]/g, " ")
.replace(/[、]/g, " ")
.replace(/[()()]/g, " ")
.replace(/[【】\[\]]/g, " ")
.replace(/[《》<>]/g, " ")
.replace(/[""""""]/g, " ")
.replace(/\s+/g, " ")
.trim();
while (i < normalized.length) {
const ch = normalized[i];
// Skip whitespace
if (/\s/.test(ch)) {
i++;
continue;
}
// ASCII or digits: capture contiguous run
if (/^[A-Za-z0-9]$/.test(ch)) {
let j = i + 1;
while (j < normalized.length && /^[A-Za-z0-9]$/.test(normalized[j])) j++;
const token = normalized.slice(i, j).toLowerCase();
tokens.push(token);
i = j;
continue;
}
// Try longest-match CN term (greedy matching)
let matched = false;
for (const key of EN_TERM_KEYS_DESC) {
if (normalized.startsWith(key, i)) {
const englishTerm = EN_TERM_MAP[key];
// Avoid adding duplicate or overly generic terms
if (!tokens.includes(englishTerm) && englishTerm !== "intro" && englishTerm !== "guide") {
tokens.push(englishTerm);
} else if (tokens.length === 0) {
// If no tokens yet, allow even generic terms
tokens.push(englishTerm);
}
i += key.length;
matched = true;
break;
}
}
if (!matched) {
// Check for single character mappings or skip
const singleChar = normalized[i];
if (EN_TERM_MAP[singleChar]) {
const term = EN_TERM_MAP[singleChar];
if (!tokens.includes(term)) {
tokens.push(term);
}
i++;
} else {
i++; // skip unknown char
}
}
}
// Post-process: clean up and merge
const filtered = tokens
.filter(Boolean)
.filter(token => token.length > 0)
.filter(token => !/^[0-9]+$/.test(token) || token.length <= 4); // Keep short numbers
// Try to create more meaningful combinations
const priorityTerms: string[] = [];
const descriptiveTerms: string[] = [];
const actionTerms: string[] = [];
for (const token of filtered) {
if (["comparison", "intro", "guide", "tutorial", "analysis", "review", "acquisition"].includes(token)) {
actionTerms.push(token);
} else if (["digital", "information", "automotive", "mitsuoka", "aliyun", "technology", "japan"].includes(token)) {
priorityTerms.push(token);
} else {
descriptiveTerms.push(token);
}
}
// Combine terms intelligently
let finalTokens = [...priorityTerms, ...descriptiveTerms];
// Add action term if we have specific content
if (finalTokens.length > 0 && actionTerms.length > 0) {
finalTokens.push(actionTerms[0]);
} else if (finalTokens.length === 0) {
finalTokens = [...actionTerms];
}
const raw = finalTokens.join("-");
return kebab(raw);
}
async function toSeoSlug(title: string, description?: string) {
const t = (title || "").trim();
if (!t) return "post-" + Date.now();
if (hasCJK(t)) {
// Enhanced Chinese to English slug generation
const combinedText = description ? `${t} ${description}` : t;
let slug = toEnglishSlugFromDict(combinedText);
// If dictionary approach fails or produces generic result, try alternative strategies
if (!slug || slug.length < 3 || ["intro", "guide", "post"].includes(slug)) {
// Extract meaningful terms from title
const titleSlug = toEnglishSlugFromDict(t);
// Try to identify the main subject/topic
const hasCompanyName = /阿里|腾讯|华为|百度|微软|谷歌|苹果|亚马逊|光冈/.test(t);
const hasTechTerm = /云原生|容器|微服务|服务网格|可观测性|人工智能|机器学习|深度学习/.test(t);
const hasCarTerm = /汽车|车型|跑车|轿车|电动车|发动机|品牌|制造商/.test(t);
// Add context-specific prefixes/suffixes
if (hasCompanyName && !hasTechTerm && !hasCarTerm) {
slug = titleSlug || "company-intro";
} else if (hasTechTerm) {
slug = titleSlug || "tech-guide";
} else if (hasCarTerm) {
slug = titleSlug || "automotive-guide";
} else {
slug = titleSlug || "article";
}
}
// Preserve ASCII runs from original title
slug = mergeAsciiRunsFromTitleIntoSlug(t, slug);
// Ensure slug is not too generic
if (["post", "article", "guide", "intro"].includes(slug)) {
const timestamp = new Date().getFullYear().toString().slice(-2) +
String(new Date().getMonth() + 1).padStart(2, '0');
slug = `${slug}-${timestamp}`;
}
return slug || ("post-" + Date.now());
}
// For English titles
let slug = kebab(t);
slug = mergeAsciiRunsFromTitleIntoSlug(t, slug);
return slug || ("post-" + Date.now());
}
function ensureKebabSlug(input?: string | null) {
const s = (input || "").trim();
if (!s) return null;
const out = kebab(s);
return out || null;
}
function beijingNowIso() {
// Format current time to Asia/Shanghai (+08:00) ISO-like string without converting wall time
const now = new Date();
// Derive local in +08 by adding timezone delta to emulate CN time
const utc = now.getTime() + now.getTimezoneOffset() * 60000;
const bj = new Date(utc + 8 * 3600000);
const pad = (n: number) => String(n).padStart(2, "0");
const yyyy = bj.getFullYear();
const MM = pad(bj.getMonth() + 1);
const dd = pad(bj.getDate());
const hh = pad(bj.getHours());
const mm = pad(bj.getMinutes());
const ss = pad(bj.getSeconds());
return `${yyyy}-${MM}-${dd}T${hh}:${mm}:${ss}+08:00`;
}
async function ensureUniquePath(baseDir: string, slug: string) {
// Ensure directory content/<lang>/<type>/<slug> is unique by appending -1, -2, ...
let candidate = slug;
let i = 1;
while (true) {
const dir = path.join(baseDir, candidate);
try {
await fs.access(dir);
// exists; try next
i += 1; candidate = `${slug}-${i}`;
} catch {
return candidate;
}
}
}
async function updateFrontMatterTitle(absFile: string, title: string) {
try {
const raw = await fs.readFile(absFile, "utf8");
const fm = matter(raw);
const data = { ...(fm.data || {}) } as Record<string, unknown>;
data.title = title;
const out = matter.stringify(fm.content, data as any);
await fs.writeFile(absFile, out, "utf8");
return true;
} catch {
return false;
}
}
// Build a tool registry and wire MCP handlers (tools/list, tools/call)
type ToolExec = (args: any) => Promise<{
content: Array<{ type: "text"; text: string }>;
}>;
const tools: Record<
string,
{
description: string;
inputSchema: Record<string, any>;
execute: ToolExec;
}
> = {
list_content: {
description: "List content markdown pages with basic metadata",
inputSchema: {
type: "object",
properties: {
lang: { type: "string", enum: ["zh", "en"] },
type: { type: "string" },
limit: { type: "integer", minimum: 1, maximum: 5000 },
},
},
execute: async (args: { lang?: string; type?: string; limit?: number }) => {
const pages = await indexPages({ lang: args.lang as any, type: args.type, limit: args.limit ?? 200 });
return { content: [{ type: "text", text: JSON.stringify(pages, null, 2) }] };
},
},
get_page: {
description: "Get a page by repo-relative or content-relative path",
inputSchema: {
type: "object",
properties: {
path: { type: "string", description: "Path like content/zh/blog/slug/index.md or zh/blog/slug/index.md" },
},
required: ["path"],
},
execute: async (args: { path: string }) => {
const p = args.path;
const rel = p.startsWith("content/") ? p : path.join("content", p);
const abs = path.join(REPO_ROOT, rel);
const data = await fs.readFile(abs, "utf8");
return { content: [{ type: "text", text: data }] };
},
},
search_content: {
description: "Search markdown content for a query and return ranked matches",
inputSchema: {
type: "object",
properties: {
query: { type: "string", minLength: 2 },
lang: { type: "string", enum: ["zh", "en"] },
type: { type: "string" },
limit: { type: "integer", minimum: 1, maximum: 200 },
},
required: ["query"],
},
execute: async (args: { query: string; lang?: string; type?: string; limit?: number }) => {
const { query, lang, type, limit = 50 } = args;
const pages = await indexPages({ lang: lang as any, type, limit: 2000 });
const scored: Array<PageInfo & { score: number; snippet?: string; line?: number }> = [];
for (const p of pages) {
const res = await searchInFile(p.file, query);
if (res.count > 0) scored.push({ ...p, score: res.count, snippet: res.snippet, line: res.firstLine });
}
scored.sort((a, b) => b.score - a.score);
const top = scored.slice(0, limit);
return { content: [{ type: "text", text: JSON.stringify(top, null, 2) }] };
},
},
page_url: {
description: "Compute site URL for a given content path",
inputSchema: {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
},
execute: async (args: { path: string }) => {
const p = args.path;
const rel = p.startsWith("content/") ? p : path.join("content", p);
const url = toSiteUrl(rel);
return { content: [{ type: "text", text: url }] };
},
},
suggest_slug: {
description: "Suggest an English kebab-case slug from title/description using AI if configured; otherwise local heuristic",
inputSchema: {
type: "object",
properties: {
title: { type: "string", minLength: 2 },
description: { type: "string" },
lang: { type: "string", enum: ["zh", "en"], default: "zh" },
maxWords: { type: "integer", minimum: 1, maximum: 12, default: 6 },
},
required: ["title"],
},
execute: async (args: { title: string; description?: string; lang?: string; maxWords?: number }) => {
const { title, description = "", maxWords = 6 } = args;
const suggested = await suggestSlugAI(title, description, maxWords);
const fallback = await toSeoSlug(title, description);
const slug = ensureKebabSlug(suggested) || fallback;
return { content: [{ type: "text", text: JSON.stringify({ slug }, null, 2) }] };
},
},
open_in_editor_link: {
description: "Return local file-editor URL for dev helper (requires make server)",
inputSchema: {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
},
execute: async (args: { path: string }) => {
const p = args.path;
const rel = p.startsWith("content/") ? p : path.join("content", p);
const abs = path.join(REPO_ROOT, rel);
const url = new URL("http://localhost:8089/open");
url.searchParams.set("file", abs);
return { content: [{ type: "text", text: url.toString() }] };
},
},
run_task: {
description: "Run a documented project task (generate-analysis, upload-images, check-image-dimensions)",
inputSchema: {
type: "object",
properties: {
task: { type: "string", enum: ["generate-analysis", "upload-images", "check-image-dimensions"] },
args: { type: "array", items: { type: "string" } },
},
required: ["task"],
},
execute: async (args: { task: string; args?: string[] }) => {
const res = await runNpm(args.task, args.args || []);
const ok = res.code === 0;
return {
content: [
{
type: "text",
text: JSON.stringify(
{ ok, code: res.code, stdout: res.stdout.slice(0, 8000), stderr: res.stderr.slice(0, 8000) },
null,
2
),
},
],
};
},
},
create_content: {
description:
"Plan or create new content with an SEO-friendly slug. Defaults to planOnly; set write=true to create once with the suggested content.",
inputSchema: {
type: "object",
properties: {
type: { type: "string", enum: ["blog", "book", "podcast", "notice", "trans", "ai", "slide", "publication"] },
title: { type: "string", minLength: 2, description: "The human title/topic (Chinese or English)" },
lang: { type: "string", enum: ["zh", "en"] },
parent: { type: "string" },
slug: { type: "string", description: "Manual slug override (kebab-case). If provided, takes precedence." },
useAI: { type: "boolean", description: "If true and slug is not provided, try AI to propose an English slug", default: false },
description: { type: "string", description: "Optional content synopsis to guide AI slug suggestion" },
write: { type: "boolean", description: "If true, will write the planned content once (no hugo new)", default: false },
content: { type: "string", description: "Optional full file content to write instead of the recommended template when write=true" },
},
required: ["type", "title", "lang"],
},
execute: async (args: { type: string; title: string; lang: string; parent?: string; slug?: string; write?: boolean; content?: string; description?: string }) => {
const { type, title, lang, parent, slug: slugOverride, write = false, content, description } = args;
// Compute slug and target path
const manual = ensureKebabSlug(slugOverride);
const slugRaw = manual || (await toSeoSlug(title, description));
const typeBase = path.join(REPO_ROOT, "content", lang, type);
const baseDir = parent ? path.join(typeBase, parent) : typeBase;
const uniqueSlug = await ensureUniquePath(baseDir, slugRaw);
const relDir = path.join("content", lang, type, parent ?? "", uniqueSlug);
const relPath = path.join(relDir, "index.md");
const absPath = path.join(REPO_ROOT, relPath);
const url = toSiteUrl(relPath);
// Build recommended content (blog-friendly defaults)
const date = beijingNowIso();
const fm: Record<string, unknown> = {
title,
linktitle: "",
date,
lastmod: date,
draft: false,
slug: uniqueSlug,
comment: true,
banner_image: `https://assets.jimmysong.io/images/blog/${uniqueSlug}/banner.webp`,
description: "",
};
const yaml =
"---\n" +
Object.entries(fm)
.map(([k, v]) => {
if (Array.isArray(v)) return `${k}:\n` + v.map((it) => ` - ${it}`).join("\n");
if (typeof v === "boolean") return `${k}: ${v ? "true" : "false"}`;
return `${k}: ${JSON.stringify(v)} `;
})
.join("\n") +
"\n---\n";
const bodyTemplate = [
"\n",
lang === "zh" ? "本文介绍主题背景与关键要点。" : "This article introduces the topic and key points.",
"\n\n## ",
lang === "zh" ? "背景" : "Background",
"\n\n",
lang === "zh" ? "在此阐述背景、问题与目标。" : "Explain context, problems, and goals.",
"\n\n## ",
lang === "zh" ? "核心能力" : "Key Capabilities",
"\n\n- ...\n\n## ",
lang === "zh" ? "应用场景" : "Use Cases",
"\n\n- ...\n\n## ",
lang === "zh" ? "总结" : "Summary",
"\n\n",
lang === "zh" ? "对全文进行简要总结。" : "Summarize the key points.",
"\n\n## ",
lang === "zh" ? "References" : "References",
"\n\n- [Title - domain]()\n",
].join("");
const recommendedContent = yaml + bodyTemplate;
if (!write) {
return {
content: [
{
type: "text",
text: JSON.stringify(
{ ok: true, planOnly: true, slug: uniqueSlug, relDir, relPath, absPath, url, recommendedContent },
null,
2
),
},
],
};
}
await fs.mkdir(path.dirname(absPath), { recursive: true });
await fs.writeFile(absPath, content ?? recommendedContent, "utf8");
return {
content: [
{ type: "text", text: JSON.stringify({ ok: true, written: true, relPath, absPath, url }, null, 2) },
],
};
},
},
plan_new_content: {
description:
"Plan a new content file without writing. Returns slug, paths, URL, and a recommended front matter + body template to write via filesystem.",
inputSchema: {
type: "object",
properties: {
type: { type: "string", enum: ["blog", "book", "podcast", "notice", "trans", "ai", "slide", "publication"] },
title: { type: "string", minLength: 2 },
lang: { type: "string", enum: ["zh", "en"] },
parent: { type: "string" },
slug: { type: "string", description: "Manual slug override (kebab-case). If provided, takes precedence." },
},
required: ["type", "title", "lang"],
},
execute: async (args: { type: string; title: string; lang: string; parent?: string; slug?: string }) => {
const { type, title, lang, parent, slug: slugOverride } = args;
const manual = ensureKebabSlug(slugOverride);
const slugRaw = manual || (await toSeoSlug(title));
const typeBase = path.join(REPO_ROOT, "content", lang, type);
const baseDir = parent ? path.join(typeBase, parent) : typeBase;
const uniqueSlug = await ensureUniquePath(baseDir, slugRaw);
const relDir = path.join("content", lang, type, parent ?? "", uniqueSlug);
const relPath = path.join(relDir, "index.md");
const absPath = path.join(REPO_ROOT, relPath);
const url = toSiteUrl(relPath);
// Build a recommended front matter for blog type (others minimal)
const date = beijingNowIso();
const fm: Record<string, unknown> = {
title,
linktitle: "",
date,
lastmod: date,
draft: false,
slug: uniqueSlug,
};
if (type === "blog") {
fm.categories = ["技术"];
fm.tags = ["示例"];
fm.comment = true;
fm.banner_image = `https://assets.jimmysong.io/images/blog/${uniqueSlug}/banner.webp`;
fm.description = "";
}
const yaml =
"---\n" +
// Simple YAML emitter for our flat structure
Object.entries(fm)
.map(([k, v]) => {
if (Array.isArray(v)) return `${k}:\n` + v.map((it) => ` - ${it}`).join("\n");
if (typeof v === "boolean") return `${k}: ${v ? "true" : "false"}`;
return `${k}: ${JSON.stringify(v)} `;
})
.join("\n") +
"\n---\n";
const bodyTemplate = [
"\n",
lang === "zh" ? "本文介绍主题背景与关键要点。" : "This article introduces the topic and key points.",
"\n\n## ",
lang === "zh" ? "背景" : "Background",
"\n\n",
lang === "zh" ? "在此阐述背景、问题与目标。" : "Explain context, problems, and goals.",
"\n\n## ",
lang === "zh" ? "核心能力" : "Key Capabilities",
"\n\n- ...\n\n## ",
lang === "zh" ? "应用场景" : "Use Cases",
"\n\n- ...\n\n## ",
lang === "zh" ? "总结" : "Summary",
"\n\n",
lang === "zh" ? "对全文进行简要总结。" : "Summarize the key points.",
"\n\n## ",
lang === "zh" ? "References" : "References",
"\n\n- [Title - domain]()\n",
].join("");
const suggested = yaml + bodyTemplate;
return {
content: [
{
type: "text",
text: JSON.stringify(
{