惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
I
InfoQ
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
小众软件
小众软件
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
Engineering at Meta
Engineering at Meta
人人都是产品经理
人人都是产品经理
Microsoft Security Blog
Microsoft Security Blog
Last Week in AI
Last Week in AI
H
Help Net Security
爱范儿
爱范儿
云风的 BLOG
云风的 BLOG
博客园 - 司徒正美
Y
Y Combinator Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Microsoft Azure Blog
Microsoft Azure Blog
L
LangChain Blog
WordPress大学
WordPress大学
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
腾讯CDC

博客园 - Shapley

项目心得 进程间通讯方式 SQL Server LEAD函数实践 sql server行专列一例 数据库字段排序方法两则 Sql Server生成ULID例子 审批流进化记 winform+Task+async 献丑贴:Task.Run中foreach优化 Sql Server Begin TRY sample No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter' has been registered. 某低代码平台自定义控件技术点 Element-plus的el-date-picker控件动态切换中英文方案 Chrome浏览器无法查看页面跳转前的请求日志及解决办法 element-plus上传视频并生成缩略图(封面)方案 JWT自动刷新草案 Ajax方法POST的两种提交方式 H5项目在微信浏览器运行实录 Sql Server变量声明及使用技巧 修改Dify的Nginx对外访问端口 Task with Console(with SemaphoreSlim) Task实战 asp.net core 9.0发布centos7.9 Barrier CountdownEvent
C#使用MCP协议调用大模型示例
Shapley · 2026-07-16 · via 博客园 - Shapley

前置条件

运行平台:.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