#!/usr/bin/env python3
"""A small MCP workspace server over the pricing project, for the governed-call tutorial."""
import json
import sys
from pathlib import Path

WORKSPACE = Path(__file__).resolve().with_name('workspace')
TOOLS = [
    {'name': 'read_file', 'description': 'Read a file in the pricing project.',
     'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string'}},
                     'required': ['path'], 'additionalProperties': False}},
    {'name': 'write_file', 'description': 'Replace a file in the pricing project.',
     'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string'}, 'text': {'type': 'string'}},
                     'required': ['path', 'text'], 'additionalProperties': False}},
]


def resolve(relative):
    path = (WORKSPACE / relative).resolve()
    if WORKSPACE not in path.parents:
        raise ValueError('Path outside the workspace')
    return path

for line in sys.stdin:
    request = json.loads(line)
    if 'id' not in request:
        continue
    method = request.get('method')
    if method == 'initialize':
        result = {'protocolVersion': request['params']['protocolVersion'],
                  'capabilities': {'tools': {}},
                  'serverInfo': {'name': 'larkfield-workspace', 'version': '1.0.0'}}
    elif method == 'tools/list':
        result = {'tools': TOOLS}
    elif method == 'tools/call':
        params = request['params']
        arguments = params['arguments']
        if params['name'] == 'read_file':
            text = resolve(arguments['path']).read_text()
        elif params['name'] == 'write_file':
            text = arguments['text']
            resolve(arguments['path']).write_text(text)
        else:
            raise ValueError('Unknown tool')
        result = {'content': [{'type': 'text', 'text': text}]}
    elif method == 'ping':
        result = {}
    else:
        print(json.dumps({'jsonrpc': '2.0', 'id': request['id'],
                          'error': {'code': -32601, 'message': 'Method not found'}}), flush=True)
        continue
    print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], 'result': result}), flush=True)
