使用说明
构建自己的MCP服务器
我们正在使用这个研讨会。Net 9、Visual Studio Code和GitHub Copilot。请确保所有内容都已安装、配置和许可。
Resources:
本地
如果按如下方式安装MCP服务器模板,则可以跳过步骤2至6:
dotnet new install Microsoft.McpServer.ProjectTemplates
dotnet new mcpserver
- 打开终端(VS代码 控制+移动+
</kbd> and typecode-r{path}`)并转到您的第一个MCP服务器项目想要驻留的位置。
cd C:\Repos\9A\MCP
- 创建新的控制台应用程序
dotnet new console -n NineAFirstMCPServer
- 转到项目文件夹
cd .\NineAFirstMCPServer\
- 添加NuGet包
dotnet add package ModelContextProtocol --prerelease
dotnet add package Microsoft.Extensions.Hosting
- 打开
Program.cs在VS代码中,用以下代码替换现有代码:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options =>
{
// stdout is reserved for MCP communication, divert logs to stderr
options.LogToStandardErrorThreshold = LogLevel.Trace;
});
// Add MCP service
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly(); // Scan assembly for classes marked with [McpServerToolType] attribute
// Add additional services
await builder.Build().RunAsync();
- 将工具类添加到项目中:
dotnet new class -n DemoTool
- 打开新创建的类文件
DemoTool.cs并添加以下代码:
using System.ComponentModel;
using ModelContextProtocol.Server;
namespace NineAFirstMCPServer;
[McpServerToolType]
public static class DemoTool
{
}
- 现在将一些工具添加到这个类中:
[McpServerToolType]
public static class DemoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"hello {message}";
[McpServerTool, Description("Tell MCP server name to the client.")]
public static string MyName() => $"My name is '{nameof(NineAFirstMCPServer)} von NineAltitudes'.";
[McpServerTool, Description("Converts the message to camelCase.")]
public static string CamelCase(string message)
{
var words = message.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0) return string.Empty;
var result = words[0].ToLower();
for (int i = 1; i < words.Length; i++)
{
if (words[i].Length > 0)
result += char.ToUpper(words[i][0]) + words[i][1..].ToLower();
}
return result;
}
}
- 创建
.vscode项目根目录下的文件夹(如果尚未存在)。
mkdir .vscode
- 在此文件夹中创建一个名为的文件
mcp.json.打开它并复制粘贴以下json:
{
"inputs": [],
"servers": {
"NineAFirstMCP": {
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"{path to .csproj file}" <- change
]
}
}
}
- 启动MCP服务器:保存时,它可以自动启动服务器。否则,请单击启动服务器
Start在“服务器”下mcp.json或按 控制+甲状旁腺功能亢进+P 然后键入“MCP”,选择“MCP:列出服务器”并选择 NineAFirst MCP 紧随其后 启动服务器. - 在VS代码Github Copilot中提示可能触发新MCP服务器的内容,例如“Camelcase以下消息:'一些随机消息'”。
享受。
连接到现有API
为了获取数据或使我们的MCP服务器执行我们需要连接到外部源的操作。这可以是现有的API、数据库,也可以只是某个文件共享。让我们在MCP服务器上实现一个外部API。
- 创建用于创建外部连接的新服务类:
dotnet new class -n ExternalApiService
- 添加所需的NuGet包
dotnet add package Microsoft.Extensions.Http
- 更新
Program.cs注入依赖 Http客户端;
// Add additional services
builder.Services.AddHttpClient();
- 通过以下代码添加用于与外部API通信的Http客户端:
using System.Text.Json;
namespace NineAFirstMCPServer;
public class ExternalApiService
{
private readonly IHttpClientFactory _httpClient;
public ExternalApiService(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory;
}
public async Task<string> GetJokeAsync()
{
try
{
var client = _httpClient.CreateClient();
var response = await client.GetAsync("https://official-joke-api.appspot.com/random_joke");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var joke = JsonSerializer.Deserialize<Joke>(content, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return joke != null ? $"{joke.Setup} - {joke.Punchline}" : "No joke found.";
}
catch (HttpRequestException ex)
{
return $"HTTP error occurred: {ex.Message}";
}
catch (JsonException ex)
{
return $"Failed to parse response: {ex.Message}";
}
catch (Exception ex)
{
return $"{nameof(ExternalApiService)} failed: {ex.Message}";
}
}
private class Joke
{
public string Setup { get; set; }
public string Punchline { get; set; }
}
}
- 更新
Program.cs添加新 外部服务 作为一个歌手
using NineAFirstMCPServer;
...
// Add additional services
...
builder.Services.AddSingleton<ExternalApiService>();
- 创建新的工具类:
dotnet new class -n ExternalApiTool
- 添加MCP属性
[McpServerToolType],添加外部API服务externalApiService并定义一些与外部API交互的工具:
using System.ComponentModel;
using ModelContextProtocol.Server;
namespace NineAFirstMCPServer;
[McpServerToolType]
public class ExternalApiTool
{
private readonly ExternalApiService _externalApiService;
public ExternalApiTool(ExternalApiService externalApiService)
{
_externalApiService = externalApiService;
}
[McpServerTool, Description("Fetches a random joke from an external API")]
public async Task<string> GetRandomJokeAsync()
{
return await _externalApiService.GetJokeAsync();
}
}
与代理人交谈
工具可以有 McpServer 表示通过参数注入到方法中的服务器,并且可以使用该参数与连接的客户端进行交互。基本上,您可以要求客户端执行LLM任务,如总结或翻译消息。
您还可以使用预定义提示 [McpServerPrompt] 属性。
[McpServerPromptType]
public static class MyPrompts
{
[McpServerPrompt, Description("Creates a prompt to summarize the provided message.")]
public static ChatMessage Summarize([Description("The content to summarize")] string content) =>
new(ChatRole.User, $"Please summarize this content into a single sentence: {content}");
}
配置hpw以处理客户端请求
...
容器
...
