# 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.*