Generated banner for Cue Kind Definition
Generated logo for Cue Kind Definition

Cue Kind Definition

Grafana LabsOfficialPublished by Grafana Labs

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • No issues found

From the author

Author CUE kind definitions for grafana-app-sdk apps - schemas, versioning, field constraints, named type definitions, custom routes, and codegen configuration. Scaffolds kinds via `grafana-app-sdk project kind add`, writes spec/status schemas with type constraints (regex, enum, range), defines `#`-prefixed named types for reusable structs, registers versions in the app manifest, and runs `grafana-app-sdk generate` with explicit error recovery. Use when working with CUE kinds, adding a new resource type, adding a version to an existing kind, writing schema field constraints, defining `#Definition` types, adding custom routes, editing files under `kinds/`, or when the user asks to "model a resource", "add a CUE schema", or "write a kind" — even without saying "CUE" explicitly.
— the description by Grafana Labs

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to defining resource kinds within the grafana-app-sdk ecosystem using CUE. It covers the full lifecycle of kind management, including scaffolding new resources, defining complex schemas with field constraints, versioning, and configuring code generation for Go and TypeScript. It ensures that developers can maintain consistent, type-safe resource models while adhering to the framework's specific manifest and directory requirements.

What it does

  • Scaffolds new resource kinds using the CLI.
  • Defines spec and status schemas with advanced CUE constraints like regex, enums, and ranges.
  • Supports reusable struct definitions using # prefixed types.
  • Manages multi-version resource schemas and manifest registration.
  • Configures per-kind code generation settings for Go and TypeScript.
  • Facilitates the definition of custom API routes at the kind or version level.

When to use it

  • When creating a new resource type for a grafana-app-sdk application.
  • When adding a new version to an existing resource kind.
  • When defining or updating schema field constraints and validation rules.
  • When you need to define reusable struct types for complex resource models.
  • When adding custom API routes to your application.

Advantages

  • Ensures type safety through CUE's constraint-based language.
  • Automates the generation of Go and TypeScript code from schema definitions.
  • Provides a standardized directory structure for maintainable projects.
  • Supports explicit versioning to handle breaking changes safely.
  • Reduces manual boilerplate by integrating directly with the SDK's generation tools.

Usage examples

“How do I add a new resource kind called 'DashboardConfig' to my app?”
The agent will guide you to run 'grafana-app-sdk project kind add DashboardConfig', edit the generated .cue files in the kinds/ directory, and execute 'grafana-app-sdk generate' to create the necessary Go and TypeScript artifacts.
“I need to add a regex constraint to a string field in my schema.”
The agent will show you how to use the '&' operator with the regex pattern, such as 'myField: string & =~"^[a-z]+"'.
“How do I create a new version for an existing kind?”
The agent will instruct you to copy the existing version file, rename the top-level object, register the new version in 'kinds/manifest.cue', and re-run the generation command.
“How can I define a reusable struct for my spec?”
The agent will explain how to define a '#'-prefixed type within the schema block, which allows you to reuse the struct across multiple fields and ensures it is generated as a named type.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/grafana/cue-kind-definition/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip cue-kind-definition.zip -d .agents/skills

Documentation by Grafana Labs

CUE Kind Definition

Common Workflows

Adding a new kind
# 1. Scaffold the kind files
grafana-app-sdk project kind add MyKind --overwrite
# Produces kinds/mykind.cue + kinds/mykind_v1alpha1.cue + updates kinds/manifest.cue.

# 2. Edit the generated .cue files — fill in schema.spec / schema.status fields

# 3. Generate types and clients
grafana-app-sdk generate

# 4. Verify the generated artifacts exist
ls pkg/generated/    # should contain new types for MyKind

If generate fails with CUE errors:

  • Read the error — CUE prints the offending file + line + which constraint failed

  • Common causes: missing required field, type mismatch (e.g. string field assigned an int), unresolved reference between version files

  • Fix the .cue source, re-run grafana-app-sdk generate. Never edit files under pkg/generated/ — they're overwritten on every run.

Adding a new version to an existing kind
# 1. Copy the existing version file
cp kinds/mykind_v1alpha1.cue kinds/mykind_v1.cue

# 2. Edit kinds/mykind_v1.cue — rename the top-level object (e.g. myKindv1) and adjust the schema

