File size: 10,634 Bytes
924e633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python
"""
Standalone FastAPI MCP server for Hyper-V management.
Server will be available at http://localhost:8000
"""
import asyncio
import json
import logging
import subprocess
import sys
import platform
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, asdict
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import uvicorn

# Ensure SelectorEventLoopPolicy on Windows
if platform.system() == "Windows":
    try:
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    except AttributeError:
        pass

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("hyperv_mcp_server")

# Pydantic models for API
class ToolCallRequest(BaseModel):
    name: str
    arguments: Dict[str, Any] = {}

class ToolInfo(BaseModel):
    name: str
    description: str
    inputSchema: Dict[str, Any]

class ToolsListResponse(BaseModel):
    tools: List[ToolInfo]

class ToolCallResponse(BaseModel):
    success: bool
    result: Any = None
    error: str = None

@dataclass
class VirtualMachine:
    name: str
    state: str
    status: str

class HyperVManager:
    def __init__(self, host: str = "localhost", username: Optional[str] = None, password: Optional[str] = None):
        self.host = host
        self.username = username
        self.password = password

    def _run_powershell(self, command: str) -> str:
        """Execute PowerShell command and return output"""
        try:
            if self.host == "localhost":
                proc = subprocess.run(
                    ["powershell", "-Command", command],
                    capture_output=True, text=True, shell=True, timeout=30
                )
                if proc.returncode != 0:
                    raise RuntimeError(f"PowerShell error: {proc.stderr}")
                return proc.stdout.strip()
            else:
                raise NotImplementedError("Remote host not supported in this server")
        except subprocess.TimeoutExpired:
            raise RuntimeError("PowerShell command timed out")
        except Exception as e:
            logger.error(f"PowerShell execution error: {e}")
            raise

    async def list_vms(self) -> List[Dict[str, Any]]:
        """List all virtual machines"""
        try:
            cmd = (
                "Get-VM | Select-Object Name,State,Status | "
                "ConvertTo-Json -Depth 2"
            )
            output = await asyncio.get_event_loop().run_in_executor(
                None, self._run_powershell, cmd
            )
            
            if not output:
                return []
                
            data = json.loads(output)
            if isinstance(data, dict):
                data = [data]
            
            vms = []
            for item in data:
                vm = VirtualMachine(
                    name=item.get('Name', ''),
                    state=item.get('State', ''),
                    status=item.get('Status', ''),
                )
                vms.append(asdict(vm))
            
            return vms
        except Exception as e:
            logger.error(f"Failed to list VMs: {e}")
            raise

    async def get_vm_status(self, vm_name: str) -> Dict[str, Any]:
        """Get status of a specific virtual machine"""
        try:
            cmd = (
                f"$vm = Get-VM -Name '{vm_name}' -ErrorAction Stop; "
                "$vm | Select-Object Name,State,Status | "
                "ConvertTo-Json -Depth 2"
            )
            output = await asyncio.get_event_loop().run_in_executor(
                None, self._run_powershell, cmd
            )
            
            if not output:
                return {}
                
            return json.loads(output)
        except Exception as e:
            logger.error(f"Failed to get VM status for {vm_name}: {e}")
            raise

    async def start_vm(self, vm_name: str) -> Dict[str, Any]:
        """Start a virtual machine"""
        try:
            cmd = f"Start-VM -Name '{vm_name}' -ErrorAction Stop"
            await asyncio.get_event_loop().run_in_executor(
                None, self._run_powershell, cmd
            )
            return {"success": True, "message": f"VM '{vm_name}' started successfully"}
        except Exception as e:
            logger.error(f"Failed to start VM {vm_name}: {e}")
            raise

    async def stop_vm(self, vm_name: str, force: bool = False) -> Dict[str, Any]:
        """Stop a virtual machine"""
        try:
            force_flag = "-Force" if force else ""
            cmd = f"Stop-VM -Name '{vm_name}' {force_flag} -ErrorAction Stop"
            await asyncio.get_event_loop().run_in_executor(
                None, self._run_powershell, cmd
            )
            return {"success": True, "message": f"VM '{vm_name}' stopped successfully"}
        except Exception as e:
            logger.error(f"Failed to stop VM {vm_name}: {e}")
            raise

    async def restart_vm(self, vm_name: str, force: bool = False) -> Dict[str, Any]:
        """Restart a virtual machine"""
        try:
            force_flag = "-Force" if force else ""
            cmd = f"Restart-VM -Name '{vm_name}' {force_flag} -ErrorAction Stop"
            await asyncio.get_event_loop().run_in_executor(
                None, self._run_powershell, cmd
            )
            return {"success": True, "message": f"VM '{vm_name}' restarted successfully"}
        except Exception as e:
            logger.error(f"Failed to restart VM {vm_name}: {e}")
            raise


