#!/usr/bin/env python3
"""Minimal MCP server exposing vault file operations."""
import json
import os
from http.server import HTTPServer, BaseHTTPRequestHandler

VAULT_ROOT = "/root/.hermes/vault"

class MCPHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass
    
    def do_POST(self):
        if self.path != '/mcp':
            self.send_error(404)
            return
        
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length).decode()
        
        try:
            req = json.loads(body)
        except:
            self.send_error(400, 'Invalid JSON')
            return
        
        method = req.get('method', '')
        req_id = req.get('id', 0)
        
        # Build response
        if method == 'initialize':
            result = {
                'jsonrpc': '2.0',
                'id': req_id,
                'result': {
                    'protocolVersion': '2024-11-05',
                    'capabilities': {'tools': {}},
                    'serverInfo': {'name': 'hermes-vault', 'version': '1.0.0'}
                }
            }
        elif method == 'tools/list':
            result = {
                'jsonrpc': '2.0',
                'id': req_id,
                'result': {
                    'tools': [
                        {'name': 'list_files', 'description': 'List files in vault directory', 'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string'}}, 'required': ['path']}},
                        {'name': 'read_file', 'description': 'Read file from vault', 'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string'}}, 'required': ['path']}},
                        {'name': 'write_file', 'description': 'Write file to vault', 'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string'}, 'content': {'type': 'string'}}, 'required': ['path', 'content']}}
                    ]
                }
            }
        elif method == 'tools/call':
            tool = req.get('params', {}).get('name', '')
            args = req.get('params', {}).get('arguments', {})
            
            if tool == 'list_files':
                path = os.path.join(VAULT_ROOT, args.get('path', '').lstrip('/'))
                try:
                    files = os.listdir(path)
                    text = json.dumps({'files': files})
                except Exception as e:
                    text = json.dumps({'error': str(e)})
                result = {'jsonrpc': '2.0', 'id': req_id, 'result': {'content': [{'type': 'text', 'text': text}]}}
            
            elif tool == 'read_file':
                path = os.path.join(VAULT_ROOT, args.get('path', '').lstrip('/'))
                try:
                    with open(path, 'r') as f:
                        content = f.read()
                    text = json.dumps({'content': content})
                except Exception as e:
                    text = json.dumps({'error': str(e)})
                result = {'jsonrpc': '2.0', 'id': req_id, 'result': {'content': [{'type': 'text', 'text': text}]}}
            
            elif tool == 'write_file':
                path = os.path.join(VAULT_ROOT, args.get('path', '').lstrip('/'))
                content = args.get('content', '')
                try:
                    os.makedirs(os.path.dirname(path), exist_ok=True)
                    with open(path, 'w') as f:
                        f.write(content)
                    text = json.dumps({'written': path})
                except Exception as e:
                    text = json.dumps({'error': str(e)})
                result = {'jsonrpc': '2.0', 'id': req_id, 'result': {'content': [{'type': 'text', 'text': text}]}}
            
            else:
                result = {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': -32601, 'message': 'Unknown tool'}}
        else:
            result = {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': -32601, 'message': 'Method not found'}}
        
        # Send as SSE
        response = f"data: {json.dumps(result)}\n\n".encode()
        self.send_response(200)
        self.send_header('Content-Type', 'text/event-stream')
        self.send_header('Cache-Control', 'no-cache')
        self.send_header('Content-Length', str(len(response)))
        self.end_headers()
        self.wfile.write(response)
        self.wfile.flush()
        self.close_connection = True

if __name__ == '__main__':
    server = HTTPServer(('127.0.0.1', 9123), MCPHandler)
    print('Vault MCP server on 127.0.0.1:9123')
    server.serve_forever()
