Spectral API Reference

Complete reference for using Spectral programmatically in TypeScript/JavaScript and Deno.

🎯 Overview

Spectral provides a complete toolkit for parsing, validating, and working with Spectral specifications. This reference covers:

  • Parser API - Parse Spectral code into AST
  • Validator API - Validate and analyze specifications
  • CLI API - Use Spectral from the command line
  • MCP Tools - Integrate with AI assistants

📦 Installation

Deno

import { Parser, Validator, CodeGenerator } from "jsr:@aexol/spectral";

Node.js / npm

npm install @aexol/spectral
import { Parser, Validator } from "@aexol/spectral";

🔧 Parser API

Parse Spectral source code into an Abstract Syntax Tree (AST).

Basic Parsing

import { Parser } from "@aexol/spectral";

const source = `
type User {
  id: string
  name: string
  email: string
}

visitor Admin {
  can manage users
  can view reports
}
`;

const parser = new Parser(source);
const ast = parser.parse();

console.log(ast);
// {
//   types: [...],
//   visitors: [...],
//   agents: [],
//   workflows: [],
//   roles: []
// }

Parser Options

interface ParserOptions {
  /** Include position information in AST nodes */
  includePositions?: boolean;
  /** Recover from errors and continue parsing */
  recoverFromErrors?: boolean;
}

const parser = new Parser(source, {
  includePositions: true,
  recoverFromErrors: true
});

AST Structure

The parser returns a SpectralAST object:

interface SpectralAST {
  types: TypeDefinition[];
  visitors: VisitorDefinition[];
  agents: AgentDefinition[];
  workflows: WorkflowDefinition[];
  roles: RoleDefinition[];
  enums: EnumDefinition[];
}

interface TypeDefinition {
  name: string;
  fields: FieldDefinition[];
  position?: Position;
}

interface FieldDefinition {
  name: string;
  type: string;
  isArray: boolean;
  isOptional: boolean;
}

interface VisitorDefinition {
  name: string;
  capabilities: Capability[];
  position?: Position;
}

interface Capability {
  verb: string;
  target: string;
  conditions?: Condition[];
  nested?: Capability[];
}

Error Handling

try {
  const ast = parser.parse();
} catch (error) {
  if (error instanceof SyntaxError) {
    console.error("Syntax error:", error.message);
    console.error("Line:", error.line, "Column:", error.column);
  }
}

✅ Validator API

Validate Spectral specifications for semantic correctness.

Basic Validation

import { Parser, Validator } from "@aexol/spectral";

const parser = new Parser(source);
const ast = parser.parse();

const validator = new Validator(ast);
const result = validator.validate();

if (!result.isValid) {
  console.error("Validation errors:", result.errors);
}

Validation Result

interface ValidationResult {
  isValid: boolean;
  errors: Diagnostic[];
  warnings: Diagnostic[];
  infos: Diagnostic[];
}

interface Diagnostic {
  severity: "error" | "warning" | "info";
  message: string;
  line?: number;
  column?: number;
  code?: string;
}

Validation Rules

The validator checks for:

  • Unique names - Types, visitors, agents, roles must have unique names
  • Valid references - Type references must exist
  • Valid verbs - Capability verbs must be recognized
  • Workflow states - Workflow transitions must reference defined states
  • Circular references - Detect and report circular type dependencies

Custom Validation

const validator = new Validator(ast, {
  strictMode: true,  // More strict validation
  allowUnknownVerbs: false,  // Require known capability verbs
});

🖥️ CLI API

Use Spectral from the command line.

Available Commands

# Parse and validate
spectral parse app.spectral
spectral validate app.spectral

# Generate documentation
spectral docs app.spectral -o README.md

# Analyze complexity
spectral analyze app.spectral

# Interactive chat
spectral chat

# AI-assisted implementation
spectral implement app.spectral --agent copilot

Programmatic CLI Usage