# Initialize FastAPI app and Hyper-V manager
app = FastAPI(title="Hyper-V MCP Server", version="1.0.0")
hyperv_manager = HyperVManager()

# Tool definitions
TOOLS = {
    "list_vms": {
        "name": "list_vms",
        "description": "List all virtual machines on the Hyper-V host",
        "inputSchema": {
            "type": "object",
            "properties": {},
            "required": []
        }
    },
    "get_vm_status": {
        "name": "get_vm_status",
        "description": "Get detailed status information for a specific virtual machine",
        "inputSchema": {
            "type": "object",
            "properties": {
                "vm_name": {"type": "string", "description": "Name of the virtual machine"}
            },
            "required": ["vm_name"]
        }
    },
    "start_vm": {
        "name": "start_vm",
        "description": "Start a virtual machine",
        "inputSchema": {
            "type": "object",
            "properties": {
                "vm_name": {"type": "string", "description": "Name of the virtual machine to start"}
            },
            "required": ["vm_name"]
        }
    },
    "stop_vm": {
        "name": "stop_vm",
        "description": "Stop a virtual machine",
        "inputSchema": {
            "type": "object",
            "properties": {
                "vm_name": {"type": "string", "description": "Name of the virtual machine to stop"},
                "force": {"type": "boolean", "description": "Force stop the VM", "default": False}
            },
            "required": ["vm_name"]
        }
    },
    "restart_vm": {
        "name": "restart_vm",
        "description": "Restart a virtual machine",
        "inputSchema": {
            "type": "object",
            "properties": {
                "vm_name": {"type": "string", "description": "Name of the virtual machine to restart"},
                "force": {"type": "boolean", "description": "Force restart the VM", "default": False}
            },
            "required": ["vm_name"]
        }
    },
}

# API Endpoints
@app.get("/")
async def root():
    """Health check endpoint"""
    return {"status": "Hyper-V MCP Server is running", "version": "1.0.0"}

@app.get("/tools", response_model=ToolsListResponse)
async def list_tools():
    """List all available tools"""
    tools = [ToolInfo(**tool_info) for tool_info in TOOLS.values()]
    return ToolsListResponse(tools=tools)

@app.post("/tools/call", response_model=ToolCallResponse)
async def call_tool(request: ToolCallRequest):
    """Execute a tool with given arguments"""
    try:
        tool_name = request.name
        arguments = request.arguments
        
        if tool_name not in TOOLS:
            raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found")
        
        # Get the corresponding method from HyperVManager
        if not hasattr(hyperv_manager, tool_name):
            raise HTTPException(status_code=500, detail=f"Method '{tool_name}' not implemented")
        
        method = getattr(hyperv_manager, tool_name)
        
        # Call the method with arguments
        if arguments:
            result = await method(**arguments)
        else:
            result = await method()
        
        return ToolCallResponse(success=True, result=result)
        
    except Exception as e:
        logger.error(f"Tool execution error: {e}")
        return ToolCallResponse(success=False, error=str(e))

# Additional convenience endpoints
@app.get("/vms")
async def get_vms():
    """Convenience endpoint to list VMs"""
    try:
        result = await hyperv_manager.list_vms()
        return {"success": True, "vms": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/vms/{vm_name}")
async def get_vm(vm_name: str):
    """Convenience endpoint to get VM status"""
    try:
        result = await hyperv_manager.get_vm_status(vm_name)
        return {"success": True, "vm": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/vms/{vm_name}/start")
async def start_vm_endpoint(vm_name: str):
    """Convenience endpoint to start a VM"""
    try:
        result = await hyperv_manager.start_vm(vm_name)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/vms/{vm_name}/stop")
async def stop_vm_endpoint(vm_name: str, force: bool = False):
    """Convenience endpoint to stop a VM"""
    try:
        result = await hyperv_manager.stop_vm(vm_name, force)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    print("Starting Hyper-V MCP Server...")
    print("Server will be available at: http://localhost:8000")
    print("API documentation at: http://localhost:8000/docs")
    
    uvicorn.run(
        app, 
        host="0.0.0.0", 
        port=8000,
        log_level="info"
    )