# 3. Register the new version in kinds/manifest.cue
#    Add a versions["v1"]: { schema: myKindv1 } entry

# 4. Re-generate
grafana-app-sdk generate

# 5. Verify both versions were generated — per-version Go types live under pkg/generated/<group>/<version>/
ls pkg/generated/             # should list both version directories (e.g. v1alpha1/ v1/)
# Optionally inspect the CRD spec under definitions/ to confirm both versions appear in `spec.versions[]`

Breaking changes (removing fields, changing types, adding required fields) must go into a new version — never modify a stable version (v1, v2) in place.

Kind file structure

The CLI produces a flat layout under kinds/:

kinds/
├── manifest.cue           # App manifest + version list declarations
├── mykind.cue             # Common (cross-version) kind metadata
└── mykind_v1alpha1.cue    # v1alpha1 schema + codegen config

For multi-version kinds, additional version files sit alongside (mykind_v1.cue, etc.). For very large kind sets (10+ kinds), consider the per-kind subdirectory layout — full kind anatomy reference in references/kind-layout.md.

CUE Kind Anatomy

Three layers per kind:

1. Common kind metadata
// kinds/mykind.cue
package kinds

myKind: {
    kind: "MyKind"               // Required: PascalCase kind name
    // other cross-version fields (scope, pluralName, validation, mutation, conversion, …)
    // Full field reference in references/kind-layout.md.
}
2. Per-version schema
// kinds/mykind_v1alpha1.cue
package kinds

myKindv1alpha1: myKind & {
    schema: {
        spec: {                       // desired state — user-set
            title:       string
            description: string | *""
            count:       int & >=0
            enabled:     bool | *true
        }
        status: {                     // observed state — operator-set
            lastObservedGeneration: int | *0
            state:                  string | *""
            message:                string | *""
        }
    }
    codegen: {
        ts: { enabled: true }
        go: { enabled: true }
    }
}
3. App manifest
// kinds/manifest.cue
package kinds

App: {
    appName: "my-app"
    versions: {
        "v1alpha1": { schema: myKindv1alpha1 }
    }
}

Codegen configuration

Control what gets generated per kind per version:

codegen: {
    ts: { enabled: true | false }   // TypeScript types
    go: { enabled: true | false }   // Go types + client
}

Disabling go for frontend-only apps avoids unused Go code. Disabling ts for backend-only resources reduces bundle size. Both default to true when omitted.

References

External resources

Files

references/cue-constraints.md

CUE Constraints Reference

CUE (Configure, Unify, Execute) is a constraint-based language. Values are not assigned — they are constrained. Every field is the intersection (&) of all constraints applied to it.

Basic Types

myString:  string
myInt:     int
myFloat:   float
myBool:    bool
myBytes:   bytes
myNull:    null

Disjunctions (OR / enums)

// String enum
status: "pending" | "active" | "archived"

// Type or null (optional)
description: string | null

// Multiple types
value: int | string

Default Values

// Optional string with default
description: string | *""

// Optional bool with default
enabled: bool | *true

// Optional int with default
replicas: int | *1

// Optional enum with default
priority: "low" | "medium" | "high" | *"medium"

Constraints

Constraints use the & (unify/intersect) operator:

// Numeric bounds
port:    int & >=1 & <=65535
count:   int & >=0
percent: float & >=0 & <=100

// String length
name:    string & strings.MinRunes(1) & strings.MaxRunes(63)

// Regex patterns
slug:    string & =~"^[a-z][a-z0-9-]*$"
email:   string & =~"^[^@]+@[^@]+\\.[^@]+$"
semver:  string & =~"^v?[0-9]+\\.[0-9]+\\.[0-9]+"

// Non-empty string
title:   string & != ""

Lists

// List of any type
items: [...]

// List of strings (scalars — inline fine)
tags: [...string]

// List of objects — always use a #Definition, never inline the struct
// ❌ Avoid:
// rules: [...{ path: string, method: string }]

