C#使用MCP协议调用大模型示例

前置条件

运行平台:.NET 9.0

所需包:

Microsoft.Extensions.AI
Microsoft.Extensions.AI.OpenAI
modelcontextprotocol

项目类型:控制台

示例代码

using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using OpenAI;
using System.ClientModel;

var transport = new StdioClientTransport(new StdioClientTransportOptions
{
    Name = "MyMCPClient",
    Command = "npx",
    Arguments = ["-y", "@modelcontextprotocol/server-everything"]
});

await using var mcpClient = await McpClient.CreateAsync(transport);
IList<McpClientTool> tools = await mcpClient.ListToolsAsync();

Console.WriteLine("已从MCP服务器加载以下工具:");
foreach (var tool in tools)
{
    Console.WriteLine($"- {tool.Name}: {tool.Description}");
}
Console.WriteLine();

var services = new ServiceCollection();
var client = new OpenAIClient(
    new ApiKeyCredential("sk-f1e"),
    new OpenAIClientOptions
    {
        Endpoint = new Uri("https://api.deepseek.com/v1")
    }
);

var chatClient = client
    .GetChatClient("deepseek-chat")
    .AsIChatClient();

//4.对话循环
List<ChatMessage> messages = [];
while (true)
{
    Console.Write("\n提问: ");
    var userInput = Console.ReadLine();
    if (string.IsNullOrEmpty(userInput)) continue;

    messages.Add(new ChatMessage(ChatRole.User, userInput));
    var response = await chatClient.GetResponseAsync(messages, new ChatOptions
    {
        Tools = [.. tools] //将MCP工具作为普通工具传入
    });

    var assistantMessage = response.Messages;
    messages.AddRange(assistantMessage);
    foreach(var i in assistantMessage)
    {
        Console.WriteLine($"\n {i.Role}:{i.Text}");
    }
}

示例结果

391286c48ef5b2a4e1aac7cd0cf07dc3

 

posted @ 2026-07-16 15:46  Shapley  阅读(4)  评论(0)    收藏  举报