Early AccessThe plugin system and API interfaces may evolve. Custom plugins may require updates as the CLI matures.
Overview
The KDX CLI plugin system extends standard CRUD operations with resource-specific commands. Plugins provide specialized functionality that goes beyond basic get, create, update, and delete operations.
Why Plugins?
While KDX CLI provides universal operations for all resource types, some resources benefit from specialized commands:
- Workspace operations - Execute commands, check status, manage users
- Store operations - Reindex data, view statistics, optimize performance
- Model operations - Train, evaluate, deploy models
- Assistant operations - Test prompts, review conversations, adjust settings
Plugins bridge the gap between generic resource management and domain-specific workflows.
Built-in Plugins
KDX CLI ships with plugins for common resource types.
Workspace Plugin
The workspace plugin adds commands for managing and interacting with workspaces.
workspace exec
Execute commands or operations within a workspace context:
# Execute a rebuild-index command
kdx workspace exec my-workspace "rebuild-index"
# Run a custom operation
kdx workspace exec engineering-ws "cleanup-temp-files"
# Execute with parameters
kdx workspace exec my-workspace "migrate-data --from v1 --to v2"
Use cases:
- Maintenance operations
- Data migrations
- Custom scripts
- Batch processing
workspace status
Display comprehensive workspace status and health information:
kdx workspace status my-workspace
Example output:
Workspace: my-workspace
====================
State: active
Active Users: 12
Created: 2025-01-15 10:30:00
Last Activity: 2025-11-07 09:15:23
Resources:
CPU: 45%
Memory: 2.3GB / 8GB
Storage: 156GB / 500GB
Health Checks:
✓ API responsive
✓ Database connected
✓ Cache operational
⚠ High storage usage (31%)
Recent Events:
[09:15] User alice@example.com logged in
[09:10] Document processed: invoice-2024-11.pdf
[09:05] Assistant completed task
Use cases:
- Monitoring workspace health
- Troubleshooting performance issues
- Capacity planning
- Audit and compliance reporting
Store Plugin
The store plugin provides operations for managing document and vector stores.
store reindex
Trigger a reindexing operation for a store:
# Trigger reindex
kdx store reindex my-store
# Force reindex even if already in progress
kdx store reindex my-store --force
# Reindex specific collection
kdx store reindex my-store --collection invoices
When to use:
- After bulk document imports
- When search results seem outdated
- After schema changes
- For performance optimization
Example output:
Reindexing store: my-store
Status: started
Job ID: reindex-abc123
Estimated time: 15 minutes
Monitor progress with:
kdx store stats my-store
store stats
Display detailed store statistics and performance metrics:
Example output:
Store: my-store
====================
Type: document-store
Status: healthy
Documents:
Total: 125,432
Indexed: 125,430
Pending: 2
Storage:
Total Size: 45.2GB
Average Document Size: 372KB
Index Size: 8.1GB
Performance:
Average Query Time: 23ms
Queries Per Second: 450
Cache Hit Rate: 94.2%
Index Status:
Last Updated: 2025-11-07 08:45:00
Update Frequency: hourly
Health: ✓ healthy
Top Collections:
invoices: 45,230 docs (18.2GB)
contracts: 32,100 docs (12.5GB)
reports: 28,890 docs (9.8GB)
Use cases:
- Performance monitoring
- Capacity planning
- Identifying slow queries
- Storage optimization
Request Validation
Plugins benefit from KDX CLI’s automatic schema validation.
Pre-Flight Validation
All create and update requests are validated against the OpenAPI schema before being sent to the API:
# workspace.yaml
kind: workspace
name: my-workspace
description: Development workspace
maxUsers: 50
kdx create workspace -f workspace.yaml
If validation fails, you get immediate feedback:
Error: Validation failed:
- Field 'name': required field missing
- Field 'maxUsers': must be >= 1
- Field 'type': must be one of: standard, enterprise
Why Pre-Flight Validation Matters
Without validation:
- Craft YAML file
- Run command
- Wait for API round-trip
- Get error from server
- Fix and repeat
With validation:
- Craft YAML file
- Run command
- Get instant local validation errors
- Fix once and succeed
Pre-flight validation saves time and catches errors before they hit your API logs.
Validation Layers
KDX CLI validates at two levels:
-
Client-side validation (pre-flight)
- Checks required fields
- Validates data types
- Verifies enum values
- Tests format patterns
- Checks min/max values
-
Server-side validation (API response)
- Business logic validation
- Cross-resource constraints
- Permission checks
- Quota limits
Both provide structured, field-level error messages.
Developing Custom Plugins
Custom plugin development requires Go programming knowledge and familiarity with the KDX CLI codebase. The plugin API is subject to change during early access.
Plugin Interface
Plugins implement the ResourcePlugin interface:
type ResourcePlugin interface {
// ResourceType returns the resource type (e.g., "workspace", "store")
ResourceType() string
// Commands returns custom cobra commands for this resource
Commands(client *Client, discovery *ResourceDiscovery) []*cobra.Command
}
Creating a Plugin
Step 1: Create plugin directory
mkdir internal/plugins/myresource
Step 2: Implement the plugin
// internal/plugins/myresource/myresource.go
package myresource
import (
"fmt"
"github.com/kodexa-ai/kdx-cli/internal/api"
"github.com/spf13/cobra"
)
type MyResourcePlugin struct{}
func (p *MyResourcePlugin) ResourceType() string {
return "myresource"
}
func (p *MyResourcePlugin) Commands(
client *api.Client,
discovery *api.ResourceDiscovery,
) []*cobra.Command {
return []*cobra.Command{
p.statusCommand(client, discovery),
p.customCommand(client, discovery),
}
}
func (p *MyResourcePlugin) statusCommand(
client *api.Client,
discovery *api.ResourceDiscovery,
) *cobra.Command {
return &cobra.Command{
Use: "status [name]",
Short: "Show resource status",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
name := args[0]
// Make API call
path := fmt.Sprintf("/api/myresources/%s/status", name)
resp, err := client.Get(path)
if err != nil {
return err
}
// Display results
fmt.Printf("Status for %s: %s\n", name, resp.Status)
return nil
},
}
}
func (p *MyResourcePlugin) customCommand(
client *api.Client,
discovery *api.ResourceDiscovery,
) *cobra.Command {
var force bool
cmd := &cobra.Command{
Use: "custom [name]",
Short: "Execute custom operation",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
name := args[0]
// Build request
payload := map[string]interface{}{
"force": force,
}
// Make API call
path := fmt.Sprintf("/api/myresources/%s/custom", name)
resp, err := client.Post(path, payload)
if err != nil {
return err
}
fmt.Printf("Operation completed: %s\n", resp.Message)
return nil
},
}
cmd.Flags().BoolVar(&force, "force", false, "Force operation")
return cmd
}
Step 3: Register the plugin
// internal/plugins/init.go
package plugins
import (
"github.com/kodexa-ai/kdx-cli/internal/plugins/myresource"
"github.com/kodexa-ai/kdx-cli/internal/plugins/workspace"
"github.com/kodexa-ai/kdx-cli/internal/plugins/store"
)
func RegisterPlugins(registry *PluginRegistry) {
registry.Register(&workspace.WorkspacePlugin{})
registry.Register(&store.StorePlugin{})
registry.Register(&myresource.MyResourcePlugin{}) // Add your plugin
}
Step 4: Build and test
# Build the CLI
make build
# Test your plugin
./bin/kdx myresource status test-resource
./bin/kdx myresource custom test-resource --force
Plugin Best Practices
1. Provide Helpful Error Messages
if name == "" {
return fmt.Errorf("resource name is required")
}
if err != nil {
return fmt.Errorf("failed to fetch status: %w", err)
}
2. Use Flags for Options
cmd.Flags().BoolVar(&force, "force", false, "Force operation")
cmd.Flags().StringVar(&collection, "collection", "", "Target collection")
cmd.Flags().IntVar(&timeout, "timeout", 30, "Timeout in seconds")
if timeout < 1 || timeout > 300 {
return fmt.Errorf("timeout must be between 1 and 300 seconds")
}
outputFormat, _ := cmd.Flags().GetString("output")
switch outputFormat {
case "json":
json.NewEncoder(os.Stdout).Encode(result)
case "yaml":
yaml.NewEncoder(os.Stdout).Encode(result)
default:
// Pretty print table
printTable(result)
}
5. Handle API Errors Gracefully
resp, err := client.Post(path, payload)
if err != nil {
if apiErr, ok := err.(*api.Error); ok {
return fmt.Errorf("API error: %s (code: %d)", apiErr.Message, apiErr.Code)
}
return fmt.Errorf("request failed: %w", err)
}
Plugin Use Cases
Maintenance Operations
# Clean up old data
kdx workspace exec my-workspace "cleanup --older-than 90d"
# Optimize store indexes
kdx store reindex my-store --optimize
# Verify data integrity
kdx workspace exec my-workspace "verify-integrity"
Monitoring & Observability
# Check workspace health
kdx workspace status prod-workspace
# Monitor store performance
kdx store stats prod-store
# Get resource metrics
kdx myresource metrics prod-instance
Administrative Tasks
# Manage users
kdx workspace users list my-workspace
kdx workspace users add my-workspace alice@example.com
# Backup and restore
kdx workspace backup my-workspace --output backup.tar.gz
kdx workspace restore my-workspace --input backup.tar.gz
Development & Testing
# Run tests
kdx assistant test my-assistant --input test-cases.json
# Evaluate model performance
kdx model evaluate my-model --dataset validation.csv
# Generate synthetic data
kdx workspace exec dev-workspace "generate-test-data --count 1000"
API Evolution & Compatibility
During early access, the plugin API may change. We’ll provide migration guides for breaking changes.
Versioning Strategy
Future plugin system will support versioning:
type ResourcePlugin interface {
ResourceType() string
Version() string // e.g., "v1", "v2"
Commands(client *Client, discovery *ResourceDiscovery) []*cobra.Command
}
Maintaining Compatibility
When developing plugins:
- Test against multiple KDX CLI versions
- Document required CLI version in plugin README
- Handle API changes gracefully with version checks
- Follow semantic versioning for your plugins
Staying Updated
- Subscribe to KDX CLI release notes
- Test plugins against beta releases
- Join the Kodexa developer community
- Report compatibility issues early
Troubleshooting
Plugin command not found
Ensure the plugin is registered:
# List all available commands
kdx --help
# Check specific resource commands
kdx workspace --help
API endpoint not found
The platform may not support the operation:
# Check platform version
kdx version
# Verify API resources
kdx api-resources --refresh
Permission denied
Check your API key permissions:
# Verify profile
kdx config current-profile
# Test basic access
kdx get workspaces
Next Steps