Cover image
Try Now
2025-04-14

Cliente MCP rápido con MCP C# SDK

3 years

Works with Finder

0

Github Watches

0

Github Forks

0

Github Stars

QuickstartClient

MCP Client Quickstart with MCP C# SDK

System Requirements

Before starting, ensure your system meets these requirements:

  • .NET 8.0 or higher
  • Anthropic API key (Claude)
  • Windows, Linux, or MacOS

Setting up your environment

First, create a new .NET project:

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

Setting up your API key

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

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:

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.

Next, we'll setup the MCP Client:

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:

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")
    };
}

This creates and configures a 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.

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.

2. Server Connection

  • Supports Python, Node.js, and .NET servers.
  • The server is started using the command specified in the arguments.
  • Configures to use stdio for communication with the server.
  • Initializes the session and available tools.

3. Query Processing

  • Leverages Microsoft.Extensions.AI for the chat client.
  • Configures the IChatClient to use automatic tool (function) invocation.
  • 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:

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`.

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
  4. Exit the session when done

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

Screenshot of the QuickstartClient connected to a weather server

相关推荐

  • av
  • Ejecute sin esfuerzo LLM Backends, API, frontends y servicios con un solo comando.

  • 1Panel-dev
  • 🔥 1Panel proporciona una interfaz web intuitiva y un servidor MCP para administrar sitios web, archivos, contenedores, bases de datos y LLM en un servidor de Linux.

  • WangRongsheng
  • 🧑‍🚀 全世界最好的 llM 资料总结(数据处理、模型训练、模型部署、 O1 模型、 MCP 、小语言模型、视觉语言模型) | Resumen de los mejores recursos del mundo.

  • rulego
  • ⛓️Rulego es un marco de motor de regla de orquestación de componentes de alta generación de alto rendimiento, de alto rendimiento y de alto rendimiento para GO.

  • Byaidu
  • Traducción de papel científico en PDF con formatos preservados - 基于 Ai 完整保留排版的 PDF 文档全文双语翻译 , 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 等服务 等服务 等服务 提供 提供 提供 提供 提供 提供 提供 提供 提供 提供 提供 提供 cli/mcp/docker/zotero

  • sigoden
  • Cree fácilmente herramientas y agentes de LLM utilizando funciones Plain Bash/JavaScript/Python.

  • hkr04
  • SDK liviano C ++ MCP (Protocolo de contexto del modelo)

  • RockChinQ
  • 😎简单易用、🧩丰富生态 - 大模型原生即时通信机器人平台 | 适配 Qq / 微信(企业微信、个人微信) / 飞书 / 钉钉 / Discord / Telegram / Slack 等平台 | 支持 Chatgpt 、 Deepseek 、 DiFy 、 Claude 、 Gemini 、 Xai 、 PPIO 、 Ollama 、 LM Studio 、阿里云百炼、火山方舟、 Siliconflow 、 Qwen 、 Moonshot 、 Chatglm 、 SillyTraven 、 MCP 等 LLM 的机器人 / Agente | Plataforma de bots de mensajería instantánea basada en LLM, admite Discord, Telegram, WeChat, Lark, Dingtalk, QQ, Slack

  • dmayboroda
  • Trapo conversacional local con contenedores configurables

  • modelscope
  • Iniciar aplicaciones de múltiples agentes empoderadas con Building LLM de manera más fácil.

    Reviews

    2.8 (4)
    Avatar
    user_HCQmFW9X
    2025-04-24

    I've been using QuickstartClient by mikekistler, and it has significantly streamlined my application setup process. This tool is incredibly user-friendly and efficient, making it an essential part of my workflow. Highly recommended for anyone looking to simplify their project initiation!

    Avatar
    user_xeYfYtRU
    2025-04-24

    QuickstartClient by mikekistler is an exceptional tool for effortless MCP applications. Its user-friendly interface and seamless integration make getting started incredibly easy. The detailed welcome information guides users step-by-step, ensuring a smooth experience. Highly recommend for anyone looking to streamline their MCP workflows!

    Avatar
    user_E1LHOqNc
    2025-04-24

    QuickstartClient by mikekistler is an outstanding tool for anyone looking to quickly and efficiently get started with MCP applications. As a loyal user, I appreciate its user-friendly interface and seamless integration capabilities. The product starts with a welcoming message that sets a positive tone and guides you through the initial setup effortlessly. Highly recommend for both beginners and experienced users!

    Avatar
    user_mrqtHEpq
    2025-04-24

    I've been using QuickstartClient by mikekistler, and it's been a game-changer for my workflow. The interface is intuitive, and it integrates seamlessly with my existing setup. The ease of getting started, thanks to the clear instructions and welcoming messages, is impressive. Highly recommend it to anyone looking for an efficient client solution!