// ✅ Preferred:
#Rule: {
    path:   string
    method: "GET" | "POST" | "PUT" | "DELETE"
}
rules: [...#Rule]

// Fixed-size list
pair: [string, int]  // exactly 2 elements: a string and an int

Maps / Structs

// Map from string to string
labels: {[string]: string}

// Map from string to any
annotations: {[string]: _}

// Nested struct
metadata: {
    name:      string
    namespace: string | *"default"
    labels:    {[string]: string} | *{}
}

Optional Fields

In CUE, all struct fields are required unless marked with ?:

// Required
title: string

// Optional (may be absent)
description?: string

// Optional with a specific type
config?: {
    timeout: int | *30
}

Note: In grafana-app-sdk kind schemas, the common pattern is to use string | *"" rather than ? for optional string fields, as it provides a sensible default that the generated Go struct can hold.

Additional Types

In CUE, non-primitive types can be imported from the standard library. For exmaple, to create a field of go type time.Time:

import "time"

{
    timeField: string & time.Time
}

CUE Imports for Constraints

import "strings"

name: string & strings.MinRunes(1) & strings.MaxRunes(253)

Available standard packages: strings, math, list, regexp, encoding/json, encoding/yaml

Named Type Definitions (# prefix)

CUE supports named struct definitions using #TypeName. Inside a schema block, these define sub-types that the code generator emits as named Go structs and TypeScript interfaces.

schema: {
    #Config: {
        timeout: int & >=1 & <=3600 | *30
        retries: int & >=0 & <=10   | *3
    }

    #Rule: {
        path:   string
        weight: int & >=0 & <=100
    }

    #ResourceRef: {
        name:      string & != ""
        namespace: string | *"default"
    }

    spec: {
        config:    #Config
        rules:     [...#Rule] | *[]
        targetRef: #ResourceRef
    }
}

Scope: # definitions are scoped to the schema block they are declared in and cannot be referenced outside it.

Generated output: Each #TypeName produces a named type in Go and TypeScript:

  • Go: type Config struct { Timeout int \json:"timeout"`; Retries int `json:"retries"` }`

  • TypeScript: interface Config { timeout: number; retries: number; }

Prefer # definitions when:

  • The struct is used in more than one field

  • The struct is large or complex (many fields, nested constraints)

  • The struct appears in a list ([...#Rule]) — keeping the list declaration readable

Inline structs are fine when:

  • The struct is small and simple (2–3 fields)

  • It is used in exactly one place and unlikely to be reused

Maps ({[string]: string}) and lists of scalars ([...string]) are always fine inline.

Pattern in grafana-app-sdk Kinds

A complete schema block with preferred patterns:

schema: {
    // #Definitions for structs that are large, reused, or appear in lists
    #Config: {
        timeout: int & >=1 & <=3600 | *30
        retries: int & >=0 & <=10   | *3
    }

    #Rule: {
        path:   string
        weight: int & >=0 & <=100
    }

    spec: {
        // Required scalar fields
        title:    string & != ""
        category: "issue" | "feature" | "bug"

        // Optional scalars with defaults
        description: string | *""
        priority:    "low" | "medium" | "high" | *"medium"
        enabled:     bool | *true
        count:       int & >=0 | *0

        // Named definition for a larger/reused struct
        config: #Config

        // Small, simple, single-use struct — inline is fine
        contact: {
            name:  string
            email: string
        }

        // List of scalars (inline fine)
        tags: [...string] | *[]

        // List of objects — prefer a named definition
        rules: [...#Rule] | *[]

        // Map (always inline)
        labels: {[string]: string} | *{}
    }

    // status is written only by the operator/reconciler, never by users.
    status: {
        lastObservedGeneration: int | *0
        state:   string | *""   // e.g. "Ready", "Provisioning", "Error"
        message: string | *""
        // e.g. name of a resource provisioned by the reconciler:
        // provisionedConfigMap: string | *""
    }
}

## Common Mistakes

**Don't use `?` on spec fields that need defaults in Go:**
```cue
// Bad — Go will get zero value, hard to distinguish "not set" from empty
description?: string

// Better — explicit default
description: string | *""

Don't put server state in spec:

// Bad — this should be in status
spec: {
    lastUpdated: string  // server writes this
}

// Good
status: {
    lastUpdated: string
}

Do use != "" for required strings:

// Bad — accepts empty string
name: string

// Good — rejects empty string at API level
name: string & != ""

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Grafana Labs
Publisher
Grafana Labs (Official)
Source
grafana/skills · skills/grafana-app-sdk/cue-kind-definition · commit 8fb72a5
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Grafana Labs or Grafana Labs.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cue-kind-definition.zip