Skip to main content
Glama
blakeyoder

TypeScript Definitions MCP Server

by blakeyoder

validate_type_usage

Check TypeScript code for type errors and validate against expected types to ensure type safety in your project.

Instructions

Validate TypeScript code for type correctness

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesThe TypeScript code to validate
expectedTypeNoOptional expected type to validate against

Implementation Reference

  • Core implementation of the validate_type_usage tool logic using TypeScript Compiler API to create a temporary program, check syntactic/semantic diagnostics, and validate against an optional expected type.
    validateTypeUsage(code: string, expectedType?: string): ValidationResult {
      const errors: ValidationError[] = [];
      const warnings: ValidationWarning[] = [];
    
      try {
        // Create a temporary source file for validation
        const sourceFile = ts.createSourceFile(
          "temp.ts",
          code,
          ts.ScriptTarget.Latest,
          true
        );
    
        // Create a program with just this file
        const defaultCompilerHost = ts.createCompilerHost(this.compilerOptions);
        const compilerHost = {
          ...defaultCompilerHost,
          getSourceFile: (fileName: string, languageVersion: ts.ScriptTarget) => {
            if (fileName === "temp.ts") {
              return sourceFile;
            }
            return defaultCompilerHost.getSourceFile(fileName, languageVersion);
          }
        };
    
        const program = ts.createProgram(["temp.ts"], this.compilerOptions, compilerHost);
    
        // Get semantic diagnostics
        const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);
        const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);
    
        // Convert diagnostics to our format
        for (const diagnostic of [...syntacticDiagnostics, ...semanticDiagnostics]) {
          const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
          const position = diagnostic.start ? sourceFile.getLineAndCharacterOfPosition(diagnostic.start) : undefined;
    
          const errorInfo = {
            message,
            line: position ? position.line + 1 : undefined,
            column: position ? position.character + 1 : undefined,
            code: diagnostic.code?.toString()
          };
    
          if (diagnostic.category === ts.DiagnosticCategory.Error) {
            errors.push(errorInfo);
          } else if (diagnostic.category === ts.DiagnosticCategory.Warning) {
            warnings.push(errorInfo);
          }
        }
    
        // If expected type is provided, validate against it
        if (expectedType && errors.length === 0) {
          const typeChecker = program.getTypeChecker();
          this.validateExpectedType(sourceFile, typeChecker, expectedType, errors, warnings);
        }
    
      } catch (error) {
        errors.push({
          message: `Validation failed: ${error instanceof Error ? error.message : String(error)}`,
          code: "VALIDATION_ERROR"
        });
      }
    
      return {
        valid: errors.length === 0,
        errors,
        warnings
      };
    }
  • MCP server handler method for validate_type_usage tool that delegates to TypeValidator and formats the result as MCP response.
    private async handleValidateTypeUsage(code: string, expectedType?: string) {
      const result = this.typeValidator.validateTypeUsage(code, expectedType);
      
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    }
  • Tool registration in the ListTools response, defining name, description, and input schema.
      name: "validate_type_usage",
      description: "Validate TypeScript code for type correctness",
      inputSchema: {
        type: "object",
        properties: {
          code: {
            type: "string",
            description: "The TypeScript code to validate"
          },
          expectedType: {
            type: "string",
            description: "Optional expected type to validate against"
          }
        },
        required: ["code"]
      }
    },
  • TypeScript interface defining the expected arguments for the validate_type_usage tool, used for internal type safety.
    interface ToolArguments {
      lookup_type: { typeName: string; packageName?: string };
      validate_type_usage: { code: string; expectedType?: string };
      find_interfaces: { pattern: string };
      get_package_types: { packageName: string };
      validate_interface_implementation: {
        implementation: string;
        interfaceName: string;
        interfaceDefinition: string;
      };
      check_type_compatibility: { sourceType: string; targetType: string };
      reinitialize_indexer: { workingDir?: string };
    }
  • Tool dispatch registration in the CallToolRequest handler switch statement.
    case "validate_type_usage": {
      const validateArgs = this.validateArgs<ToolArguments["validate_type_usage"]>(args);
      return await this.handleValidateTypeUsage(validateArgs.code, validateArgs.expectedType);
    }
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 states the tool validates type correctness, implying it performs a read-only analysis, but doesn't specify what happens during validation (e.g., error reporting, success indicators, or side effects). For a tool with zero annotation coverage, this is insufficient, as it misses details like output format or potential limitations.

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 a single, direct sentence: 'Validate TypeScript code for type correctness.' It is front-loaded with the core purpose, has no unnecessary words, and efficiently conveys the tool's function without waste, earning a score of 5 for optimal conciseness.

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 complexity of type validation, the lack of annotations, no output schema, and 100% schema coverage, the description is incomplete. It doesn't explain what the validation entails, how results are returned, or any behavioral traits. For a tool that likely produces detailed output (e.g., errors or type mismatches), this leaves significant gaps, scoring 2.

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?

Schema description coverage is 100%, so the schema already documents both parameters ('code' and 'expectedType') with clear descriptions. The description adds no additional meaning beyond what the schema provides, such as syntax examples or validation rules. According to the rules, with high schema coverage (>80%), the baseline is 3, which is appropriate here.

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

Purpose4/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: 'Validate TypeScript code for type correctness.' It specifies the verb ('validate') and resource ('TypeScript code'), making the function unambiguous. However, it doesn't explicitly differentiate from siblings like 'check_type_compatibility' or 'validate_interface_implementation,' which might have overlapping purposes, so it doesn't reach a score of 5.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention any context, prerequisites, or exclusions, and with siblings like 'check_type_compatibility' and 'validate_interface_implementation' available, the lack of differentiation leaves usage unclear. This is a minimal level of guidance, scoring 2.

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/blakeyoder/typescript-definitions-mcp'

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