Skip to content

Natural Language Schema Creation via MCP - AI-Powered Entity Definition #448

Closed

Description

@malibio

Parent Issue

Part of Epic #445: Custom Entity Types - User-Defined Schemas with Natural Language Creation

Problem

Users currently have no way to create custom entity schemas without manually writing JSON schema definitions. This creates a barrier to entry for non-technical users and slows down rapid prototyping.

Current workflow (manual JSON):

{
  "id": "invoice",
  "node_type": "schema",
  "properties": {
    "is_core": false,
    "version": 1,
    "description": "Invoice tracking",
    "fields": [
      { "name": "invoice_number", "type": "string", "protection": "user", "required": true },
      { "name": "amount", "type": "number", "protection": "user" },
      { "name": "status", "type": "enum", "protection": "user", "coreValues": ["DRAFT", "SENT", "PAID"] }
    ]
  }
}

Desired workflow (natural language):

User: "Create an Invoice entity with invoice number, amount in dollars, vendor name, 
       status (draft/sent/paid), and due date"

AI: ✨ Creates schema automatically
    → invoice_number: string, required
    → amount: number
    → vendor: string
    → status: enum with values [DRAFT, SENT, PAID]
    → due_date: date

Solution

Create an MCP tool that accepts natural language descriptions and generates schema definitions with proper field types, validation, and namespace enforcement.

Architecture

Integration Points:

  1. MCP Handler - Exposes tool to Claude/AI
  2. Schema Generator - Parses natural language → schema fields
  3. Type Inference Engine - Determines field types from descriptions
  4. Namespace Enforcer - Ensures user properties use custom: prefix
  5. Schema Service - Stores generated schema (existing)

MCP Tool Specification

Tool Name: create_entity_schema_from_description

Input Schema:

interface CreateEntitySchemaInput {
  entity_name: string;          // e.g., "Invoice"
  description: string;           // Natural language field descriptions
  additional_constraints?: {     // Optional structured hints
    required_fields?: string[];
    default_values?: Record<string, any>;
    enum_values?: Record<string, string[]>;
  };
}

Output Schema:

interface CreateEntitySchemaOutput {
  schema_id: string;              // Generated schema ID
  schema_definition: SchemaDefinition;  // Full schema object
  created_fields: SchemaField[];  // List of inferred fields
  warnings?: string[];            // Any ambiguities or assumptions made
}

Example Usage:

{
  "entity_name": "Invoice",
  "description": "Track invoices with invoice number (required), amount in USD, vendor name, status (draft/sent/paid/overdue), due date, and optional notes",
  "additional_constraints": {
    "required_fields": ["invoice_number", "amount"],
    "enum_values": {
      "status": ["DRAFT", "SENT", "PAID", "OVERDUE"]
    }
  }
}

Implementation Details

1. MCP Handler (packages/core/src/mcp/handlers/schema.rs)

Add new handler alongside existing schema management tools:

pub async fn handle_create_entity_schema_from_description(
    args: serde_json::Value,
    context: &MCPContext,
) -> Result<serde_json::Value, MCPError> {
    let input: CreateEntitySchemaInput = serde_json::from_value(args)?;
    
    // Parse natural language description
    let inferred_fields = parse_field_descriptions(&input.description);
    
    // Apply additional constraints
    let fields = apply_constraints(inferred_fields, input.additional_constraints);
    
    // Enforce namespace prefixes
    let namespaced_fields = enforce_namespace_prefixes(fields);
    
    // Create schema
    let schema_id = normalize_schema_id(&input.entity_name);
    let schema = create_schema_definition(schema_id.clone(), namespaced_fields);
    
    // Store via SchemaService
    context.schema_service.create_schema(&schema_id, schema.fields).await?;
    
    Ok(serde_json::json!({
        "schema_id": schema_id,
        "schema_definition": schema,
        "created_fields": schema.fields,
        "warnings": detect_ambiguities(&input.description)
    }))
}

2. Natural Language Parser

Field Detection Patterns:

struct FieldPattern {
    field_name_patterns: Vec<Regex>,
    type_indicators: Vec<String>,
    required_indicators: Vec<String>,
}

