# Directus Schema Management System
This document provides a comprehensive guide for managing Directus database schemas using our custom schema management tools.
## š Project Structure
```
tpl.mcp-server/
āāā schemas/ # Schema definition files
ā āāā tasks.json # Task collection schema
āāā scripts/ # Management scripts
ā āāā upload-schema.js # Schema upload utility
āāā src/
ā āāā models/
ā āāā Task.ts # TypeScript model definitions
āāā .env # Environment configuration
āāā package.json # Project dependencies and scripts
```
## š Quick Start
### Prerequisites
1. **Environment Setup**: Ensure your `.env` file contains:
```env
DIRECTUS_URL=https://your-directus-instance.com/
DIRECTUS_TOKEN=your-admin-token-here
NODE_ENV=development
```
2. **Dependencies**: Install required packages:
```bash
npm install
```
### Creating Your First Schema
1. **Create a schema file** in the `schemas/` directory:
```bash
# Example: schemas/my-collection.json
```
2. **Upload the schema** to Directus:
```bash
npm run upload-schema schemas/my-collection.json
```
## š Schema File Format
Schema files use a simple JSON format that defines collections and their fields:
### Basic Structure
```json
{
"name": "collection_name",
"comment": "Description of the collection",
"fields": [
{
"field": "field_name",
"type": "field_type",
"required": true,
"comment": "Field description"
}
]
}
```
### Field Types
| Type | Description | Database Type |
|------|-------------|---------------|
| `uuid` | UUID primary key | `uuid` |
| `string` | Text field with length limit | `varchar` |
| `text` | Long text field | `text` |
| `integer` | Whole numbers | `integer` |
| `decimal` | Decimal numbers | `decimal` |
| `float` | Floating point numbers | `real` |
| `boolean` | True/false values | `boolean` |
| `date` | Date only | `date` |
| `timestamp` | Date and time | `timestamp` |
| `json` | JSON data | `json` |
### Field Properties
| Property | Type | Description | Example |
|----------|------|-------------|---------|
| `field` | string | Field name (required) | `"title"` |
| `type` | string | Field type (required) | `"string"` |
| `required` | boolean | Field is required | `true` |
| `nullable` | boolean | Field can be null | `false` |
| `primary` | boolean | Primary key field | `true` |
| `unique` | boolean | Unique constraint | `true` |
| `readonly` | boolean | Read-only in UI | `true` |
| `hidden` | boolean | Hidden in UI | `true` |
| `length` | number | Max length for strings | `255` |
| `default_value` | any | Default value | `"draft"` |
| `enum` | array | Allowed values | `["draft", "published"]` |
| `comment` | string | Field description | `"User's email address"` |
### Special Fields
#### Primary Key (UUID)
```json
{
"field": "id",
"type": "uuid",
"primary": true,
"required": true,
"readonly": true,
"hidden": true,
"comment": "Primary key"
}
```
#### Enum/Select Field
```json
{
"field": "status",
"type": "string",
"length": 50,
"required": true,
"enum": ["draft", "published", "archived"],
"default_value": "draft",
"comment": "Content status"
}
```
#### Timestamps
```json
{
"field": "created_at",
"type": "timestamp",
"required": true,
"readonly": true,
"hidden": true,
"comment": "Creation timestamp"
}
```
## š Complete Example: Tasks Collection
Here's the complete `schemas/tasks.json` file as a reference:
```json
{
"name": "tasks",
"comment": "Task management collection for MCP server",
"fields": [
{
"field": "id",
"type": "uuid",
"primary": true,
"required": true,
"readonly": true,
"hidden": true,
"comment": "Primary key"
},
{
"field": "title",
"type": "string",
"length": 255,
"required": true,
"comment": "Task title"
},
{
"field": "description",
"type": "text",
"nullable": true,
"comment": "Task description"
},
{
"field": "status",
"type": "string",
"length": 50,
"default_value": "todo",
"required": true,
"enum": ["todo", "in_progress", "completed"],
"comment": "Task status"
},
{
"field": "priority",
"type": "string",
"length": 20,
"default_value": "medium",
"required": true,
"enum": ["low", "medium", "high"],
"comment": "Task priority"
},
{
"field": "due_date",
"type": "timestamp",
"nullable": true,
"comment": "Task due date"
},
{
"field": "created_at",
"type": "timestamp",
"required": true,
"readonly": true,
"hidden": true,
"comment": "Creation timestamp"
},
{
"field": "updated_at",
"type": "timestamp",
"required": true,
"readonly": true,
"hidden": true,
"comment": "Last update timestamp"
}
]
}
```
## š ļø Upload Script Usage
### Basic Upload
```bash
npm run upload-schema schemas/my-collection.json
```
### Direct Script Usage
```bash
node scripts/upload-schema.js schemas/my-collection.json
```
### Script Features
- ā
**Connection Testing**: Verifies Directus connection before upload
- ā
**Collision Detection**: Checks if collection already exists
- ā
**Field Creation**: Creates all fields with proper types and constraints
- ā
**Error Handling**: Continues with other fields if one fails
- ā
**Enum Support**: Automatically creates dropdown interfaces for enum fields
- ā
**Special Fields**: Handles UUIDs, timestamps, and other special field types
### Upload Output Example
```
š Starting schema upload: schemas/tasks.json
š Directus URL: https://your-directus-instance.com/
š Using token: ***Wq8y
š Schema loaded: tasks
š Fields: 8
ā
Connected to Directus successfully
š Checking if collection "tasks" exists...
š Collection "tasks" does not exist - will create
š¦ Creating collection: tasks
ā
Collection created successfully
š Creating 8 fields...
š Creating field: id (uuid)
ā Field creation failed: id - Field "id" already exists
š Creating field: title (string)
ā
Field created: title
š Creating field: description (text)
ā
Field created: description
š Creating field: status (string)
ā
Field created: status
š Creating field: priority (string)
ā
Field created: priority
š Creating field: due_date (timestamp)
ā
Field created: due_date
š Creating field: created_at (timestamp)
ā
Field created: created_at
š Creating field: updated_at (timestamp)
ā
Field created: updated_at
š Schema upload completed successfully!
š Collection: tasks
š Fields processed: 8
š Access at: https://your-directus-instance.com/admin/content/tasks
```
## š§ Advanced Usage
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `DIRECTUS_URL` | Directus instance URL | Required |
| `DIRECTUS_TOKEN` | Admin API token | Required |
| `NODE_ENV` | Environment mode | `development` |
### Token Requirements
The `DIRECTUS_TOKEN` must have the following permissions:
- **Collections**: Create, Read, Update
- **Fields**: Create, Read, Update
- **Schema**: Read access to `/server/info`
### Creating Admin Tokens
1. Log into your Directus admin panel
2. Go to **Settings** ā **Access Tokens**
3. Create a new token with **Admin** role
4. Copy the token to your `.env` file
## š Best Practices
### Schema Design
1. **Use descriptive field names**: `user_email` instead of `email`
2. **Add comments**: Document the purpose of each field
3. **Set appropriate lengths**: Don't use unlimited text for short strings
4. **Use enums for fixed values**: Status fields, categories, etc.
5. **Include timestamps**: `created_at` and `updated_at` for audit trails
### File Organization
1. **One collection per file**: `schemas/users.json`, `schemas/posts.json`
2. **Descriptive filenames**: Match the collection name
3. **Version control**: Commit schema files to track changes
4. **Backup before changes**: Test on development environment first
### Development Workflow
1. **Design the schema** in your preferred tool
2. **Create the JSON file** following our format
3. **Test upload** on development environment
4. **Verify in Directus UI** that fields appear correctly
5. **Test data entry** to ensure validation works
6. **Deploy to production** when ready
## šØ Troubleshooting
### Common Issues
#### Authentication Errors
```
ā Failed to connect to Directus: 401 Unauthorized
```
**Solution**: Check your `DIRECTUS_TOKEN` in the `.env` file
#### Collection Already Exists
```
ā ļø Collection "tasks" already exists. Skipping creation.
```
**Solution**: This is normal. The script will add missing fields to existing collections.
#### Field Creation Fails
```
ā Field creation failed: title - Invalid field type
```
**Solution**: Check the field type is supported (see Field Types table above)
#### Permission Errors
```
ā Error creating collection: 403 Forbidden
```
**Solution**: Ensure your token has admin permissions
### Debug Mode
For detailed error information, check the full error response in the console output. The script shows complete API responses for debugging.
## š Migration and Updates
### Adding Fields to Existing Collections
1. Add the new field to your schema JSON file
2. Run the upload script again
3. Only new fields will be created; existing fields are skipped
### Modifying Existing Fields
ā ļø **Warning**: The upload script doesn't modify existing fields. To change field properties:
1. Use the Directus admin interface, or
2. Create a new collection with the updated schema, or
3. Manually update via the Directus API
### Schema Versioning
Consider maintaining schema versions:
```
schemas/
āāā v1/
ā āāā tasks.json
āāā v2/
ā āāā tasks.json
āāā current/
āāā tasks.json ā ../v2/tasks.json
```
## š Support
For issues or questions about the schema management system:
1. Check this documentation first
2. Review the console output for specific error messages
3. Verify your Directus permissions and token
4. Test with a simple schema first
## š Related Files
- **`schemas/tasks.json`**: Example schema file
- **`scripts/upload-schema.js`**: Upload utility script
- **`src/models/Task.ts`**: TypeScript model definitions
- **`.env`**: Environment configuration
- **`package.json`**: NPM scripts and dependencies
---
*This documentation covers the complete Directus schema management workflow. Keep this file updated as the system evolves.*