C# 文件操作--filesystem MCP 服务器

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("🚀 连接 MCP 服务 - Filesystem (Tools 版)\n");

        var testDir = "C:\\temp";

        // 确保测试文件存在
        var testFile = Path.Combine(testDir, "test.txt");
        if (!File.Exists(testFile))
        {
            Directory.CreateDirectory(testDir);
            File.WriteAllText(testFile, "Hello MCP from C#!");
            Console.WriteLine($"📁 创建测试文件:{testFile}\n");
        }

        // 启动 MCP 服务
        var serverProcess = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = @"C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Microsoft\VisualStudio\NodeJs\npx.cmd",
                Arguments = $"-y @modelcontextprotocol/server-filesystem {testDir}",
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            }
        };

        serverProcess.Start();
        var stdin = serverProcess.StandardInput;
        var stdout = serverProcess.StandardOutput;

        // 1. 初始化
        Console.WriteLine("📤 [1] 初始化");
        var initRequest = new
        {
            jsonrpc = "2.0",
            id = "1",
            method = "initialize",
            @params = new
            {
                protocolVersion = "2024-11-05",
                capabilities = new { },
                clientInfo = new
                {
                    name = "MyCSharpClient",
                    version = "1.0.0"
                }
            }
        };
        await stdin.WriteLineAsync(JsonSerializer.Serialize(initRequest));
        await stdin.FlushAsync();
        var init = await stdout.ReadLineAsync();
        Console.WriteLine($"📥 {FormatJson(init)}\n");

        // 2. 列出可用工具
        Console.WriteLine("📤 [2] 列出工具 (tools/list)");
        var toolsRequest = new
        {
            jsonrpc = "2.0",
            id = "2",
            method = "tools/list",
            @params = new { }
        };
        await stdin.WriteLineAsync(JsonSerializer.Serialize(toolsRequest));
        await stdin.FlushAsync();
        var tools = await stdout.ReadLineAsync();
        Console.WriteLine($"📥 {FormatJson(tools)}\n");

        // 3. 读取文件(用工具调用)
        Console.WriteLine("📤 [3] 读取文件 (tools/call - read_file)");
        var readRequest = new
        {
            jsonrpc = "2.0",
            id = "3",
            method = "tools/call",
            @params = new
            {
                name = "read_file",
                arguments = new
                {
                    path = $"{testDir}\\test.txt"
                }
            }
        };
        await stdin.WriteLineAsync(JsonSerializer.Serialize(readRequest));
        await stdin.FlushAsync();
        var read = await stdout.ReadLineAsync();
        Console.WriteLine($"📥 {FormatJson(read)}\n");

        // 4. 列出目录(用工具调用)
        Console.WriteLine("📤 [4] 列出目录 (tools/call - list_directory)");
        var dirRequest = new
        {
            jsonrpc = "2.0",
            id = "4",
            method = "tools/call",
            @params = new
            {
                name = "list_directory",
                arguments = new
                {
                    path = testDir
                }
            }
        };
        await stdin.WriteLineAsync(JsonSerializer.Serialize(dirRequest));
        await stdin.FlushAsync();
        var dir = await stdout.ReadLineAsync();
        Console.WriteLine($"📥 {FormatJson(dir)}\n");

        serverProcess.Kill();
        Console.WriteLine("✅ 测试完成!");
    }

    static string FormatJson(string? json)
    {
        if (string.IsNullOrEmpty(json)) return "(空)";
        try
        {
            var doc = JsonDocument.Parse(json);
            return JsonSerializer.Serialize(doc, new JsonSerializerOptions { WriteIndented = true });
        }
        catch { return json; }
    }
}

 

posted @ 2026-06-16 16:48  天才卧龙  阅读(6)  评论(0)    收藏  举报