【亲测免费】 Model Context Protocol C SDK 使用教程

Model Context Protocol C# SDK 使用教程

【免费下载链接】csharp-sdk The official C# SDK for Model Context Protocol servers and clients, maintained by Microsoft 【免费下载链接】csharp-sdk 项目地址: https://gitcode.com/gh_mirrors/csha/csharp-sdk

1. 项目介绍

Model Context Protocol C# SDK 是一个开源项目,为 .NET 应用程序、服务和库提供了与 Model Context Protocol (MCP) 进行交互的能力。MCP 是一个开放协议,它标准化了应用程序向大型语言模型(LLMs)提供上下文的方式,实现了 LLMs 与各种数据源和工具的安全集成。

2. 项目快速启动

安装

首先,您需要通过 NuGet 安装 MCP C# SDK 包:

dotnet add package ModelContextProtocol --prerelease

创建客户端

以下是一个创建 MCP 客户端并连接到服务器的示例:

var client = await McpClientFactory.CreateAsync(new McpClientOptions
{
    Id = "everything",
    Name = "Everything",
    TransportType = TransportTypes.StdIo,
    TransportOptions = new Dictionary<string, object>
    {
        ["command"] = "npx",
        ["arguments"] = "-y @modelcontextprotocol/server-everything"
    }
});

// 打印服务器提供的工具列表
foreach (var tool in await client.ListToolsAsync())
{
    Console.WriteLine($"{tool.Name} ({tool.Description})");
}

// 调用一个工具(通常由 LLM 工具调用驱动)
var result = await client.CallToolAsync("echo", new Dictionary<string, object?>
{
    ["message"] = "Hello MCP!"
}, CancellationToken.None);

// echo 总是返回一个文本内容对象
Console.WriteLine(result.Content.First(c => c.Type == "text").Text);

创建服务器

以下是一个创建 MCP 服务器并注册应用程序中所有工具的示例:

var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
    // 配置所有日志输出到 stderr
    consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});

builder.Services.AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();

注册工具

这里是一个注册工具的例子,包括一个简单的 Echo 工具:

[McpServerToolType]
public static class EchoTool
{
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) => $"Hello {message}";
}

3. 应用案例和最佳实践

在这一部分,您将学习如何在实际应用中使用 MCP C# SDK。我们将提供案例代码和最佳实践,帮助您更好地集成和使用 SDK。

4. 典型生态项目

在这一部分,我们将介绍一些使用 MCP C# SDK 的典型生态项目,包括它们的功能和如何与这些项目进行交互。

请注意,以上代码和说明仅为快速启动示例,实际使用时可能需要根据具体需求进行调整。随着项目的进展,我们将提供更多详细文档和示例代码。

【免费下载链接】csharp-sdk The official C# SDK for Model Context Protocol servers and clients, maintained by Microsoft 【免费下载链接】csharp-sdk 项目地址: https://gitcode.com/gh_mirrors/csha/csharp-sdk

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值