Skip to main content

CWCloud MCP Public API

This document describes the public API provided by the pkg/mcp package, which allows other Go projects to integrate with CWCloud AI services and create their own MCP servers.

Installation​

go get github.com/cwloudtech/cwcloud-mcp/pkg/mcp

Quick Start​

package main

import (
"log"
"cwcloud-mcp/pkg/mcp"
)

func main() {
// Create a CWCloud client
client := mcp.NewClient(
mcp.DefaultAPIURL,
"your-access-key",
"your-secret-key",
mcp.LogLevelInfo,
)

// Generate AI content
response, err := client.GeneratePrompt(&mcp.PromptRequest{
Adapter: mcp.AdapterGPT4o,
Message: "Hello, World!",
EnableHistory: true,
})
if err != nil {
log.Fatal(err)
}

log.Printf("AI Response: %s", response.Response)
}

Core Components​

Client Interface​

The Client interface provides access to all CWCloud AI services and infrastructure management:

type Client interface {
// AI Services
GeneratePrompt(req *PromptRequest) (*PromptResponse, error)
ListConversations() (*ConversationList, error)
GetConversation(id string) (*ConversationDetail, error)
DeleteConversation(id string) error
ListAdapters() (*AdapterList, error)
GetUsageStats(params map[string]string) (*UsageStats, error)

// Authentication
ValidateAuth() error

// Environment Management
ListEnvironments() (*EnvironmentList, error)
GetEnvironment(id string) (*EnvironmentDetail, error)
ListAdminEnvironments() (*EnvironmentList, error)
GetAdminEnvironment(id string) (*EnvironmentDetail, error)
CreateEnvironment(req *EnvironmentRequest) (*EnvironmentDetail, error)
UpdateEnvironment(id string, req *EnvironmentRequest) (*EnvironmentDetail, error)
DeleteEnvironment(id string) error

// Project Management
ListProjects() ([]Project, error)
GetProject(id string) (*Project, error)
ListAdminProjects() ([]Project, error)
GetAdminProject(id string) (*Project, error)

// Instance Management
ListInstances() ([]Instance, error)
GetInstance(provider, region, id string) (*Instance, error)

// Storage Management
ListBuckets() ([]Bucket, error)
GetBucket(id string) (*Bucket, error)

// Registry Management
ListRegistries() ([]Registry, error)
GetRegistry(id string) (*Registry, error)

// Function Management
ListFunctions() ([]Function, error)
GetFunction(id string) (*Function, error)

// Monitoring Management
ListMonitors() ([]Monitor, error)
GetMonitor(id string) (*Monitor, error)

// User Management (NEW!)
ListUsers() ([]User, error)
GetUser(userID string) (*User, error)
CreateUser(req *CreateUserRequest) (*User, error)

// DNS Management (NEW!)
ListDNSRecords() ([]DNSRecord, error)
GetDNSRecord(recordID string) (*DNSRecord, error)
CreateDNSRecord(req *CreateDNSRecordRequest) (*DNSRecord, error)
}

Factory Function​

func NewClient(baseURL, accessKey, secretKey, logLevel string) Client

Creates a new CWCloud API client. Use mcp.DefaultAPIURL for production.

Available AI Adapters​

Use these constants when specifying which AI model to use:

const (
AdapterGPT4o = "gpt4o"
AdapterGPT4oMini = "gpt4o-mini"
AdapterClaude3Sonnet = "claude3sonnet"
AdapterClaude3Haiku = "claude3haiku"
AdapterGemini = "gemini"
AdapterGeminiPro = "gemini-pro"
)

MCP Tool Creation​

The library provides helpers for creating MCP tools:

Simple AI Tool​

tool := mcp.NewSimpleAITool(
"summarize",
"Summarize text using AI",
client,
mcp.AdapterGPT4o,
)

Conversation Management Tool​

tool := mcp.NewConversationTool(
"list_conversations",
"List all AI conversations",
client,
)

Environment Management Tools​

// List environments tool
listEnvTool := mcp.NewListEnvironmentsTool(
"list_environments",
"List Cloud Environments",
"List all your cloud environments with various output formats",
client,
)

// Get environment tool
getEnvTool := mcp.NewGetEnvironmentTool(
"get_environment",
"Get Environment Details",
"Get detailed information about a specific environment",
client,
)

// Create environment tool
createEnvTool := mcp.NewCreateEnvironmentTool(
"create_environment",
"Create Environment",
"Create a new cloud environment",
client,
)

// Update environment tool
updateEnvTool := mcp.NewUpdateEnvironmentTool(
"update_environment",
"Update Environment",
"Update environment properties",
client,
)

// Delete environment tool
deleteEnvTool := mcp.NewDeleteEnvironmentTool(
"delete_environment",
"Delete Environment",
"Delete an environment with confirmation",
client,
)

Custom Tools​

Implement the MCPTool interface:

type MCPTool interface {
GetName() string
GetDescription() string
GetInputSchema() map[string]interface{}
Execute(ctx context.Context, params map[string]interface{}) (*MCPToolResult, error)
}

Data Types​

PromptRequest​

type PromptRequest struct {
Adapter string // AI model to use
Message string // Prompt text
Settings *PromptSettings // Optional parameters
ListID string // Conversation ID (optional)
EnableHistory bool // Save to conversation history
}

PromptSettings​

type PromptSettings struct {
MaxTokens *int // Maximum tokens to generate
Temperature *float64 // Creativity (0.0 to 1.0)
TopP *int // Nucleus sampling
Model *string // Specific model variant
}

PromptResponse​

type PromptResponse struct {
Status string // Response status
Response string // AI-generated text
ListID string // Conversation ID
Usage TokenUsage // Token usage statistics
}

Environment Management Types​

type Environment struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Status string `json:"status"`
Provider string `json:"provider"`
Region string `json:"region"`
Size string `json:"size"`
UserID string `json:"user_id"`
CreatedAt APITime `json:"created_at"`
UpdatedAt APITime `json:"updated_at"`
}

type EnvironmentRequest struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Path string `json:"path,omitempty"`
LogoURL string `json:"logo_url,omitempty"`
Type string `json:"type,omitempty"`
Provider string `json:"provider,omitempty"`
Region string `json:"region,omitempty"`
Size string `json:"size,omitempty"`
IsPrivate bool `json:"is_private,omitempty"`
Roles []string `json:"roles,omitempty"`
}

type EnvironmentList struct {
Status string `json:"status"`
Environments []Environment `json:"environments"`
Total int `json:"total"`
}

type EnvironmentDetail struct {
Status string `json:"status"`
Environment Environment `json:"environment"`
}

Authentication​

Before making API calls, validate your credentials:

if err := client.ValidateAuth(); err != nil {
log.Fatal("Authentication failed:", err)
}

Error Handling​

All methods return standard Go errors. Check for authentication failures, network issues, and API errors:

response, err := client.GeneratePrompt(req)
if err != nil {
// Handle error appropriately
log.Printf("API call failed: %v", err)
return
}

Conversation Management​

Start a Conversation​

response, err := client.GeneratePrompt(&mcp.PromptRequest{
Adapter: mcp.AdapterGPT4o,
Message: "Hello, let's chat!",
EnableHistory: true, // This creates a conversation
})
conversationID := response.ListID

Continue a Conversation​

response, err := client.GeneratePrompt(&mcp.PromptRequest{
Adapter: mcp.AdapterGPT4o,
Message: "Tell me more about that.",
ListID: conversationID, // Continue existing conversation
})

List All Conversations​

conversations, err := client.ListConversations()
if err != nil {
return err
}

for _, conv := range conversations.Conversations {
fmt.Printf("ID: %s, Title: %s\n", conv.ID, conv.Title)
}

Environment Management​

User Environment Operations (Read-Only)​

These methods provide read-only access to environment information and use user-level endpoints:

List Environments (User)​

envList, err := client.ListEnvironments()
if err != nil {
return err
}

for _, env := range envList.Environments {
fmt.Printf("ID: %d, Name: %s, Type: %s, Status: %s\n",
env.ID, env.Name, env.Type, env.Status)
}

Get Environment Details (User)​

envDetail, err := client.GetEnvironment("123")
if err != nil {
return err
}

env := envDetail.Environment
fmt.Printf("Environment: %s (%s)\n", env.Name, env.Status)
fmt.Printf("Provider: %s, Region: %s\n", env.Provider, env.Region)

Admin Environment Operations (Full CRUD)​

These methods provide full environment management capabilities and require admin authorization:

List Environments (Admin)​

// List environments with admin privileges (enhanced details)
envList, err := client.ListAdminEnvironments()
if err != nil {
return err
}

for _, env := range envList.Environments {
fmt.Printf("ID: %d, Name: %s, Type: %s, Status: %s\n",
env.ID, env.Name, env.Type, env.Status)
}

Get Environment Details (Admin)​

// Get environment details with admin metadata
envDetail, err := client.GetAdminEnvironment("123")
if err != nil {
return err
}

env := envDetail.Environment
fmt.Printf("Environment: %s (%s)\n", env.Name, env.Status)
fmt.Printf("Provider: %s, Region: %s\n", env.Provider, env.Region)

Create Environment (Admin Only)​

envReq := &mcp.EnvironmentRequest{
Name: "my-web-app",
Description: "Production web application environment",
Path: "prod-web-app",
IsPrivate: true,
Roles: []string{"admin", "developer"},
Provider: "aws",
Region: "us-east-1",
LogoURL: "https://example.com/logo.png",
}

envDetail, err := client.CreateEnvironment(envReq)
if err != nil {
return err
}

