前言
網上使用Python創建一個MCP客戶端的教程已經有很多了,而使用C#創建一個MCP客戶端的教程還很少。
為什么要創建一個MCP客戶端呢?
創建了一個MCP客戶端之后,你就可以使用別人寫好的一些MCP服務了。
效果展示
為了方便大家復現,我沒有使用WPF/Avalonia之類的做界面。只是一個簡單的控制臺程序,可以很容易看懂。

接入了fetch_mcp可以實現獲取網頁內容了,使用的模型只要具有tool use能力的應該都可以。
我使用的是Qwen/Qwen2.5-72B-Instruct。
開始實踐
主要使用的包如下所示:

首先獲取MCP服務器:
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");
}
重點在:
TransportOptions = new Dictionary<string, string>
{
["command"] = node,
["arguments"] = D:/Learning/AI-related/fetch-mcp/dist/index.js,
}
用于連接你想連接的MCP服務器。
如果能正確顯示你連接mcp服務器提供的工具,說明連接成功。
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);
}

開啟一個聊天循環:
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 =
[
new(ChatRole.System, "You are a helpful assistant, helping us test MCP server functionality."),
];
}
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($"調用函數名:{functionCall.Name};參數信息:{arguments}");
foreach (var message in toolUseMessage)
{
var functionResultContent = (FunctionResultContent)message.Contents[0];
Console.WriteLine($"調用工具結果:{functionResultContent.Result}");
}
Console.ForegroundColor = ConsoleColor.White;
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("本次沒有調用工具");
Console.ForegroundColor = ConsoleColor.White;
}
return response.Text;
}
代碼已經放到GitHub,地址:https://github.com/Ming-jiayou/mcp_demo
將.env-example修改為.env應該就可以運行,如果報錯,設置成嵌入的資源即可。
.env配置示例:
API_KEY=sk-xxx
BaseURL=https:
ModelID=Qwen/Qwen2.5-72B-Instruct
MCPCommand=node
MCPArguments=D:/Learning/AI-related/fetch-mcp/dist/index.js
?轉自https://www.cnblogs.com/mingupupu/p/18772576
該文章在 2025/3/17 9:38:15 編輯過