|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + ha "github.com/mkelcik/go-ha-client" |
| 13 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 14 | +) |
| 15 | + |
| 16 | +// Global Home Assistant client |
| 17 | +var client *ha.Client |
| 18 | + |
| 19 | +// Input types |
| 20 | +type ListEntitiesInput struct { |
| 21 | +} |
| 22 | + |
| 23 | +type GetServicesInput struct { |
| 24 | +} |
| 25 | + |
| 26 | +type CallServiceInput struct { |
| 27 | + Domain string `json:"domain" jsonschema:"the domain of the service (e.g., 'switch', 'light')"` |
| 28 | + Service string `json:"service" jsonschema:"the service name (e.g., 'turn_on', 'turn_off')"` |
| 29 | + EntityID string `json:"entity_id" jsonschema:"the entity ID (e.g., 'switch.switch_1')"` |
| 30 | +} |
| 31 | + |
| 32 | +// Output types |
| 33 | +type Entity struct { |
| 34 | + EntityID string `json:"entity_id" jsonschema:"the entity ID"` |
| 35 | + State string `json:"state" jsonschema:"current state"` |
| 36 | + FriendlyName interface{} `json:"friendly_name" jsonschema:"friendly name if available"` |
| 37 | + Domain string `json:"domain" jsonschema:"domain of the entity"` |
| 38 | +} |
| 39 | + |
| 40 | +type ListEntitiesOutput struct { |
| 41 | + Entities []Entity `json:"entities" jsonschema:"list of all entities"` |
| 42 | + Count int `json:"count" jsonschema:"number of entities"` |
| 43 | +} |
| 44 | + |
| 45 | +type ServiceField struct { |
| 46 | + Description string `json:"description" jsonschema:"field description"` |
| 47 | + Example string `json:"example,omitempty" jsonschema:"example value"` |
| 48 | + Required bool `json:"required,omitempty" jsonschema:"whether the field is required"` |
| 49 | +} |
| 50 | + |
| 51 | +type Service struct { |
| 52 | + Domain string `json:"domain" jsonschema:"service domain"` |
| 53 | + Name string `json:"name" jsonschema:"service name"` |
| 54 | + Fields map[string]ServiceField `json:"fields" jsonschema:"service fields"` |
| 55 | +} |
| 56 | + |
| 57 | +type GetServicesOutput struct { |
| 58 | + Services []Service `json:"services" jsonschema:"list of all available services"` |
| 59 | + Count int `json:"count" jsonschema:"number of services"` |
| 60 | +} |
| 61 | + |
| 62 | +type CallServiceOutput struct { |
| 63 | + Success bool `json:"success" jsonschema:"whether the call was successful"` |
| 64 | + Message string `json:"message" jsonschema:"status message"` |
| 65 | +} |
| 66 | + |
| 67 | +// ListEntities returns all entities in Home Assistant |
| 68 | +func ListEntities(ctx context.Context, req *mcp.CallToolRequest, input ListEntitiesInput) ( |
| 69 | + *mcp.CallToolResult, |
| 70 | + ListEntitiesOutput, |
| 71 | + error, |
| 72 | +) { |
| 73 | + states, err := client.GetStates(ctx) |
| 74 | + if err != nil { |
| 75 | + return nil, ListEntitiesOutput{}, fmt.Errorf("failed to get states: %w", err) |
| 76 | + } |
| 77 | + |
| 78 | + var entities []Entity |
| 79 | + for _, state := range states { |
| 80 | + // Extract domain from entity ID |
| 81 | + data := strings.Split(state.EntityId, ".") |
| 82 | + domain := "" |
| 83 | + if len(data) > 0 { |
| 84 | + domain = data[0] |
| 85 | + } |
| 86 | + |
| 87 | + // Extract friendly name if available |
| 88 | + friendlyName := state.Attributes["friendly_name"] |
| 89 | + |
| 90 | + entity := Entity{ |
| 91 | + EntityID: state.EntityId, |
| 92 | + State: state.State, |
| 93 | + FriendlyName: friendlyName, |
| 94 | + Domain: domain, |
| 95 | + } |
| 96 | + entities = append(entities, entity) |
| 97 | + } |
| 98 | + |
| 99 | + output := ListEntitiesOutput{ |
| 100 | + Entities: entities, |
| 101 | + Count: len(entities), |
| 102 | + } |
| 103 | + |
| 104 | + return nil, output, nil |
| 105 | +} |
| 106 | + |
| 107 | +// GetServices returns all available services in Home Assistant |
| 108 | +func GetServices(ctx context.Context, req *mcp.CallToolRequest, input GetServicesInput) ( |
| 109 | + *mcp.CallToolResult, |
| 110 | + GetServicesOutput, |
| 111 | + error, |
| 112 | +) { |
| 113 | + services, err := client.GetServices(ctx) |
| 114 | + if err != nil { |
| 115 | + return nil, GetServicesOutput{}, fmt.Errorf("failed to get services: %w", err) |
| 116 | + } |
| 117 | + |
| 118 | + var result []Service |
| 119 | + for _, s := range services { |
| 120 | + for serviceName, serviceInfo := range s.Services { |
| 121 | + // Convert service fields to our format |
| 122 | + fields := make(map[string]ServiceField) |
| 123 | + for fieldName, fieldInfo := range serviceInfo.Fields { |
| 124 | + field := ServiceField{ |
| 125 | + Description: fieldInfo.Description, |
| 126 | + } |
| 127 | + |
| 128 | + // Set example if available (convert to string if needed) |
| 129 | + if fieldInfo.Example != nil { |
| 130 | + switch v := fieldInfo.Example.(type) { |
| 131 | + case string: |
| 132 | + field.Example = v |
| 133 | + default: |
| 134 | + field.Example = fmt.Sprintf("%v", v) |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + // Set required flag if available |
| 139 | + if fieldInfo.Selector != nil { |
| 140 | + field.Required = true // Set based on selector if needed |
| 141 | + } |
| 142 | + |
| 143 | + fields[fieldName] = field |
| 144 | + } |
| 145 | + |
| 146 | + service := Service{ |
| 147 | + Domain: s.Domain, |
| 148 | + Name: serviceName, |
| 149 | + Fields: fields, |
| 150 | + } |
| 151 | + result = append(result, service) |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + output := GetServicesOutput{ |
| 156 | + Services: result, |
| 157 | + Count: len(result), |
| 158 | + } |
| 159 | + |
| 160 | + return nil, output, nil |
| 161 | +} |
| 162 | + |
| 163 | +// CallService calls a service in Home Assistant |
| 164 | +func CallService(ctx context.Context, req *mcp.CallToolRequest, input CallServiceInput) ( |
| 165 | + *mcp.CallToolResult, |
| 166 | + CallServiceOutput, |
| 167 | + error, |
| 168 | +) { |
| 169 | + // Prepare the service command |
| 170 | + cmd := ha.DefaultServiceCmd{ |
| 171 | + Domain: input.Domain, |
| 172 | + Service: input.Service, |
| 173 | + EntityId: input.EntityID, |
| 174 | + } |
| 175 | + |
| 176 | + // Call the service |
| 177 | + _, err := client.CallService(ctx, cmd) |
| 178 | + if err != nil { |
| 179 | + return nil, CallServiceOutput{ |
| 180 | + Success: false, |
| 181 | + Message: fmt.Sprintf("Failed to call service: %v", err), |
| 182 | + }, nil |
| 183 | + } |
| 184 | + |
| 185 | + output := CallServiceOutput{ |
| 186 | + Success: true, |
| 187 | + Message: fmt.Sprintf("Successfully called %s.%s on entity %s", input.Domain, input.Service, input.EntityID), |
| 188 | + } |
| 189 | + |
| 190 | + return nil, output, nil |
| 191 | +} |
| 192 | + |
| 193 | +func main() { |
| 194 | + // Get configuration from environment variables |
| 195 | + token := os.Getenv("HA_TOKEN") |
| 196 | + if token == "" { |
| 197 | + log.Fatal("HA_TOKEN environment variable is required") |
| 198 | + } |
| 199 | + |
| 200 | + host := os.Getenv("HA_HOST") |
| 201 | + if host == "" { |
| 202 | + host = "http://localhost:8123" |
| 203 | + } |
| 204 | + |
| 205 | + // Create Home Assistant client |
| 206 | + client = ha.NewClient( |
| 207 | + ha.ClientConfig{ |
| 208 | + Token: token, |
| 209 | + Host: host, |
| 210 | + }, |
| 211 | + &http.Client{ |
| 212 | + Timeout: 30 * time.Second, |
| 213 | + }, |
| 214 | + ) |
| 215 | + |
| 216 | + // Test connection |
| 217 | + if err := client.Ping(context.Background()); err != nil { |
| 218 | + log.Printf("Warning: Could not ping Home Assistant instance: %v", err) |
| 219 | + } else { |
| 220 | + log.Println("Connected to Home Assistant instance") |
| 221 | + } |
| 222 | + |
| 223 | + // Create MCP server with Home Assistant tools |
| 224 | + server := mcp.NewServer(&mcp.Implementation{Name: "homeassistant", Version: "v1.0.0"}, nil) |
| 225 | + |
| 226 | + // Register tools |
| 227 | + mcp.AddTool(server, &mcp.Tool{ |
| 228 | + Name: "list_entities", |
| 229 | + Description: "List all entities in Home Assistant and their current states", |
| 230 | + }, ListEntities) |
| 231 | + |
| 232 | + mcp.AddTool(server, &mcp.Tool{ |
| 233 | + Name: "get_services", |
| 234 | + Description: "Get all available services in Home Assistant", |
| 235 | + }, GetServices) |
| 236 | + |
| 237 | + mcp.AddTool(server, &mcp.Tool{ |
| 238 | + Name: "call_service", |
| 239 | + Description: "Call a service in Home Assistant (e.g., turn_on, turn_off, toggle)", |
| 240 | + }, CallService) |
| 241 | + |
| 242 | + // Run the server |
| 243 | + if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil { |
| 244 | + log.Fatal(err) |
| 245 | + } |
| 246 | +} |
0 commit comments