fmt.Printf("Created environment: %s (ID: %d)\n",
envDetail.Environment.Name, envDetail.Environment.ID)

Update Environment (Admin Only)​

updateReq := &mcp.EnvironmentRequest{
Name: "updated-web-app",
Description: "Updated description",
IsPrivate: false,
}

envDetail, err := client.UpdateEnvironment("123", updateReq)
if err != nil {
return err
}

fmt.Printf("Updated environment: %s\n", envDetail.Environment.Name)

Delete Environment (Admin Only)​

err := client.DeleteEnvironment("123")
if err != nil {
return err
}

fmt.Println("Environment deleted successfully")

New Types (User & DNS Management)​

User Management​

type User struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
IsActive bool `json:"is_active"`
IsAdmin bool `json:"is_admin"`
CreatedAt APITime `json:"created_at"`
UpdatedAt APITime `json:"updated_at"`
}

type CreateUserRequest struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
IsActive bool `json:"is_active"`
IsAdmin bool `json:"is_admin"`
}

// Example usage
users, err := client.ListUsers()
if err != nil {
return err
}

newUser, err := client.CreateUser(&mcp.CreateUserRequest{
Username: "john.doe",
Email: "john@example.com",
Password: "secure-password",
IsActive: true,
})

DNS Management​

type DNSRecord struct {
ID int `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL int `json:"ttl"`
Priority int `json:"priority"`
Zone string `json:"zone"`
Status string `json:"status"`
CreatedAt APITime `json:"created_at"`
UpdatedAt APITime `json:"updated_at"`
}

type CreateDNSRecordRequest struct {
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL int `json:"ttl"`
Priority int `json:"priority"`
Zone string `json:"zone"`
}

// Example usage
records, err := client.ListDNSRecords()
if err != nil {
return err
}

newRecord, err := client.CreateDNSRecord(&mcp.CreateDNSRecordRequest{
Name: "api.example.com",
Type: "A",
Content: "192.168.1.100",
Zone: "example.com",
TTL: 300,
})

MCP Tool Factory Functions​

The library provides factory functions for creating MCP-compatible tools:

// User management tools
userTool := mcp.NewListUsersTool(
"list_users",
"List Users",
"List all system users",
client,
)

createUserTool := mcp.NewCreateUserTool(
"create_user",
"Create User",
"Create a new system user",
client,
)

// DNS management tools
dnsTool := mcp.NewListDNSRecordsTool(
"list_dns_records",
"List DNS Records",
"List all DNS records",
client,
)

createDNSTool := mcp.NewCreateDNSRecordTool(
"create_dns_record",
"Create DNS Record",
"Create a new DNS record",
client,
)

Usage Statistics​

Track your AI usage and costs:

stats, err := client.GetUsageStats(nil)
if err != nil {
return err
}

fmt.Printf("Total tokens: %d\n", stats.Usage.TotalTokens)
fmt.Printf("Total cost: $%.4f\n", stats.Usage.TotalCost)

// Usage by adapter
for adapter, usage := range stats.Usage.ByAdapter {
fmt.Printf("%s: %d tokens, $%.4f\n",
adapter, usage.Tokens, usage.Cost)
}

Examples​

See the examples/ directory for complete working examples:

  • examples/usage.go - Comprehensive usage examples
  • Basic client operations
  • Custom MCP tool creation
  • Conversation management
  • Usage statistics
  • User and DNS management

Thread Safety​

The client is safe for concurrent use across multiple goroutines.

Best Practices​

  1. Reuse Clients: Create one client instance and reuse it across your application
  2. Handle Errors: Always check for errors, especially authentication failures
  3. Set Limits: Use MaxTokens to control costs and response length
  4. Save Conversations: Use EnableHistory: true for multi-turn conversations
  5. Monitor Usage: Regularly check usage statistics to track costs
  6. Secure Credentials: Store API keys securely and never commit them to version control
  7. Use Admin Tools Carefully: Admin tools have elevated privileges - use with caution

Complete Feature Set (119 Tools)​

The CWCloud MCP library now provides 119 comprehensive tools across 10 categories:

  • AI Services (3 tools): AI generation, conversations, adapters
  • Environment Management (11 tools): Full CRUD + admin operations
  • Project Management (7 tools): Complete project lifecycle
  • Instance Management (10 tools): VM operations with admin controls
  • Storage Management (10 tools): Bucket operations with admin controls
  • Registry Management (10 tools): Container registry operations
  • Function Management (12 tools): Serverless with invocation
  • Monitoring Management (10 tools): Endpoint monitoring
  • User Management (10 tools): Complete user lifecycle
  • DNS Management (10 tools): DNS record management

Integration with MCP Servers​

This library is designed to be used within MCP servers. The tools created with this library can be easily integrated into MCP protocol implementations.

For a complete example of an MCP server using this library, see the main cwcloud-mcp server implementation in the project root.