欧美成人精品手机在线观看_69视频国产_动漫精品第一页_日韩中文字幕网 - 日本欧美一区二区

LOGO OA教程 ERP教程 模切知識(shí)交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

使用C#創(chuàng)建一個(gè)MCP客戶端

freeflydom
2025年3月17日 9:38 本文熱度 424

前言

網(wǎng)上使用Python創(chuàng)建一個(gè)MCP客戶端的教程已經(jīng)有很多了,而使用C#創(chuàng)建一個(gè)MCP客戶端的教程還很少。

為什么要?jiǎng)?chuàng)建一個(gè)MCP客戶端呢?

創(chuàng)建了一個(gè)MCP客戶端之后,你就可以使用別人寫好的一些MCP服務(wù)了。

效果展示

為了方便大家復(fù)現(xiàn),我沒有使用WPF/Avalonia之類的做界面。只是一個(gè)簡單的控制臺(tái)程序,可以很容易看懂。

接入了fetch_mcp可以實(shí)現(xiàn)獲取網(wǎng)頁內(nèi)容了,使用的模型只要具有tool use能力的應(yīng)該都可以。

我使用的是Qwen/Qwen2.5-72B-Instruct。

開始實(shí)踐

主要使用的包如下所示:

首先獲取MCP服務(wù)器:

 private static async Task<IMcpClient> GetMcpClientAsync()
 {
     DotEnv.Load();
     var envVars = DotEnv.Read();
     McpClientOptions options = new()
     {
         ClientInfo = new() { Name = "SimpleToolsConsole", Version = "1.0.0" }
     };
     var config = new McpServerConfig
     {
         Id = "test",
         Name = "Test",
         TransportType = TransportTypes.StdIo,
         TransportOptions = new Dictionary<string, string>
         {
             ["command"] = envVars["MCPCommand"],
             ["arguments"] = envVars["MCPArguments"],
         }
     };
     var factory = new McpClientFactory(
         new[] { config },
         options,
         NullLoggerFactory.Instance
     );
     return await factory.GetClientAsync("test");
 }

寫死的話就是這樣寫:

 private static async Task<IMcpClient> GetMcpClientAsync()
 {
     DotEnv.Load();
     var envVars = DotEnv.Read();
     McpClientOptions options = new()
     {
         ClientInfo = new() { Name = "SimpleToolsConsole", Version = "1.0.0" }
     };
     var config = new McpServerConfig
     {
         Id = "test",
         Name = "Test",
         TransportType = TransportTypes.StdIo,
         TransportOptions = new Dictionary<string, string>
         {
             ["command"] = node,
             ["arguments"] = D:/Learning/AI-related/fetch-mcp/dist/index.js,
         }
     };
     var factory = new McpClientFactory(
         new[] { config },
         options,
         NullLoggerFactory.Instance
     );
     return await factory.GetClientAsync("test");
 }

重點(diǎn)在:

 TransportOptions = new Dictionary<string, string>
         {
             ["command"] = node,
             ["arguments"] = D:/Learning/AI-related/fetch-mcp/dist/index.js,
         }

用于連接你想連接的MCP服務(wù)器。

如果能正確顯示你連接mcp服務(wù)器提供的工具,說明連接成功。

  var listToolsResult = await client.ListToolsAsync();
  var mappedTools = listToolsResult.Tools.Select(t => t.ToAITool(client)).ToList();
  Console.WriteLine("Tools available:");
  foreach (var tool in mappedTools)
  {
      Console.WriteLine("  " + tool);
  }

開啟一個(gè)聊天循環(huán):

    Console.WriteLine("\nMCP Client Started!");
    Console.WriteLine("Type your queries or 'quit' to exit.");
    ChatDemo chatDemo = new ChatDemo();
    while (true)
    {
        try
        {
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.Write("\nQuery: ");
            string query = Console.ReadLine()?.Trim() ?? string.Empty;
            if (query.ToLower() == "quit")
                break;
            if (query.ToLower() == "clear")
            {
                Console.Clear();
                chatDemo.Messages.Clear();                    
            }
            else 
            {
                string response = await chatDemo.ProcessQueryAsync(query, mappedTools);
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine($"AI回答:{response}");
                Console.ForegroundColor = ConsoleColor.White;
            }                      
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\nError: {ex.Message}");
        }
    }
}

處理每次詢問:

 public async Task<string> ProcessQueryAsync(string query, List<AITool> tools)
 {
     if(Messages.Count == 0)
     {
         Messages =
         [
          // Add a system message
         new(ChatRole.System, "You are a helpful assistant, helping us test MCP server functionality."),
         ];
     }
     
     // Add a user message
     Messages.Add(new(ChatRole.User, query));
     var response = await ChatClient.GetResponseAsync(
            Messages,
            new() { Tools = tools });
     Messages.AddMessages(response);
     var toolUseMessage = response.Messages.Where(m => m.Role == ChatRole.Tool);
     if (toolUseMessage.Count() > 0)
     {
         var functionMessage = response.Messages.Where(m => m.Text == "").First();             
         var functionCall = (FunctionCallContent)functionMessage.Contents[1];
         Console.ForegroundColor = ConsoleColor.Green;
         string arguments = "";
         foreach (var arg in functionCall.Arguments)
         {
             arguments += $"{arg.Key}:{arg.Value};";
         }
         Console.WriteLine($"調(diào)用函數(shù)名:{functionCall.Name};參數(shù)信息:{arguments}");
         foreach (var message in toolUseMessage)
         {
             var functionResultContent = (FunctionResultContent)message.Contents[0];
             Console.WriteLine($"調(diào)用工具結(jié)果:{functionResultContent.Result}");
         }
         Console.ForegroundColor = ConsoleColor.White;
     }
     else
     {
         Console.ForegroundColor = ConsoleColor.Green;
         Console.WriteLine("本次沒有調(diào)用工具");
         Console.ForegroundColor = ConsoleColor.White;
     }
     return response.Text;
 }

代碼已經(jīng)放到GitHub,地址:https://github.com/Ming-jiayou/mcp_demo

將.env-example修改為.env應(yīng)該就可以運(yùn)行,如果報(bào)錯(cuò),設(shè)置成嵌入的資源即可。

.env配置示例:

API_KEY=sk-xxx
BaseURL=https://api.siliconflow.cn/v1
ModelID=Qwen/Qwen2.5-72B-Instruct
MCPCommand=node
MCPArguments=D:/Learning/AI-related/fetch-mcp/dist/index.js

?轉(zhuǎn)自https://www.cnblogs.com/mingupupu/p/18772576


該文章在 2025/3/17 9:38:15 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對(duì)中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對(duì)港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場(chǎng)、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場(chǎng)作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲(chǔ)管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲(chǔ)管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號(hào)管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved