使用说明
MCP-创建自己的工具
一旦你知道该怎么做,创建自己的MCP服务器就出奇地容易。 首先,您需要:
- .net(9+)安装在您的计算机上(或dev容器等),
- IDE的选择-在这里我们将使用Visual Studio Code,
- 创建项目:
新控制台-n McpServerExample
- 添加必要的包:
微软.NET添加包。扩展。托管
.net添加包--预发布ModelContextProtocol
- 在Program.cs中添加以下代码:
using Microsoft.Extensions.Hosting;
var builder = Host.CreateApplicationBuilder(args);
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly()
.WithPromptsFromAssembly()
.WithResourcesFromAssembly();
await builder.Build().RunAsync();
- 创建一个名为“工具”的新文件夹
- 在此新文件夹中,添加“DotnetFoundationpositoryReporter.cs”类
- 键入以下代码:
using ModelContextProtocol.Server;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace McpServerExample.Tools;
[McpServerToolType]
internal class DotnetFoundationRepositoryReporter
{
[McpServerTool(Name = "GetDotnetFoundationRepositories")]
[Description("Fetches repositories from the .NET Foundation GitHub organization.")]
internal async Task<string> GetDotnetFoundationRepositories()
{
using HttpClient client = new();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("User-Agent", "McpServerExample");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
var json = await client.GetStringAsync("https://api.github.com/orgs/dotnet/repos");
return json;
}
}
- 构建项目:
.net构建
- 现在有趣的部分-使用我们的MCP服务器:
a) 使用Visual Studio代码打开一个新的空文件夹
b) 创建一个名为“.vscode”的新文件夹
c) 在此文件夹中创建mcp.json文件,内容如下:
{
"inputs": [],
"servers": {
"McpServerExample":{
"type": "stdio",
"command": "dotnet",
"args": [
"run",
"--project",
"McpServerExample.csproj", //Path to your project created in first point
"--no-build"
]
}
}
}
- 如果一切顺利,在“McpServerExample”文件顶部应显示播放图标和单词“Start”。点击它。
- 在您的visual studio中以代理模式打开副驾驶聊天,并询问类似“github存储库做什么。net foundation当前维护”这样的问题。
您的代理将请求使用新创建的工具的权限。授予它,它将返回一个公共GitHub存储库列表。
资源:
- https://learn.microsoft.com/en-us/dotnet/ai/quickstarts/build-mcp-server
- https://youtu.be/DpyjAKmNwpI?si=ea6frTWNn5gty-u1
- https://github.com/MarcinSredzinski/McpServerExample
