烂翻译系列之——MCP开发——构建MCP客户端

Get started building your own client that can integrate with all MCP servers.

开始构建你自己的客户端,以集成所有 MCP 服务。

In this tutorial, you’ll learn how to build an LLM-powered chatbot client that connects to MCP servers.

在本教程中,你将学习如何构建一个支持大语言模型(LLM)的聊天机器人客户端,并连接到 MCP 服务。

Before you begin, it helps to have gone through our Build an MCP Server tutorial so you can understand how clients and servers communicate.

开始之前,建议你先完成我们的《构建 MCP 服务》教程,以便更好地理解客户端与服务端之间的通信机制。

You can find the complete code for this tutorial here.

你可以在此处找到本教程的完整代码。

System Requirements    系统要求

Before starting, ensure your system meets these requirements:

开始之前,请确保你的系统满足以下要求:

  • .NET 8.0 or higher    .NET 8.0 或更高版本
  • Anthropic API key (Claude)    Anthropic API 密钥(用于访问 Claude)
  • Windows, Linux, or macOS

Setting up your environment    设置你的环境

First, create a new .NET project:

首先,创建一个新的 .NET 项目:

dotnet new console -n QuickstartClient
cd QuickstartClient

Then, add the required dependencies to your project:

然后,向你的项目添加所需的依赖项:

dotnet add package ModelContextProtocol --prerelease
dotnet add package Anthropic.SDK
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.AI

Setting up your API key    设置你的 API 密钥

You’ll need an Anthropic API key from the Anthropic Console.

你需要从 Anthropic 控制台获取一个 Anthropic API 密钥。

dotnet user-secrets init
dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>"

Creating the Client    创建客户端

Basic Client Structure    基础客户端结构

First, let’s setup the basic client class in the file Program.cs:

首先,让我们在 Program.cs 文件中设置基础的客户端类:

using Anthropic.SDK;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;

var builder = Host.CreateApplicationBuilder(args);

builder.Configuration
    .AddEnvironmentVariables()
    .AddUserSecrets<Program>();

This creates the beginnings of a .NET console application that can read the API key from user secrets.

这将创建一个 .NET 控制台应用程序的初始结构,能够从用户机密(user secrets)中读取 API 密钥。

Next, we’ll setup the MCP Client:

接下来,我们将设置 MCP 客户端:

var (command, arguments) = GetCommandAndArguments(args);

var clientTransport = new StdioClientTransport(new()
{
    Name = "Demo Server",
    Command = command,
    Arguments = arguments,
});

await using var mcpClient = await McpClientFactory.CreateAsync(clientTransport);

var tools = await mcpClient.ListToolsAsync();
foreach (var tool in tools)
{
    Console.WriteLine($"Connected to server with tools: {tool.Name}");
}

Add this function at the end of the Program.cs file:

将此函数添加到 Program.cs 文件的末尾:

static (string command, string[] arguments) GetCommandAndArguments(string[] args)
{
    return args switch
    {
        [var script] when script.EndsWith(".py") => ("python", args),
        [var script] when script.EndsWith(".js") => ("node", args),
        [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", ["run", "--project", script, "--no-build"]),
        _ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
    };
}

代码说明:

在C#中,return args switch { ... } 是一种使用模式匹配的switch表达式语法。这种语法从C# 8.0开始引入,它允许更简洁的模式匹配和返回值的方式。

  1. 模式匹配语法

    • return args switch { ... } 是一个switch表达式,它根据args的值返回不同的结果

    • [var script] 是列表模式,匹配只有一个元素的数组并将该元素赋值给script变量

    • when条件用于进一步筛选匹配情况

  2. 匹配模式

    • 第一个模式匹配以.py结尾的文件,返回python命令

    • 第二个模式匹配以.js结尾的文件,返回node命令

    • 第三个模式匹配存在的目录或以.csproj结尾的文件,返回dotnet命令

    • 默认情况抛出异常

This creates an MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.

这将创建一个 MCP 客户端,该客户端会连接到作为命令行参数提供的服务,然后列出所连接服务上可用的工具。

Query processing logic    查询处理逻辑

Now let’s add the core functionality for processing queries and handling tool calls: 

现在,让我们添加用于处理查询和调用工具的核心功能:

using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
    .Messages
    .AsBuilder()
    .UseFunctionInvocation()
    .Build();

var options = new ChatOptions
{
    MaxOutputTokens = 1000,
    ModelId = "claude-3-5-sonnet-20241022",
    Tools = [.. tools]
};

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("MCP Client Started!");
Console.ResetColor();

PromptForInput();
while(Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase))
{
    if (string.IsNullOrWhiteSpace(query))
    {
        PromptForInput();
        continue;
    }

    await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))
    {
        Console.Write(message);
    }
    Console.WriteLine();

    PromptForInput();
}

static void PromptForInput()
{
    Console.WriteLine("Enter a command (or 'exit' to quit):");
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.Write("> ");
    Console.ResetColor();
}

Key Components Explained    关键组件说明

1. Client Initialization    客户端初始化

  • The client is initialized using McpClientFactory.CreateAsync(), which sets up the transport type and command to run the server.    客户端通过 McpClientFactory.CreateAsync() 进行初始化,该方法会设置传输类型以及用于运行服务的命令。

2. Server Connection    服务连接

  • Supports Python, Node.js, and .NET servers.    支持连接 Python、Node.js 和 .NET 编写的服务。

  • The server is started using the command specified in the arguments.    使用命令行参数中指定的命令启动服务。

  • Configures to use stdio for communication with the server.    配置为通过标准输入输出(stdio)与服务进行通信。

  • Initializes the session and available tools.    初始化会话并获取服务提供的可用工具列表。

3. Query Processing    查询处理

  • Leverages Microsoft.Extensions.AI for the chat client.    使用 Microsoft.Extensions.AI 构建聊天客户端。

  • Configures the IChatClient to use automatic tool (function) invocation.    配置 IChatClient 以支持自动调用工具(函数)(通过UseFunctionInvocation())。

  • The client reads user input and sends it to the server.    客户端读取用户输入并将其发送至服务。

  • The server processes the query and returns a response.    服务处理查询并返回结果。

  • The response is displayed to the user.    将最终响应呈现给用户。

Running the Client    运行客户端

To run your client with any MCP server:

运行你的客户端使用任意 MCP 服务:

dotnet run -- path/to/server.csproj # dotnet server
dotnet run -- path/to/server.py # python server
dotnet run -- path/to/server.js # node server

If you’re continuing the weather tutorial from the server quickstart, your command might look something like this: dotnet run -- path/to/QuickstartWeatherServer.

如果您继续使用基于服务快速入门中的天气练习,你的命令可能类似于:dotnet run -- path/to/QuickstartWeatherServer

The client will:

客户端将执行以下操作:

  1. Connect to the specified server    连接到指定的服务

  2. List available tools    列出可用的工具

  3. Start an interactive chat session where you can:    启动一个交互式聊天会话,在其中你可以:

    • Enter queries    输入查询

    • See tool executions    看到工具的执行过程

    • Get responses from Claude    获取 Claude 返回的响应

  4. Exit the session when done    完成后退出会话

Here’s an example of what it should look like it connected to a weather server quickstart:

以下是一个连接到天气服务快速入门示例时的运行效果:

image

posted @ 2025-09-18 17:50  菜鸟吊思  阅读(7)  评论(0)    收藏  举报