Skip to main content
Glama

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
NameRequiredDescriptionDefault
filePathYesJSON 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
                };
            }
        }
    );
  • 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
          }
        };
      }
    }
  • 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"
      )
    });
  • 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
        }
      });
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions generating a schema but lacks details on error handling, output format, performance considerations, or any constraints like rate limits or authentication needs, leaving significant gaps for a tool that processes external resources.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded and concise, consisting of two clear sentences that directly state the tool's function and parameter requirement without any redundant or unnecessary information, making it highly efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity in handling external JSON sources and no output schema or annotations, the description is incomplete. It fails to address critical aspects like the format of the generated TypeScript schema, error responses for invalid inputs, or limitations, which are essential for effective use by an AI agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds minimal semantics beyond the input schema, which already has 100% coverage. It reiterates that the parameter is a 'file path or HTTP/HTTPS URL' but does not provide additional context like supported file formats, URL protocols beyond HTTP/HTTPS, or examples, so it meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Generate') and resource ('TypeScript schema for a JSON file or remote JSON URL'), distinguishing it from sibling tools like json_dry_run and json_filter by focusing on schema generation rather than validation or filtering.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by specifying the input type ('JSON file or remote JSON URL'), but does not explicitly state when to use this tool versus alternatives like json_dry_run or json_filter, nor does it provide exclusions or prerequisites for usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/kehvinbehvin/json-mcp-filter'

If you have feedback or need assistance with the MCP directory API, please join our Discord server