import { exec } from "@aexol/spectral/cli";

// Parse file
const parseResult = await exec(["parse", "app.spectral"]);

// Validate file
const validateResult = await exec([
  "validate",
  "app.spectral"
]);

🤖 MCP Tools API

Integrate Spectral with AI assistants via Model Context Protocol.

Available Tools

  1. parse_spectral - Parse and return AST
  2. validate_spectral - Validate and return diagnostics
  3. get_spectral_docs - Get documentation
  4. complete_spectral - Get code completions
  5. explain_spectral - Explain code in natural language
  6. spectral_to_natural_language - Convert to description
  7. get_spectral_schema - Export JSON Schema

Using MCP Tools

# List tools
spectral mcp --list-tools

# Execute a tool
spectral mcp --tool validate_spectral --args '{
  "code": "visitor Admin { can manage users }"
}'

# Run as MCP server (for AI assistants)
spectral mcp --stdio

Tool Schemas

Each tool accepts specific arguments:

// validate_spectral
{
  code: string;  // Spectral source code to validate
}

// explain_spectral
{
  code: string;  // Spectral code to explain
}

📊 Analysis API

Analyze Spectral specifications for complexity and patterns.

Analyze AST

import { Parser, analyze } from "@aexol/spectral";

const parser = new Parser(source);
const ast = parser.parse();

const analysis = analyze(ast);

console.log(analysis);
// {
//   typeCount: 5,
//   visitorCount: 3,
//   workflowCount: 2,
//   totalCapabilities: 15,
//   maxNestingDepth: 4,
//   complexity: "medium"
// }

Visualization

import { visualize } from "@aexol/spectral/utils";

const tree = visualize(ast);
console.log(tree);

// Output:
// └── Admin
//     ├── can manage users
//     │   └── can create users
//     │   └── can delete users
//     └── can view reports

🔍 Utility Functions

Extract Types

import { extractTypes } from "@aexol/spectral/utils";

const types = extractTypes(ast);
// Returns array of all type definitions

Find References

import { findReferences } from "@aexol/spectral/utils";

const refs = findReferences(ast, "User");
// Returns all places where "User" type is referenced

Convert to JSON Schema

import { toJSONSchema } from "@aexol/spectral/utils";

const schema = toJSONSchema(ast);
// Returns JSON Schema representation of types

🎯 Complete Example

Here's a complete example using multiple APIs:

import { 
  Parser, 
  Validator, 
  analyze,
  visualize 
} from "@aexol/spectral";

async function processSpectral(source: string) {
  // 1. Parse
  console.log("Parsing...");
  const parser = new Parser(source);
  const ast = parser.parse();
  
  // 2. Validate
  console.log("Validating...");
  const validator = new Validator(ast);
  const validation = validator.validate();
  
  if (!validation.isValid) {
    console.error("Validation errors:", validation.errors);
    return;
  }
  
  // 3. Analyze
  console.log("Analyzing...");
  const analysis = analyze(ast);
  console.log("Complexity:", analysis.complexity);
  
  // 4. Visualize
  console.log("Capability Tree:");
  console.log(visualize(ast));
  
  console.log("✅ Done!");
}

// Use it
const source = await Deno.readTextFile("app.spectral");
await processSpectral(source);

🚨 Error Handling

Parser Errors

import { SyntaxError, Parser } from "@aexol/spectral";

try {
  const parser = new Parser(source);
  const ast = parser.parse();
} catch (error) {
  if (error instanceof SyntaxError) {
    console.error(`Syntax error at line ${error.line}: ${error.message}`);
  }
}

Validation Errors

const validation = validator.validate();

for (const error of validation.errors) {
  console.error(`[${error.severity}] ${error.message}`);
  if (error.line) {
    console.error(`  at line ${error.line}, column ${error.column}`);
  }
}

📚 Next Steps


Questions? Join our community or check the Quick Reference.