json_schema
Generate TypeScript schema from JSON files or URLs to validate and document data structures for development workflows.
Instructions
Generate TypeScript schema for a JSON file or remote JSON URL. Provide the file path or HTTP/HTTPS URL as the only parameter.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | JSON file path (local) or HTTP/HTTPS URL to generate schema from |
Implementation Reference
- src/index.ts:507-561 (registration)Registration of the 'json_schema' MCP tool using server.tool(). Includes tool name, description, inline input schema validation with Zod, and an async handler that validates input using JsonSchemaInputSchema, calls processJsonSchema, and formats the response.
server.tool( "json_schema", "Generate TypeScript schema for a JSON file or remote JSON URL. Provide the file path or HTTP/HTTPS URL as the only parameter.", { filePath: z.string().describe("JSON file path (local) or HTTP/HTTPS URL to generate schema from") }, async ({ filePath }) => { try { const validatedInput = JsonSchemaInputSchema.parse({ filePath: filePath }); const result = await processJsonSchema(validatedInput); if (result.success) { // Format file size for display const formatFileSize = (bytes: number): string => { if (bytes < 1024) return `${bytes} bytes`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; }; const fileSizeInfo = `// File size: ${formatFileSize(result.fileSizeBytes)} (${result.fileSizeBytes} bytes)\n\n`; return { content: [ { type: "text", text: fileSizeInfo + result.schema } ] }; } else { return { content: [ { type: "text", text: `Error: ${result.error.message}` } ], isError: true }; } } catch (error) { return { content: [ { type: "text", text: `Validation error: ${error instanceof Error ? error.message : String(error)}` } ], isError: true }; } } ); - src/index.ts:272-323 (handler)Core handler function processJsonSchema that executes the tool logic: ingests JSON content via JsonIngestionContext, calculates file size, generates TypeScript schema using quicktype library, handles errors, and returns schema or error.
async function processJsonSchema(input: JsonSchemaInput): Promise<JsonSchemaResult> { try { // Use strategy pattern to ingest JSON content const ingestionResult = await jsonIngestionContext.ingest(input.filePath); if (!ingestionResult.success) { // Map strategy errors to existing error format for backward compatibility return { success: false, error: ingestionResult.error }; } const jsonContent = ingestionResult.content; // Calculate file size in bytes const fileSizeBytes = new TextEncoder().encode(jsonContent).length; // Generate schema using quicktype with fixed parameters try { const result = await quicktypeJSON( "typescript", "GeneratedType", jsonContent ); return { success: true, schema: result.lines.join('\n'), fileSizeBytes }; } catch (error) { return { success: false, error: { type: 'quicktype_error', message: 'Failed to generate schema', details: error } }; } } catch (error) { return { success: false, error: { type: 'validation_error', message: 'Unexpected error during processing', details: error } }; } } - src/index.ts:19-24 (schema)Zod input schema JsonSchemaInputSchema used for validating the tool's filePath parameter, ensuring it's a valid local path or HTTP/HTTPS URL.
const JsonSchemaInputSchema = z.object({ filePath: z.string().min(1, "File path or HTTP/HTTPS URL is required").refine( (val) => val.length > 0 && (val.startsWith('./') || val.startsWith('/') || val.startsWith('http://') || val.startsWith('https://') || !val.includes('/')), "Must be a valid file path or HTTP/HTTPS URL" ) }); - src/index.ts:101-123 (helper)Helper function quicktypeJSON that generates TypeScript types from JSON sample using the quicktype library, used by processJsonSchema to produce the schema output.
async function quicktypeJSON( targetLanguage: LanguageName, typeName: string, jsonString: string ): Promise<SerializedRenderResult> { const jsonInput = jsonInputForTargetLanguage(targetLanguage); await jsonInput.addSource({ name: typeName, samples: [jsonString] }); const inputData = new InputData(); inputData.addInput(jsonInput); return await quicktype({ inputData, lang: targetLanguage, rendererOptions: { "just-types": true } }); }