npm package: @172ai/containers-mcp-server
Description: MCP server for 172.ai container management platform - enables AI assistants to manage containers, builds, and files with comprehensive workflow prompts
Author: 172.ai
Latest version: 1.13.2

# 172.ai Container Management MCP Server

A **Model Context Protocol (MCP) server** that provides AI assistants with access to the 172.ai container management platform. This server exposes powerful tools for managing containers, builds, executions, files, and capabilities through a standardized MCP interface, enabling natural language interactions with your containerized applications.

🌐 **Live Documentation**: [https://172.ai/#/mcp](https://172.ai/#/mcp)

[![npm version](https://badge.fury.io/js/@172ai%2Fcontainers-mcp-server.svg)](https://www.npmjs.com/package/@172ai/containers-mcp-server)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 🚀 Quick Start

```bash
# Install globally
npm install -g @172ai/containers-mcp-server

# Run interactive setup
containers-mcp-server --setup

# Test configuration and authentication
containers-mcp-server --test
# Start the server
containers-mcp-server
```

## ✨ Features

### Container Management
- **List Containers**: Browse available containers with filtering options
- **Get Container Details**: Retrieve detailed information about specific containers
- **Create Container**: Create new container templates
- **Update Container**: Modify existing container configurations
- **Delete Container**: Remove containers from the system
- **Copy Container**: Create copies of existing containers

### Build Management
- **Build Container**: Initiate container build processes
- **Get Build Status**: Monitor build progress and status
- **List Builds**: View build history for containers
- **Get Build Logs**: Access detailed build logs and output
- **Explain Build Logs**: Get AI-powered analysis and explanations of build failures

### Container Fix Management
- **Fix Container**: Automatically analyze build failures, apply AI-generated fixes, and rebuild (primary workflow)
- **Analyze Container Failure**: Analyze build/execution failures without auto-applying fixes (for review workflows)
- **Approve and Apply Fix**: Apply a specific fix attempt after reviewing analysis results
- **Get Fix History**: View all fix attempts for a container with their outcomes
- **Get Fix Status**: Get detailed status and information about a specific fix attempt

### File Management
- **List Container Files**: Browse files within containers
- **Get File Content**: Read file contents
- **Upload Files**: Add new files to containers
- **Update Files**: Modify existing file contents
- **Delete Files**: Remove files from containers

### Container Execution Management
- **Start Execution**: Deploy and run containers with configurable duration
- **Stop Execution**: Stop running container executions
- **Get Execution Status**: Check current execution status and progress
- **List Executions**: View active container executions for the user
- **Get Execution Progress**: Monitor detailed execution progress and logs
- **Get Execution Logs**: Access real-time execution logs and debugging info
- **Extend Execution**: Extend the duration of running executions
- **Get Execution History**: View complete execution history for containers

### Capability Management
- **List Capabilities**: View available system capabilities
- **Get Capability Details**: Access detailed capability information
- **Search Capabilities**: Find capabilities by name or description

## Installation

1. **Clone or create the MCP server directory**:
   ```bash
   mkdir containers-mcp-server
   cd containers-mcp-server
   ```

2. **Install dependencies**:
   ```bash
   npm install
   ```

3. **Configure environment variables**:
   ```bash
   cp .env.example .env
   # Edit .env with your configuration
   ```

4. **Build the project**:
   ```bash
   npm run build
   ```

## Configuration

### Environment Variables

The server requires configuration through environment variables. Copy `.env.example` to `.env` and configure:

#### Required Settings
- `CONTAINER_API_URL`: Base URL for the container management API
- Authentication (choose one):
  - `API_KEY`: Your API key for authentication
  - `OAUTH_TOKEN`: OAuth token for temporary access
  - `OAUTH_CLIENT_ID` + `OAUTH_CLIENT_SECRET`: For automated token refresh

#### Optional Settings
- `NODE_ENV`: Environment (development, production, test)
- `LOG_LEVEL`: Logging verbosity (error, warn, info, debug)
- `RATE_LIMIT_PER_MINUTE`: API rate limiting
- `REQUEST_TIMEOUT`: Request timeout in milliseconds
- `MAX_RETRIES`: Number of retry attempts for failed requests

### Authentication Methods

The server supports three authentication methods:

1. **API Key** (Recommended for production):
   ```bash
   API_KEY=your_api_key_here
   ```

2. **OAuth Token** (For temporary access):
   ```bash
   OAUTH_TOKEN=your_oauth_token_here
   ```

3. **OAuth Client Credentials** (For automated systems):
   ```bash
   OAUTH_CLIENT_ID=your_client_id_here
   OAUTH_CLIENT_SECRET=your_client_secret_here
   ```

## Usage

### Running the Server

#### Development Mode
```bash
npm run dev
```

#### Production Mode
```bash
npm start
```

### Connecting to Claude Code

1. **Add to your Claude Code configuration**:
   ```json
   {
     "mcpServers": {
       "containers": {
         "command": "node",
         "args": ["/path/to/containers-mcp-server/dist/server.js"],
         "env": {
           "CONTAINER_API_URL": "http://localhost:3000",
           "API_KEY": "your_api_key_here"
         }
       }
     }
   }
   ```

2. **Restart Claude Code** to load the new server

### Available Tools

Once connected, you can use these tools in your AI conversations:

#### Container Operations
- `list_containers` - List available containers
- `get_container` - Get detailed container information
- `create_container` - Create new container templates
- `update_container` - Update container configurations
- `delete_container` - Remove containers
- `copy_container` - Create container copies

#### Build Operations
- `build_container` - Start container builds
- `get_build_status` - Check build progress
- `list_builds` - View build history
- `explain_build_logs` - Get AI analysis of build failures

#### Fix Operations
- `fix_container` - Auto-analyze, fix, and rebuild failed containers
- `analyze_container_failure` - Analyze failures without auto-applying fixes
- `approve_and_apply_fix` - Apply a specific fix after review
- `get_fix_history` - View all fix attempts for a container
- `get_fix_status` - Get details of a specific fix attempt

#### Execution Operations
- `start_execution` - Deploy and run containers
- `stop_execution` - Stop running container executions
- `get_execution_status` - Check execution status and progress
- `list_executions` - List active container executions
- `get_execution_progress` - Monitor execution progress with logs
- `get_execution_logs` - Access real-time execution logs
- `extend_execution` - Extend duration of running executions
- `get_execution_history` - View execution history for containers

#### File Operations
- `list_container_files` - Browse container files
- `get_file_content` - Read file contents
- `upload_file` - Add files to containers

#### Capability Operations
- `list_capabilities` - View available capabilities

### Example Usage

```typescript
// List public containers
await listContainers({ scope: 'public', limit: 10 });

// Get container details
await getContainer({ containerId: 'container-123' });

// Build a container
await buildContainer({ containerId: 'container-123' });

// Fix a failed container automatically
await fixContainer({
  containerId: 'container-123',
  autoApply: true,
  progressToken: 'fix-progress-123'
});

// Analyze failure without auto-applying
const analysis = await analyzeContainerFailure({
  containerId: 'container-123'
});

// Review and approve a specific fix
await approveAndApplyFix({
  containerId: 'container-123',
  fixAttemptId: analysis.fixAttemptId
});

// View fix history
await getFixHistory({
  containerId: 'container-123',
  limit: 10
});

// Deploy and run a container
await startExecution({ 
  containerId: 'container-123', 
  durationDays: 7 
});

// Check execution status
await getExecutionStatus({ containerId: 'container-123' });

// List all active executions
await listExecutions({ limit: 20 });

// Stop a running container
await stopExecution({ containerId: 'container-123' });

// Upload a file
await uploadFile({ 
  containerId: 'container-123',
  filePath: 'src/app.js',
  content: 'console.log("Hello, world!");',
  mimeType: 'application/javascript'
});
```

## API Reference

### Tool Parameters

#### `list_containers`
- `scope`: Filter by scope ('public', 'myCollection', 'all')
- `limit`: Maximum number of results (1-100)
- `offset`: Number of results to skip
- `query`: Search query for filtering

#### `get_container`
- `containerId`: Container ID to retrieve

#### `create_container`
- `name`: Container name
- `description`: Container description
- `dockerfile`: Dockerfile content
- `tags`: Array of tags (optional)
- `isPrivate`: Privacy setting (optional)
- `envVars`: Environment variables (optional)

#### `build_container`
- `containerId`: Container ID to build
- `progressToken`: Optional token for real-time progress notifications

#### `fix_container`
- `containerId`: Container ID to fix
- `autoApply`: Auto-apply fix after analysis (default: true)
- `progressToken`: Optional token for real-time progress notifications

#### `analyze_container_failure`
- `containerId`: Container ID to analyze
- `progressToken`: Optional token for progress notifications

#### `approve_and_apply_fix`
- `containerId`: Container ID
- `fixAttemptId`: Fix attempt ID from analysis result
- `progressToken`: Optional token for progress notifications

#### `get_fix_history`
- `containerId`: Container ID
- `limit`: Maximum number of fix attempts to return (default: 10)

#### `get_fix_status`
- `containerId`: Container ID
- `fixAttemptId`: Fix attempt ID to retrieve

#### `upload_file`
- `containerId`: Target container ID
- `filePath`: File path within container
- `content`: File content (base64 for binary files)
- `mimeType`: MIME type (optional)

## Error Handling

The server provides comprehensive error handling with:

- **Validation errors**: Invalid input parameters
- **Authentication errors**: Invalid or missing credentials
- **Authorization errors**: Insufficient permissions
- **Network errors**: Connection issues
- **Rate limiting**: API quota exceeded
- **Timeouts**: Request timeouts

All errors include:
- Human-readable error messages
- Error codes for programmatic handling
- Request IDs for debugging
- Troubleshooting hints

## Development

### Project Structure
```
containers-mcp-server/
├── server.ts                 # Main server entry point
├── auth.ts                   # Authentication management
├── config.ts                 # Configuration management
├── services/
│   ├── containerService.ts   # Container management
│   ├── buildService.ts       # Build management
│   ├── fileService.ts        # File management
│   └── capabilityService.ts  # Capability management
├── utils/
│   ├── errorHandler.ts       # Error handling utilities
│   └── apiError.ts          # API error classes
├── package.json
├── tsconfig.json
├── .env.example
└── README.md
```

### Available Scripts
- `npm run dev` - Development mode with hot reload
- `npm run build` - Build for production
- `npm run start` - Start production server
- `npm run test` - Run tests
- `npm run lint` - Code linting
- `npm run clean` - Clean build artifacts

### Adding New Tools

1. **Define the tool in `server.ts`**:
   ```typescript
   this.server.registerTool("my_new_tool", {
     title: "My New Tool",
     description: "Description of what it does",
     inputSchema: z.object({
       param1: z.string(),
       param2: z.number().optional()
     })
   }, async ({ param1, param2 }) => {
     // Implementation
   });
   ```

2. **Add service methods** in appropriate service files

3. **Update documentation** and examples

## Troubleshooting

### Common Issues

1. **Authentication Failed**
   - Check API key or OAuth credentials
   - Verify the container API URL is correct
   - Ensure the API key has required scopes

2. **Connection Timeout**
   - Check network connectivity
   - Verify container service is running
   - Increase `REQUEST_TIMEOUT` if needed

3. **Rate Limiting**
   - Reduce request frequency
   - Check `RATE_LIMIT_PER_MINUTE` setting
   - Consider using API key instead of OAuth

4. **Build Failures**
   - Check container configuration
   - Verify Dockerfile syntax
   - Review build logs for errors

### Debug Mode

Enable debug logging:
```bash
LOG_LEVEL=debug npm run dev
```

This provides detailed information about:
- API requests and responses
- Authentication flow
- Error details and stack traces
- Performance metrics

## 🏭 Production Deployment Guide

### Resource Allocation

The platform supports configurable CPU and memory resources for optimal performance:

#### CPU Options
- **1 vCPU**: Light workloads, simple web services, development
- **2 vCPUs**: Web applications, small databases, API services
- **4 vCPUs**: Heavy web apps, medium databases, data processing
- **8 vCPUs**: Large databases, intensive processing, high-traffic apps

#### Memory Options
- **1Gi**: Lightweight services, static sites, simple APIs
- **2Gi**: Web applications, small databases, moderate traffic
- **4Gi**: Medium databases, data processing, higher traffic
- **8Gi**: Large databases, memory-intensive apps, high traffic
- **16Gi**: Enterprise databases, big data processing, heavy workloads

#### Resource Sizing Guidelines

**Web Applications:**
```bash
# Small/Medium (< 1000 users)
start_execution({
  containerId: "your-container-id",
  cpu: "2",
  memory: "2Gi",
  durationDays: 7
})

# Large (1000+ users)
start_execution({
  containerId: "your-container-id",
  cpu: "4",
  memory: "8Gi",
  durationDays: 30
})
```

**Database Workloads:**
```bash
# PostgreSQL/MySQL
start_execution({
  containerId: "your-db-container",
  cpu: "4",
  memory: "8Gi",
  durationDays: 30
})

# MongoDB/Elasticsearch
start_execution({
  containerId: "your-nosql-container",
  cpu: "8",
  memory: "16Gi",
  durationDays: 30
})
```

**Workflow Automation (n8n, Zapier alternatives):**
```bash
start_execution({
  containerId: "workflow-container",
  cpu: "4",
  memory: "8Gi",
  durationDays: 30,
  envVars: {
    DB_TYPE: "sqlite",
    DB_SQLITE_DATABASE: "/home/node/.n8n/database.sqlite",
    N8N_BASIC_AUTH_ACTIVE: "true",
    N8N_BASIC_AUTH_USER: "admin",
    N8N_BASIC_AUTH_PASSWORD: "secure-password"
  }
})
```

### Performance Optimization

#### Resource Planning
1. **Start Conservative**: Begin with 2 CPU / 2Gi memory
2. **Monitor Metrics**: Use `get_container_metrics` to track utilization
3. **Scale Gradually**: Increase resources based on actual usage patterns
4. **Cost Optimization**: Right-size resources to avoid over-provisioning

#### Common Optimization Patterns
```bash
# Development/Testing
cpu: "1", memory: "1Gi"

# Production Web Apps
cpu: "2-4", memory: "2Gi-4Gi"

# Production Databases
cpu: "4-8", memory: "8Gi-16Gi"

# Data Processing/ETL
cpu: "8", memory: "16Gi"
```

### Environment Variable Management

#### Production Environment Setup
```bash
# Security
NODE_ENV=production
API_TIMEOUT=30000
RATE_LIMIT_PER_MINUTE=1000

# Database Configuration
DB_TYPE=sqlite
DB_SQLITE_DATABASE=/app/data/database.sqlite
DB_SQLITE_POOL_SIZE=10
DB_SQLITE_ENABLE_WAL=true

# Application Specific
N8N_BASIC_AUTH_ACTIVE=true
N8N_HOST=0.0.0.0
N8N_PORT=5678
N8N_PROTOCOL=http
```

#### Environment Variable Best Practices
1. **Never hardcode secrets** in Dockerfiles
2. **Use .env files** for local development
3. **Override at runtime** using start_execution envVars
4. **Validate critical vars** in application startup
5. **Document required variables** in your container description

## 📚 Application Deployment Examples

### Example 1: n8n Workflow Automation

Complete production deployment for n8n workflow automation platform:

```javascript
// 1. Create the container with comprehensive Dockerfile
const container = await create_container({
  name: "n8n-workflow-automation",
  description: "Production n8n workflow automation with SQLite persistence",
  dockerfile: `FROM n8nio/n8n:latest

# Set up data directory with proper permissions
USER root
RUN mkdir -p /home/node/.n8n && chown -R node:node /home/node/.n8n
USER node

# Production environment configuration
ENV NODE_ENV=production
ENV DB_TYPE=sqlite
ENV DB_SQLITE_DATABASE=/home/node/.n8n/database.sqlite
ENV DB_SQLITE_POOL_SIZE=10
ENV DB_SQLITE_ENABLE_WAL=true
ENV N8N_BASIC_AUTH_ACTIVE=true
ENV N8N_HOST=0.0.0.0
ENV N8N_PORT=5678

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \\
  CMD curl -f http://localhost:5678/healthz || exit 1

EXPOSE 5678
CMD ["n8n", "start"]`,
  tags: ["workflow-automation", "n8n", "production"],
  envVars: [
    { key: "N8N_BASIC_AUTH_USER", value: "admin" },
    { key: "N8N_BASIC_AUTH_PASSWORD", value: "secure-password-change-me" }
  ]
})

// 2. Build the container
await build_container({ containerId: container.id })

// 3. Start with production resources
await start_execution({
  containerId: container.id,
  cpu: "4",
  memory: "8Gi",
  durationDays: 30
})
```

### Example 2: PostgreSQL Database

```javascript
const dbContainer = await create_container({
  name: "postgresql-production",
  description: "Production PostgreSQL database with persistent storage",
  dockerfile: `FROM postgres:15-alpine

# Install extensions
RUN apk add --no-cache postgresql-contrib

# Configuration
ENV POSTGRES_DB=myapp
ENV POSTGRES_USER=appuser
ENV PGDATA=/var/lib/postgresql/data/pgdata

# Optimization for production
RUN echo "shared_preload_libraries = 'pg_stat_statements'" >> /usr/share/postgresql/postgresql.conf.sample
RUN echo "max_connections = 200" >> /usr/share/postgresql/postgresql.conf.sample
RUN echo "shared_buffers = 256MB" >> /usr/share/postgresql/postgresql.conf.sample

EXPOSE 5432`,
  envVars: [
    { key: "POSTGRES_PASSWORD", value: "secure-db-password" }
  ]
})

await start_execution({
  containerId: dbContainer.id,
  cpu: "4",
  memory: "8Gi",
  durationDays: 30
})
```

### Example 3: Node.js Web Application

```javascript
const webAppContainer = await create_container({
  name: "nodejs-web-app",
  description: "Production Node.js web application with monitoring",
  dockerfile: `FROM node:18-alpine

WORKDIR /app

# Copy package files
COPY package*.json ./
RUN npm ci --only=production

# Copy application code
COPY . .

# Security: run as non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /app
USER nodejs

# Environment setup
ENV NODE_ENV=production
ENV PORT=3000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\
  CMD curl -f http://localhost:3000/health || exit 1

EXPOSE 3000
CMD ["npm", "start"]`,
  tags: ["nodejs", "web-app", "production"]
})

await start_execution({
  containerId: webAppContainer.id,
  cpu: "2",
  memory: "4Gi",
  durationDays: 14
})
```

## 🔧 Troubleshooting Guide

### Common Deployment Issues

#### Container Fails to Start
**Symptoms**: Container status shows "failed" or "stopped"
**Solutions**:
1. Check build logs: `get_build_logs({ containerId, buildLogId })`
2. Verify Dockerfile syntax and base image availability
3. Ensure EXPOSE ports match application ports
4. Check for missing dependencies or environment variables

```bash
# Debug container startup
get_execution_logs({
  executionId: "your-execution-id",
  lines: 100,
  severity: ["ERROR", "WARNING"]
})
```

#### Resource Allocation Problems
**Symptoms**: Application runs slowly or crashes with OOM errors
**Solutions**:
1. Monitor current usage: `get_container_metrics({ containerId })`
2. Increase memory allocation if utilization > 80%
3. Add CPU resources if utilization consistently > 70%
4. Check for memory leaks in application code

```javascript
// Upgrade resources for running container
await stop_execution({ containerId })
await start_execution({
  containerId,
  cpu: "4",        // Increased from 2
  memory: "8Gi",   // Increased from 4Gi
  durationDays: 30
})
```

#### Environment Variable Issues
**Symptoms**: Application configuration errors, database connection failures
**Solutions**:
1. Verify environment variables in Dockerfile
2. Check runtime override in start_execution
3. Ensure sensitive values aren't hardcoded
4. Validate variable formats and required values

```javascript
// Correct environment variable setup
await start_execution({
  containerId: "your-container",
  envVars: {
    DATABASE_URL: "sqlite:///app/data/db.sqlite",
    NODE_ENV: "production",
    PORT: "8080"
  }
})
```

#### Performance Optimization Issues
**Symptoms**: Slow response times, high resource usage, timeout errors
**Solutions**:
1. **CPU Bottlenecks**:
   - Monitor CPU metrics regularly
   - Increase CPU allocation
   - Optimize application code (async operations, caching)

2. **Memory Issues**:
   - Check for memory leaks
   - Increase memory allocation
   - Implement proper garbage collection

3. **I/O Bottlenecks**:
   - Use connection pooling for databases
   - Implement caching strategies
   - Optimize database queries

#### Network and Connectivity Issues
**Symptoms**: Cannot access container, API timeouts, connection refused
**Solutions**:
1. Verify container is running: `get_execution_status({ containerId })`
2. Check exposed ports match application ports
3. Ensure health checks are properly configured
4. Verify firewall and security group settings

```dockerfile
# Correct port configuration
EXPOSE 8080
HEALTHCHECK --interval=30s CMD curl -f http://localhost:8080/health
```

### Debug Mode and Logging

Enable comprehensive debugging:
```bash
# Server-side debugging
LOG_LEVEL=debug containers-mcp-server

# Container-specific logging
get_runtime_logs({
  executionId: "your-execution-id",
  lines: 500,
  severity: ["DEBUG", "INFO", "WARNING", "ERROR"]
})
```

### Performance Monitoring

Monitor container performance:
```javascript
// Get real-time metrics
const metrics = await get_container_metrics({ containerId })

// Check key indicators:
// - CPU utilization < 70% for optimal performance
// - Memory utilization < 80% to avoid OOM
// - Request rate trends for scaling decisions
```

### Getting Help

1. **Check this troubleshooting guide** for common solutions
2. **Enable debug logging** for detailed error information
3. **Monitor metrics** to identify performance bottlenecks
4. **Review execution logs** for application-specific errors
5. **Check resource allocation** against application requirements

For persistent issues:
- Include container ID, execution ID, and error logs
- Provide steps to reproduce the issue
- Share relevant configuration (Dockerfile, environment variables)

## Security

### Best Practices

1. **Use API Keys**: Prefer API keys over OAuth tokens for production
2. **Secure Storage**: Store credentials securely (environment variables, secrets manager)
3. **Network Security**: Use HTTPS endpoints when possible
4. **Access Control**: Use minimum required scopes
5. **Monitoring**: Monitor API usage and errors

### Security Features

- **Request timeout protection**
- **Rate limiting**
- **Input validation**
- **Error message sanitization**
- **SSL/TLS certificate validation**

## License

MIT License - see LICENSE file for details

## Support

For issues and support:
1. Check the troubleshooting section
2. Review error messages and request IDs
3. Enable debug logging for detailed information
4. Create an issue with reproduction steps

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make changes with tests
4. Submit a pull request

Please follow the existing code style and include tests for new functionality.