fn parse_field_descriptions(description: &str) -> Vec<InferredField> {
    let patterns = vec![
        // Pattern: "invoice number (required)"
        FieldPattern {
            field_name: r"(\w+\s*\w*)\s*\(required\)",
            type_hint: None,
            required: true,
        },
        // Pattern: "amount in USD" → number type
        FieldPattern {
            field_name: r"(\w+)\s+in\s+(USD|dollars|euros)",
            type_hint: Some("number"),
            required: false,
        },
        // Pattern: "status (draft/sent/paid)" → enum type
        FieldPattern {
            field_name: r"(\w+)\s*\(([\w/]+)\)",
            type_hint: Some("enum"),
            enum_values: r"([\w/]+)",
            required: false,
        },
        // Pattern: "due date" → date type
        FieldPattern {
            field_name: r"(\w+\s+date)",
            type_hint: Some("date"),
            required: false,
        },
    ];
    
    // Parse description and extract fields
    // ...
}

3. Type Inference Engine

Type Detection Rules:

fn infer_field_type(field_description: &str, field_name: &str) -> FieldType {
    // Keyword-based inference
    if contains_any(field_description, &["date", "when", "time"]) {
        return FieldType::Date;
    }
    
    if contains_any(field_description, &["amount", "price", "cost", "USD", "dollars", "count"]) {
        return FieldType::Number;
    }
    
    if contains_any(field_description, &["yes/no", "true/false", "enabled", "disabled"]) {
        return FieldType::Boolean;
    }
    
    // Pattern: "(option1/option2/option3)"
    if let Some(enum_values) = extract_enum_pattern(field_description) {
        return FieldType::Enum { core_values: enum_values };
    }
    
    // Default: string
    FieldType::String
}

Confidence Scoring:

struct InferredField {
    name: String,
    field_type: FieldType,
    confidence: f32,  // 0.0 - 1.0
    ambiguities: Vec<String>,
}

4. Namespace Enforcement

Critical Rule: All user-defined properties MUST use namespace prefixes to avoid conflicts with future core properties.

fn enforce_namespace_prefixes(fields: Vec<InferredField>) -> Vec<SchemaField> {
    fields.into_iter().map(|inferred| {
        let field_name = if !has_namespace_prefix(&inferred.name) {
            // Auto-add "custom:" prefix if missing
            format!("custom:{}", normalize_field_name(&inferred.name))
        } else {
            inferred.name
        };
        
        SchemaField {
            name: field_name,
            field_type: inferred.field_type,
            protection: FieldProtection::User,
            required: inferred.required,
            description: Some(inferred.original_description),
        }
    }).collect()
}

fn has_namespace_prefix(name: &str) -> bool {
    name.starts_with("custom:") || 
    name.starts_with("org:") || 
    name.starts_with("plugin:")
}

5. AI Prompt Engineering

System Prompt Addition:

When creating entity schemas from user descriptions:
1. Extract all mentioned fields (invoice number, amount, status, etc.)
2. Infer field types based on context:
   - Numbers: amount, price, count, quantity, age
   - Dates: date, when, time, deadline, due
   - Enums: status with options (draft/sent/paid)
   - Boolean: yes/no, enabled/disabled, active/inactive
   - String: default fallback
3. Mark fields as required if explicitly stated or critical to entity
4. Auto-generate sensible default values where appropriate
5. Use SCREAMING_SNAKE_CASE for enum values (DRAFT, SENT, PAID)
6. Apply "custom:" prefix to all field names automatically
7. Return warnings for ambiguous descriptions

Acceptance Criteria

Functional Requirements

  • MCP tool create_entity_schema_from_description exists
  • Accepts natural language entity descriptions
  • Infers field types with >80% accuracy on common patterns
  • Enforces custom: namespace prefix automatically
  • Creates valid schema definitions
  • Returns warnings for ambiguous descriptions
  • Supports additional_constraints for explicit type hints

Type Inference Requirements

  • Detects number fields (amount, price, count, etc.)
  • Detects date fields (date, deadline, due, etc.)
  • Detects enum fields from "(option1/option2)" syntax
  • Detects boolean fields (yes/no, enabled/disabled)
  • Defaults to string for ambiguous fields
  • Handles multi-word field names ("invoice number" → "invoice_number")

Namespace Enforcement Requirements

  • All user fields have custom: prefix
  • Field names normalized to snake_case
  • No conflicts with reserved core property names
  • Warnings if user tries to use simple names without prefix

Testing Requirements

  • Unit tests: Field extraction from descriptions
  • Unit tests: Type inference for each field type
  • Unit tests: Namespace prefix enforcement
  • Unit tests: Enum value extraction
  • Integration tests: Full schema creation from description
  • Integration tests: Edge cases (empty description, ambiguous types)
  • E2E tests: AI creates schema → user creates node → properties work

Testing Plan

Unit Tests (Rust)

