typescript-sdk/scripts/fetch-spec-types.ts

91 lines
3.1 KiB
TypeScript

import { writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as prettier from 'prettier';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PROJECT_ROOT = join(__dirname, '..');
interface GitHubCommit {
sha: string;
}
async function fetchLatestSHA(): Promise<string> {
const url = 'https://api.github.com/repos/modelcontextprotocol/modelcontextprotocol/commits?path=schema/draft/schema.ts&per_page=1';
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch commit info: ${response.status} ${response.statusText}`);
}
const commits = (await response.json()) as GitHubCommit[];
if (!commits || commits.length === 0) {
throw new Error('No commits found');
}
return commits[0].sha;
}
async function fetchSpecTypes(sha: string): Promise<string> {
const url = `https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/${sha}/schema/draft/schema.ts`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch spec types: ${response.status} ${response.statusText}`);
}
return await response.text();
}
async function main() {
try {
// Check if SHA is provided as command line argument
const providedSHA = process.argv[2];
let latestSHA: string;
if (providedSHA) {
console.log(`Using provided SHA: ${providedSHA}`);
latestSHA = providedSHA;
} else {
console.log('Fetching latest commit SHA...');
latestSHA = await fetchLatestSHA();
}
console.log(`Fetching spec.types.ts from commit: ${latestSHA}`);
const specContent = await fetchSpecTypes(latestSHA);
// Read header template
const headerTemplate = `/**
* This file is automatically generated from the Model Context Protocol specification.
*
* Source: https://github.com/modelcontextprotocol/modelcontextprotocol
* Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts
* Last updated from commit: {SHA}
*
* DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates.
* To update this file, run: pnpm run fetch:spec-types
*/`;
const header = headerTemplate.replace('{SHA}', latestSHA);
// Combine header and content
const fullContent = header + specContent;
// Format with prettier using the project's config so the output passes lint
const outputPath = join(PROJECT_ROOT, 'packages', 'core', 'src', 'types', 'spec.types.ts');
const prettierConfig = await prettier.resolveConfig(outputPath);
const formatted = await prettier.format(fullContent, { ...prettierConfig, filepath: outputPath });
writeFileSync(outputPath, formatted, 'utf-8');
console.log('Successfully updated packages/core/src/types/spec.types.ts');
} catch (error) {
console.error('Error:', error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
main();