-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathrender-seps.ts
More file actions
447 lines (378 loc) · 14.9 KB
/
render-seps.ts
File metadata and controls
447 lines (378 loc) · 14.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
#!/usr/bin/env tsx
/**
* Script to render SEPs (Specification Enhancement Proposals) into Mintlify docs format.
*
* This script:
* 1. Reads all SEP markdown files from the seps/ directory
* 2. Parses their metadata (title, status, type, authors, etc.)
* 3. Generates an index page with a tabular overview
* 4. Generates individual MDX files for each SEP in docs/seps/
*
* Usage: npx tsx scripts/render-seps.ts [--check]
* --check: Verify generated files are up to date (exit 1 if not)
*/
import * as fs from "fs";
import * as path from "path";
import { execFileSync } from "child_process";
const npx = process.platform === "win32" ? "npx.cmd" : "npx";
const SEPS_DIR = path.join(__dirname, "..", "seps");
const DOCS_SEPS_DIR = path.join(__dirname, "..", "docs", "seps");
const DOCS_JSON_PATH = path.join(__dirname, "..", "docs", "docs.json");
interface SEPMetadata {
number: string;
title: string;
status: string;
type: string;
created: string;
accepted?: string;
authors: string;
sponsor: string;
prNumber: string;
slug: string;
filename: string;
}
/**
* Parse SEP metadata from markdown content
*/
function parseSEPMetadata(content: string, filename: string): SEPMetadata | null {
// Skip template, README, and 0000- placeholder drafts
if (filename === "TEMPLATE.md" || filename === "README.md" || filename.startsWith("0000-")) {
return null;
}
// Extract SEP number and slug from filename (e.g., "1850-pr-based-sep-workflow.md")
const filenameMatch = filename.match(/^(\d+)-(.+)\.md$/);
if (!filenameMatch) {
console.warn(`Warning: Skipping ${filename} - doesn't match SEP naming convention`);
return null;
}
const [, number, slug] = filenameMatch;
// Parse title from first heading
const titleMatch = content.match(/^#\s+SEP-\d+:\s+(.+)$/m);
const title = titleMatch ? titleMatch[1].trim() : "Untitled";
// Parse metadata fields using regex
const statusMatch = content.match(/^\s*-\s*\*\*Status\*\*:\s*(.+)$/m);
const typeMatch = content.match(/^\s*-\s*\*\*Type\*\*:\s*(.+)$/m);
const createdMatch = content.match(/^\s*-\s*\*\*Created\*\*:\s*(.+)$/m);
const acceptedMatch = content.match(/^\s*-\s*\*\*Accepted\*\*:\s*(.+)$/m);
const authorsMatch = content.match(/^\s*-\s*\*\*Author\(s\)\*\*:\s*(.+)$/m);
const sponsorMatch = content.match(/^\s*-\s*\*\*Sponsor\*\*:\s*(.+)$/m);
const prMatch = content.match(/^\s*-\s*\*\*PR\*\*:.*?(?:#|\/pull\/)(\d+)/m);
return {
number,
title,
status: statusMatch ? statusMatch[1].trim() : "Unknown",
type: typeMatch ? typeMatch[1].trim() : "Unknown",
created: createdMatch ? createdMatch[1].trim() : "Unknown",
accepted: acceptedMatch ? acceptedMatch[1].trim() : undefined,
authors: authorsMatch ? authorsMatch[1].trim() : "Unknown",
sponsor: sponsorMatch ? sponsorMatch[1].trim() : "None",
prNumber: prMatch ? prMatch[1] : number,
slug,
filename,
};
}
/**
* Convert GitHub usernames to links
*/
function formatAuthors(authors: string): string {
return authors.replace(/@([\w-]+)/g, "[@$1](https://github.com/$1)");
}
/**
* Format PR number as a GitHub link
*/
function formatPrLink(prNumber: string): string {
return `[#${prNumber}](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/${prNumber})`;
}
/**
* Truncate title to max length, adding ellipsis if needed
*/
function truncateTitle(title: string, maxLength: number): string {
if (title.length <= maxLength) return title;
return title.slice(0, maxLength - 1).trim() + "…";
}
/**
* Get status badge color for Mintlify
*/
function getStatusBadgeColor(status: string): string {
const statusLower = status.toLowerCase();
if (statusLower === "final") return "green";
if (statusLower === "accepted") return "blue";
if (statusLower === "in-review") return "yellow";
if (statusLower === "draft") return "gray";
if (statusLower === "rejected" || statusLower === "withdrawn") return "red";
if (statusLower === "dormant") return "orange";
if (statusLower === "superseded") return "purple";
return "gray";
}
/**
* Generate MDX content for a single SEP page
*/
function generateSEPPage(sep: SEPMetadata, originalContent: string): string {
// Remove the header metadata section and title from original content for the body
// Find where the Abstract section starts
const abstractIndex = originalContent.indexOf("## Abstract");
const body = abstractIndex !== -1 ? originalContent.slice(abstractIndex) : originalContent;
return `---
title: "SEP-${sep.number}: ${sep.title}"
sidebarTitle: "SEP-${sep.number}: ${truncateTitle(sep.title, 40)}"
description: "${sep.title}"
---
<div className="flex items-center gap-2 mb-4">
<Badge color="${getStatusBadgeColor(sep.status)}" shape="pill">${sep.status}</Badge>
<Badge color="gray" shape="pill">${sep.type}</Badge>
</div>
| Field | Value |
|-------|-------|
| **SEP** | ${sep.number} |
| **Title** | ${sep.title} |
| **Status** | ${sep.status} |
| **Type** | ${sep.type} |
| **Created** | ${sep.created} |
${sep.accepted ? `| **Accepted** | ${sep.accepted} |\n` : ""}| **Author(s)** | ${formatAuthors(sep.authors)} |
| **Sponsor** | ${formatAuthors(sep.sponsor)} |
| **PR** | ${formatPrLink(sep.prNumber)} |
---
${body}
`;
}
/**
* Generate the SEP index page with tabular overview
*/
function generateIndexPage(seps: SEPMetadata[]): string {
// Sort SEPs by number (descending - newest first)
const sortedSeps = [...seps].sort((a, b) => parseInt(b.number) - parseInt(a.number));
// Group by status for summary
const byStatus = sortedSeps.reduce(
(acc, sep) => {
const status = sep.status.toLowerCase();
acc[status] = (acc[status] || 0) + 1;
return acc;
},
{} as Record<string, number>
);
// Generate table rows
const tableRows = sortedSeps
.map((sep) => {
const statusBadge = `<Badge color="${getStatusBadgeColor(sep.status)}" shape="pill">${sep.status}</Badge>`;
return `| [SEP-${sep.number}](/seps/${sep.number}-${sep.slug}) | ${sep.title} | ${statusBadge} | ${sep.type} | ${sep.created} |`;
})
.join("\n");
// Generate status summary
const statusSummary = Object.entries(byStatus)
.map(([status, count]) => `- **${status.charAt(0).toUpperCase() + status.slice(1)}**: ${count}`)
.join("\n");
return `---
title: Specification Enhancement Proposals (SEPs)
sidebarTitle: SEP Index
description: Index of all MCP Specification Enhancement Proposals
---
Specification Enhancement Proposals (SEPs) are the primary mechanism for proposing major changes to the Model Context Protocol. Each SEP provides a concise technical specification and rationale for proposed features.
<Card title="Submit a SEP" icon="file-plus" href="/community/sep-guidelines">
Learn how to submit your own Specification Enhancement Proposal
</Card>
## Summary
${statusSummary}
## All SEPs
| SEP | Title | Status | Type | Created |
|-----|-------|--------|------|---------|
${tableRows}
## SEP Status Definitions
| Status | Definition |
| --- | --- |
| <Badge color="gray" shape="pill">Draft</Badge> | SEP proposal with a sponsor, undergoing informal review |
| <Badge color="yellow" shape="pill">In-Review</Badge> | SEP proposal ready for formal review by Core Maintainers |
| <Badge color="blue" shape="pill">Accepted</Badge> | SEP accepted, awaiting reference implementation |
| <Badge color="green" shape="pill">Final</Badge> | SEP finalized with reference implementation complete |
| <Badge color="red" shape="pill">Rejected</Badge> | SEP rejected by Core Maintainers |
| <Badge color="red" shape="pill">Withdrawn</Badge> | SEP withdrawn by the author |
| <Badge color="purple" shape="pill">Superseded</Badge> | SEP replaced by a newer SEP |
| <Badge color="orange" shape="pill">Dormant</Badge> | SEP without a sponsor, closed after 6 months |
`;
}
/**
* Read all SEP files and parse their metadata
*/
function readAllSEPs(): { metadata: SEPMetadata; content: string }[] {
const files = fs.readdirSync(SEPS_DIR).filter((f) => f.endsWith(".md"));
const seps: { metadata: SEPMetadata; content: string }[] = [];
for (const file of files) {
const content = fs.readFileSync(path.join(SEPS_DIR, file), "utf-8");
const metadata = parseSEPMetadata(content, file);
if (metadata) {
seps.push({ metadata, content });
}
}
return seps;
}
/**
* Group SEPs by status for navigation
*/
function groupSepsByStatus(seps: SEPMetadata[]): Record<string, SEPMetadata[]> {
const groups: Record<string, SEPMetadata[]> = {};
// Define status order for navigation
const statusOrder = ["Final", "Accepted", "In-Review", "Draft", "Withdrawn", "Rejected", "Superseded", "Dormant"];
for (const sep of seps) {
// Normalize status to title case (handling hyphenated statuses like "In-Review")
const status = sep.status.split('-').map(word =>
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
).join('-');
if (!groups[status]) {
groups[status] = [];
}
groups[status].push(sep);
}
// Sort each group by SEP number
for (const status of Object.keys(groups)) {
groups[status].sort((a, b) => parseInt(a.number) - parseInt(b.number));
}
// Return in preferred order
const orderedGroups: Record<string, SEPMetadata[]> = {};
for (const status of statusOrder) {
if (groups[status]) {
orderedGroups[status] = groups[status];
}
}
// Add any remaining statuses not in the predefined order
for (const status of Object.keys(groups)) {
if (!orderedGroups[status]) {
orderedGroups[status] = groups[status];
}
}
return orderedGroups;
}
/**
* Update docs.json to include SEPs as a top-level tab, grouped by status
*/
function updateDocsJson(seps: SEPMetadata[]): string {
const docsJson = JSON.parse(fs.readFileSync(DOCS_JSON_PATH, "utf-8"));
// Group SEPs by status
const groupedSeps = groupSepsByStatus(seps);
// Build nested navigation structure
const sepSubgroups: Array<string | { group: string; pages: string[] }> = [];
for (const [status, statusSeps] of Object.entries(groupedSeps)) {
if (statusSeps.length === 0) continue;
const pages = statusSeps.map((sep) => `seps/${sep.number}-${sep.slug}`);
sepSubgroups.push({
group: status,
pages,
});
}
const sepsTab = {
tab: "SEPs",
pages: ["seps/index", ...sepSubgroups],
};
// Remove any legacy SEPs group from the Community tab
const communityTab = docsJson.navigation.tabs.find((tab: { tab: string }) => tab.tab === "Community");
if (communityTab) {
communityTab.pages = communityTab.pages.filter(
(item: { group?: string } | string) => !(typeof item === "object" && item.group === "SEPs")
);
}
// Find existing SEPs tab
const sepsTabIndex = docsJson.navigation.tabs.findIndex((tab: { tab: string }) => tab.tab === "SEPs");
if (sepsTabIndex >= 0) {
docsJson.navigation.tabs[sepsTabIndex] = sepsTab;
} else {
// Insert before the Community tab if present, otherwise append
const communityIndex = docsJson.navigation.tabs.findIndex((tab: { tab: string }) => tab.tab === "Community");
if (communityIndex >= 0) {
docsJson.navigation.tabs.splice(communityIndex, 0, sepsTab);
} else {
docsJson.navigation.tabs.push(sepsTab);
}
}
return JSON.stringify(docsJson, null, 2) + "\n";
}
/**
* Main function
*/
async function main() {
const checkMode = process.argv.includes("--check");
console.log("Reading SEP files...");
const seps = readAllSEPs();
console.log(`Found ${seps.length} SEP(s)`);
if (seps.length === 0) {
console.log("No SEPs found to render.");
return;
}
// Ensure output directory exists
if (!fs.existsSync(DOCS_SEPS_DIR)) {
fs.mkdirSync(DOCS_SEPS_DIR, { recursive: true });
}
// Track all expected files for check mode
const expectedFiles: { path: string; content: string }[] = [];
// Generate index page
const indexPath = path.join(DOCS_SEPS_DIR, "index.mdx");
const indexContent = generateIndexPage(seps.map((s) => s.metadata));
expectedFiles.push({ path: indexPath, content: indexContent });
// Generate individual SEP pages
for (const { metadata, content } of seps) {
const sepPath = path.join(DOCS_SEPS_DIR, `${metadata.number}-${metadata.slug}.mdx`);
const sepContent = generateSEPPage(metadata, content);
expectedFiles.push({ path: sepPath, content: sepContent });
}
// Generate updated docs.json
const docsJsonContent = updateDocsJson(seps.map((s) => s.metadata));
expectedFiles.push({ path: DOCS_JSON_PATH, content: docsJsonContent });
if (checkMode) {
// Check mode: verify all files match expected content (after formatting)
// Write to temp files, format with Prettier, then compare
const tempDir = fs.mkdtempSync(path.join(require("os").tmpdir(), "seps-check-"));
let hasChanges = false;
try {
// Write expected content to temp files
const tempFiles: { original: string; temp: string }[] = [];
for (const { path: filePath, content } of expectedFiles) {
const tempPath = path.join(tempDir, path.basename(filePath));
fs.writeFileSync(tempPath, content, "utf-8");
tempFiles.push({ original: filePath, temp: tempPath });
}
// Format MDX files with Prettier
const mdxTempFiles = tempFiles.filter(({ temp }) => temp.endsWith(".mdx")).map(({ temp }) => temp);
if (mdxTempFiles.length > 0) {
execFileSync(npx, ["prettier", "--write", ...mdxTempFiles], { stdio: "pipe" });
}
// Compare formatted temp files with existing files
for (const { original, temp } of tempFiles) {
if (!fs.existsSync(original)) {
console.error(`Missing file: ${original}`);
hasChanges = true;
continue;
}
const existing = fs.readFileSync(original, "utf-8");
const formatted = fs.readFileSync(temp, "utf-8");
if (existing !== formatted) {
console.error(`File out of date: ${original}`);
hasChanges = true;
}
}
} finally {
// Clean up temp directory
fs.rmSync(tempDir, { recursive: true, force: true });
}
if (hasChanges) {
console.error("\nSEP documentation is out of date. Run 'npm run generate:seps' to update.");
process.exit(1);
}
console.log("All SEP documentation is up to date.");
} else {
// Write mode: generate all files
for (const { path: filePath, content } of expectedFiles) {
fs.writeFileSync(filePath, content, "utf-8");
console.log(`Generated: ${path.relative(process.cwd(), filePath)}`);
}
// Format generated files with Prettier
const filesToFormat = expectedFiles
.filter(({ path: p }) => p.endsWith(".mdx"))
.map(({ path: p }) => path.relative(process.cwd(), p));
if (filesToFormat.length > 0) {
console.log("\nFormatting generated files with Prettier...");
execFileSync(npx, ["prettier", "--write", ...filesToFormat], { stdio: "inherit" });
}
console.log("\nSEP documentation generated successfully!");
}
}
main().catch((err) => {
console.error("Error:", err);
process.exit(1);
});