#[test]
fn test_parse_field_with_enum() {
    let description = "status (draft/sent/paid)";
    let field = parse_single_field_description(description);
    
    assert_eq!(field.name, "custom:status");
    assert_eq!(field.field_type, FieldType::Enum);
    assert_eq!(field.enum_values, vec!["DRAFT", "SENT", "PAID"]);
}

#[test]
fn test_infer_number_type() {
    let descriptions = vec![
        "amount in USD",
        "price",
        "total cost",
        "count of items"
    ];
    
    for desc in descriptions {
        let field = parse_single_field_description(desc);
        assert_eq!(field.field_type, FieldType::Number);
    }
}

#[test]
fn test_namespace_prefix_enforcement() {
    let fields = vec![
        InferredField { name: "invoice_number".into(), .. },
        InferredField { name: "custom:amount".into(), .. },
    ];
    
    let namespaced = enforce_namespace_prefixes(fields);
    
    assert_eq!(namespaced[0].name, "custom:invoice_number");
    assert_eq!(namespaced[1].name, "custom:amount");  // Already prefixed
}

Integration Tests

#[tokio::test]
async fn test_create_invoice_schema_from_description() {
    let input = CreateEntitySchemaInput {
        entity_name: "Invoice".into(),
        description: "invoice number (required), amount in USD, status (draft/sent/paid), due date".into(),
        additional_constraints: None,
    };
    
    let result = handle_create_entity_schema_from_description(
        serde_json::to_value(input).unwrap(),
        &context
    ).await.unwrap();
    
    let output: CreateEntitySchemaOutput = serde_json::from_value(result).unwrap();
    
    assert_eq!(output.schema_id, "invoice");
    assert_eq!(output.created_fields.len(), 4);
    
    // Verify fields
    let invoice_number = output.created_fields.iter()
        .find(|f| f.name == "custom:invoice_number").unwrap();
    assert!(invoice_number.required);
    
    let amount = output.created_fields.iter()
        .find(|f| f.name == "custom:amount").unwrap();
    assert_eq!(amount.field_type, FieldType::Number);
    
    let status = output.created_fields.iter()
        .find(|f| f.name == "custom:status").unwrap();
    assert_eq!(status.enum_values, vec!["DRAFT", "SENT", "PAID"]);
}

Example Scenarios

Scenario 1: Invoice Entity

Input:

"Create an Invoice entity with invoice number (required), amount in USD, 
 vendor name, status (draft/sent/paid), due date, and optional notes"

Generated Schema:

{
  "id": "invoice",
  "fields": [
    { "name": "custom:invoice_number", "type": "string", "required": true },
    { "name": "custom:amount", "type": "number", "required": false },
    { "name": "custom:vendor", "type": "string", "required": false },
    { "name": "custom:status", "type": "enum", "core_values": ["DRAFT", "SENT", "PAID"] },
    { "name": "custom:due_date", "type": "date", "required": false },
    { "name": "custom:notes", "type": "string", "required": false }
  ]
}

Scenario 2: Customer Entity

Input:

"Customer with first name, last name, email (required), phone, 
 account status (active/inactive/suspended), and signup date"

Generated Schema:

{
  "id": "customer",
  "fields": [
    { "name": "custom:first_name", "type": "string" },
    { "name": "custom:last_name", "type": "string" },
    { "name": "custom:email", "type": "string", "required": true },
    { "name": "custom:phone", "type": "string" },
    { "name": "custom:account_status", "type": "enum", "core_values": ["ACTIVE", "INACTIVE", "SUSPENDED"] },
    { "name": "custom:signup_date", "type": "date" }
  ]
}

Dependencies

Performance Considerations

  • Schema generation: <100ms for typical entity (5-10 fields)
  • Type inference: <10ms per field
  • No impact on runtime - schema creation is one-time operation

Future optimization:

  • Cache common field patterns
  • Pre-trained ML model for type inference (overkill for MVP)

Migration Notes

No migration required - This is purely additive functionality.

Deployment notes:

Documentation Updates

  • Add natural language schema creation guide
  • Document type inference patterns and keywords
  • Add examples for common entity types
  • Document namespace enforcement rules
  • Update MCP tool documentation

Success Metrics

  • 80% accurate type inference on first try

  • <5 minutes to create custom entity via natural language
  • Zero namespace conflicts with core properties
  • 90% user satisfaction with generated schemas


Labels: enhancement, ai-integration, mcp, rust, backend
Priority: Medium (enhances user experience, not blocking)
Estimated effort: 8-12 hours

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions