# Write Module Implementation
This document describes the implementation of the Komodo MCP Write module with 21 CRUD operations.
## Overview
The Write module (`src/modules/write.ts`) implements create, update, and delete operations for 7 resource types in the Komodo API.
## Resource Types
| Resource | Create | Update | Delete | Total |
|----------|--------|--------|--------|-------|
| Server | ✓ | ✓ | ✓ | 3 |
| Deployment | ✓ | ✓ | ✓ | 3 |
| Stack | ✓ | ✓ | ✓ | 3 |
| Build | ✓ | ✓ | ✓ | 3 |
| Repo | ✓ | ✓ | ✓ | 3 |
| Procedure | ✓ | ✓ | ✓ | 3 |
| Action | ✓ | ✓ | ✓ | 3 |
| **Total** | | | | **21** |
## Functions
### Server Operations
#### `createServer(config: CreateServerRequest): Promise<KomodoResponse<Server>>`
Creates a new server.
**Required Fields:**
- `name` (string) - Server name
- `address` (string) - Server address
**Optional Fields:**
- `port` (number) - Server port (1-65535)
- `region` (string) - Server region
- `provider` (string) - Cloud provider
- `tags` (string[]) - Server tags
- `enabled` (boolean) - Enable/disable server
- `metadata` (object) - Additional metadata
**Validation:**
- Name and address must be non-empty strings
- Port must be 1-65535
- Tags must be an array if provided
- Metadata must be an object if provided
**Example:**
```typescript
const server = await createServer({
name: 'production-web-01',
address: '192.168.1.100',
port: 22,
region: 'us-east-1',
provider: 'aws',
tags: ['production', 'web'],
enabled: true
});
```
---
#### `updateServer(id: string, config: UpdateServerRequest): Promise<KomodoResponse<Server>>`
Updates an existing server.
**Parameters:**
- `id` (string) - Server ID (required)
- `config` (object) - Fields to update (all optional)
**Example:**
```typescript
const updated = await updateServer('server-123', {
enabled: false,
tags: ['production', 'web', 'maintenance']
});
```
---
#### `deleteServer(id: string): Promise<KomodoResponse<DeleteResponse>>`
Deletes a server.
**Parameters:**
- `id` (string) - Server ID (required)
**Example:**
```typescript
const result = await deleteServer('server-123');
```
---
### Deployment Operations
#### `createDeployment(config: CreateDeploymentRequest): Promise<KomodoResponse<Deployment>>`
Creates a new deployment.
**Required Fields:**
- `name` (string) - Deployment name
- `serverId` (string) - Target server ID
**Optional Fields:**
- `image` (string) - Docker image
- `dockerCompose` (string) - Docker Compose configuration
- `environment` (object) - Environment variables
- `volumes` (string[]) - Volume mappings
- `networks` (string[]) - Network configurations
- `ports` (array) - Port mappings `{ host: number, container: number }`
- `restart` (enum) - Restart policy: `no`, `always`, `on-failure`, `unless-stopped`
- `enabled` (boolean) - Enable/disable deployment
- `metadata` (object) - Additional metadata
**Example:**
```typescript
const deployment = await createDeployment({
name: 'api-service',
serverId: 'server-123',
image: 'myapp:latest',
environment: {
NODE_ENV: 'production',
PORT: '3000'
},
ports: [{ host: 80, container: 3000 }],
restart: 'always',
enabled: true
});
```
---
#### `updateDeployment(id: string, config: UpdateDeploymentRequest): Promise<KomodoResponse<Deployment>>`
Updates an existing deployment.
**Example:**
```typescript
const updated = await updateDeployment('deploy-456', {
image: 'myapp:v2.0',
environment: {
NODE_ENV: 'production',
PORT: '3000',
NEW_FEATURE_FLAG: 'true'
}
});
```
---
#### `deleteDeployment(id: string): Promise<KomodoResponse<DeleteResponse>>`
Deletes a deployment.
---
### Stack Operations
#### `createStack(config: CreateStackRequest): Promise<KomodoResponse<Stack>>`
Creates a new Docker Compose stack.
**Required Fields:**
- `name` (string) - Stack name
- `composeFile` (string) - Docker Compose file content
**Optional Fields:**
- `environment` (object) - Environment variables
- `projectName` (string) - Docker Compose project name
- `enabled` (boolean) - Enable/disable stack
- `metadata` (object) - Additional metadata
**Example:**
```typescript
const stack = await createStack({
name: 'monitoring-stack',
composeFile: `
version: '3.8'
services:
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
`,
projectName: 'monitoring',
enabled: true
});
```
---
#### `updateStack(id: string, config: UpdateStackRequest): Promise<KomodoResponse<Stack>>`
Updates an existing stack.
---
#### `deleteStack(id: string): Promise<KomodoResponse<DeleteResponse>>`
Deletes a stack.
---
### Build Operations
#### `createBuild(config: CreateBuildRequest): Promise<KomodoResponse<Build>>`
Creates a new build configuration.
**Required Fields:**
- `name` (string) - Build name
- `repoId` (string) - Repository ID
**Optional Fields:**
- `dockerfile` (string) - Path to Dockerfile
- `context` (string) - Build context path
- `buildArgs` (object) - Build arguments
- `target` (string) - Build target stage
- `tags` (string[]) - Image tags
- `enabled` (boolean) - Enable/disable build
- `metadata` (object) - Additional metadata
**Example:**
```typescript
const build = await createBuild({
name: 'api-build',
repoId: 'repo-789',
dockerfile: './Dockerfile',
context: '.',
buildArgs: {
NODE_VERSION: '18',
BUILD_ENV: 'production'
},
tags: ['latest', 'v1.0.0'],
enabled: true
});
```
---
#### `updateBuild(id: string, config: UpdateBuildRequest): Promise<KomodoResponse<Build>>`
Updates an existing build.
---
#### `deleteBuild(id: string): Promise<KomodoResponse<DeleteResponse>>`
Deletes a build.
---
### Repo Operations
#### `createRepo(config: CreateRepoRequest): Promise<KomodoResponse<Repo>>`
Creates a new repository.
**Required Fields:**
- `name` (string) - Repository name
- `url` (string) - Git repository URL
**Optional Fields:**
- `branch` (string) - Git branch (default: main/master)
- `credentials` (object) - Authentication credentials
- `username` (string) - Git username
- `password` (string) - Git password/token
- `sshKey` (string) - SSH private key
- `autoSync` (boolean) - Enable auto-sync
- `webhookSecret` (string) - Webhook secret for auto-sync
- `enabled` (boolean) - Enable/disable repo
- `metadata` (object) - Additional metadata
**Validation:**
- URL must be a valid URL format
**Example:**
```typescript
const repo = await createRepo({
name: 'my-app',
url: 'https://github.com/org/repo.git',
branch: 'main',
credentials: {
username: 'git-user',
password: 'ghp_token123'
},
autoSync: true,
enabled: true
});
```
---
#### `updateRepo(id: string, config: UpdateRepoRequest): Promise<KomodoResponse<Repo>>`
Updates an existing repository.
---
#### `deleteRepo(id: string): Promise<KomodoResponse<DeleteResponse>>`
Deletes a repository.
---
### Procedure Operations
#### `createProcedure(config: CreateProcedureRequest): Promise<KomodoResponse<Procedure>>`
Creates a new automated procedure.
**Required Fields:**
- `name` (string) - Procedure name
- `steps` (array) - Procedure steps (non-empty array)
- `type` (enum) - Step type: `command`, `script`, `api-call`
- `command` (string) - Shell command (for command type)
- `script` (string) - Script content (for script type)
- `apiEndpoint` (string) - API endpoint (for api-call type)
- `timeout` (number) - Step timeout in ms
- `continueOnError` (boolean) - Continue on error
**Optional Fields:**
- `description` (string) - Procedure description
- `schedule` (string) - Cron schedule for automation
- `enabled` (boolean) - Enable/disable procedure
- `metadata` (object) - Additional metadata
**Validation:**
- Steps must be a non-empty array
- Each step must have a valid type
- Schedule must be valid cron format (5-6 parts)
**Example:**
```typescript
const procedure = await createProcedure({
name: 'deploy-and-test',
description: 'Deploy application and run tests',
steps: [
{
type: 'command',
command: 'docker pull myapp:latest',
timeout: 60000,
continueOnError: false
},
{
type: 'script',
script: '#!/bin/bash\ncd /app && npm test',
timeout: 120000,
continueOnError: false
},
{
type: 'api-call',
apiEndpoint: 'https://api.example.com/notify',
timeout: 5000,
continueOnError: true
}
],
schedule: '0 2 * * *', // Daily at 2 AM
enabled: true
});
```
---
#### `updateProcedure(id: string, config: UpdateProcedureRequest): Promise<KomodoResponse<Procedure>>`
Updates an existing procedure.
---
#### `deleteProcedure(id: string): Promise<KomodoResponse<DeleteResponse>>`
Deletes a procedure.
---
### Action Operations
#### `createAction(config: CreateActionRequest): Promise<KomodoResponse<Action>>`
Creates a new automated action.
**Required Fields:**
- `name` (string) - Action name
- `trigger` (object) - Trigger configuration
- `type` (enum) - Trigger type: `manual`, `webhook`, `schedule`, `event`
- `schedule` (string) - Cron schedule (for schedule type)
- `event` (string) - Event name (for event type)
- `webhookSecret` (string) - Webhook secret (for webhook type)
- `action` (object) - Action configuration
- `type` (enum) - Action type: `deployment`, `build`, `procedure`, `command`
- `targetId` (string) - Target resource ID
- `command` (string) - Command to execute (for command type)
- `parameters` (object) - Action parameters
**Optional Fields:**
- `description` (string) - Action description
- `enabled` (boolean) - Enable/disable action
- `metadata` (object) - Additional metadata
**Example:**
```typescript
const action = await createAction({
name: 'auto-deploy-on-push',
description: 'Deploy when code is pushed to main',
trigger: {
type: 'webhook',
webhookSecret: 'secret123'
},
action: {
type: 'deployment',
targetId: 'deploy-456',
parameters: {
forceRecreate: true
}
},
enabled: true
});
```
---
#### `updateAction(id: string, config: UpdateActionRequest): Promise<KomodoResponse<Action>>`
Updates an existing action.
---
#### `deleteAction(id: string): Promise<KomodoResponse<DeleteResponse>>`
Deletes an action.
---
## Validation
All functions include comprehensive input validation:
### Common Validations
- **Required fields**: Missing required fields throw validation errors
- **String fields**: Must be non-empty strings
- **URLs**: Must be valid URL format
- **Ports**: Must be integers 1-65535
- **Arrays**: Must be arrays if provided
- **Objects**: Must be objects if provided
- **Cron expressions**: Must have 5-6 parts
### Enum Validations
- **Restart policy**: `no`, `always`, `on-failure`, `unless-stopped`
- **Step type**: `command`, `script`, `api-call`
- **Trigger type**: `manual`, `webhook`, `schedule`, `event`
- **Action type**: `deployment`, `build`, `procedure`, `command`
## Error Handling
All functions use consistent error handling:
```typescript
try {
const result = await createServer({ name: 'test', address: '127.0.0.1' });
console.log(result.data);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
} else {
console.error('API error:', error.message);
}
}
```
## Response Format
All operations return a standardized response:
```typescript
interface KomodoResponse<T> {
success: boolean;
data?: T;
error?: string;
message?: string;
}
```
**Success Response:**
```json
{
"success": true,
"data": {
"id": "server-123",
"name": "production-web-01",
"status": "online",
"createdAt": "2024-01-26T12:00:00Z",
"updatedAt": "2024-01-26T12:00:00Z"
}
}
```
**Error Response:**
```json
{
"success": false,
"error": "Server not found",
"message": "No server exists with ID: server-999"
}
```
**Delete Response:**
```json
{
"success": true,
"data": {
"success": true,
"message": "Server deleted successfully",
"deletedId": "server-123"
}
}
```
## Dependencies
The Write module depends on:
- **API Client** (`src/utils/api-client.ts`) - HTTP request utilities
- **Validation** (`src/utils/validation.ts`) - Input validation
- **Types** (`src/types/api.ts`) - TypeScript type definitions
## Implementation Status
| Function | Implemented | Validated | Documented |
|----------|-------------|-----------|------------|
| createServer | ✓ | ✓ | ✓ |
| updateServer | ✓ | ✓ | ✓ |
| deleteServer | ✓ | ✓ | ✓ |
| createDeployment | ✓ | ✓ | ✓ |
| updateDeployment | ✓ | ✓ | ✓ |
| deleteDeployment | ✓ | ✓ | ✓ |
| createStack | ✓ | ✓ | ✓ |
| updateStack | ✓ | ✓ | ✓ |
| deleteStack | ✓ | ✓ | ✓ |
| createBuild | ✓ | ✓ | ✓ |
| updateBuild | ✓ | ✓ | ✓ |
| deleteBuild | ✓ | ✓ | ✓ |
| createRepo | ✓ | ✓ | ✓ |
| updateRepo | ✓ | ✓ | ✓ |
| deleteRepo | ✓ | ✓ | ✓ |
| createProcedure | ✓ | ✓ | ✓ |
| updateProcedure | ✓ | ✓ | ✓ |
| deleteProcedure | ✓ | ✓ | ✓ |
| createAction | ✓ | ✓ | ✓ |
| updateAction | ✓ | ✓ | ✓ |
| deleteAction | ✓ | ✓ | ✓ |
| **Total** | **21/21** | **21/21** | **21/21** |
## Next Steps
1. Create MCP tool wrappers for each function
2. Add comprehensive unit tests
3. Implement integration tests with mock API
4. Add usage examples in main documentation
5. Create TypeScript declaration exports
## Related Documentation
- [API Mapping](./API_MAPPING.md) - Complete API reference
- [Environment Configuration](./ENVIRONMENT.md) - Setup guide