import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { spawn } from 'child_process';

class MCPFileSystemClient {
  constructor() {
    this.client = new Client(
      { name: 'filesystem-client', version: '1.0.0' },
      { capabilities: {} }
    );
  }

  async connect() {
    // Start the MCP server process
    const serverProcess = spawn('node', ['filesystem-server.js'], {
      stdio: ['pipe', 'pipe', 'inherit']
    });

    const transport = new StdioClientTransport({
      stdin: serverProcess.stdin,
      stdout: serverProcess.stdout
    });

    await this.client.connect(transport);
  }

  async listAvailableTools() {
    const response = await this.client.request(
      { method: 'tools/list' },
      {}
    );
    return response.tools;
  }

  async readFile(path) {
    const response = await this.client.request(
      { method: 'tools/call' },
      {
        name: 'read_file',
        arguments: { path }
      }
    );
    return response;
  }

  async writeFile(path, content) {
    const response = await this.client.request(
      { method: 'tools/call' },
      {
        name: 'write_file',
        arguments: { path, content }
      }
    );
    return response;
  }
}

// Usage example
async function demonstrateFileSystemMCP() {
  const client = new MCPFileSystemClient();
  await client.connect();
  const tools = await client.listAvailableTools();
  console.log('Available tools:', tools);
  await client.writeFile('./test.txt', 'Hello from MCP!');
  const content = await client.readFile('./test.txt');
  console.log('File content:', content);
}

demonstrateFileSystemMCP().catch(console.error);