MCP服务器模板
一个用于使用ASP.NET Core创建模型上下文协议(MCP)服务器的全面.NET模板。此模板为构建能够与AI助手和其他MCP客户端集成的MCP服务器提供了坚实的基础。
什么是MCP?
该 模型上下文协议(MCP) 是一种开放标准,旨在使人工智能助手能够安全地访问外部资源和工具。MCP服务器提供三大主要功能:
- 工具AI助手可调用以执行操作的函数
- 资源助手可访问的只读数据,用于提供上下文信息
- 提示用于常见AI任务的可重用提示模板
快速入门
使用模板
- 安装模板:
dotnet new install ./- 创建一个新的MCP服务器:
dotnet new mcp-server -n MyCompany.McpServer
cd MyCompany.McpServer- 运行服务器:
dotnet run服务器将在 http://localhost:5000 默认情况下。
模板参数
--ServerName您MCP服务器的显示名称(默认:“我的MCP服务器”)--Port服务器的端口号(默认:5000)--Framework目标框架(默认:net8.0)
示例:
dotnet new mcp-server -n Acme.WeatherServer --ServerName "Acme Weather Service" --Port 8080项目结构
├── .template.config/ # Template configuration
│ └── template.json
├── Extensions/ # Utility extensions
│ └── HttpClientExtensions.cs
├── Tools/ # MCP tools implementation
│ └── ExampleTools.cs
├── Prompts/ # MCP prompts implementation
│ └── ExamplePrompts.cs
├── Resources/ # MCP resources implementation
│ └── ExampleResources.cs
├── Program.cs # Application entry point
├── appsettings.json # Configuration
├── Dockerfile # Docker configuration
└── README.md # This file创建自定义工具
工具是人工智能助手可以调用以执行操作的功能。以下是创建工具的方法:
1. 创建一个工具类
using System.ComponentModel;
using ModelContextProtocol.Server;
namespace YourNamespace.Tools;
[McpServerToolType]
public class MyTools
{
[McpServerTool, Description("Performs a custom operation")]
public static string MyTool([Description("Input parameter")] string input)
{
// Your tool logic here
return $"Processed: {input}";
}
}2. 带有依赖的异步工具
[McpServerTool, Description("Fetches data from an API")]
public static async Task FetchData(
HttpClient httpClient, // Injected dependency
[Description("API endpoint")] string endpoint)
{
var response = await httpClient.GetStringAsync(endpoint);
return response;
}3. 复杂返回类型
[McpServerTool, Description("Gets user information")]
public static string GetUserInfo([Description("User ID")] int userId)
{
var user = new { Id = userId, Name = "John Doe", Email = "john@example.com" };
return JsonSerializer.Serialize(user, new JsonSerializerOptions { WriteIndented = true });
}创建自定义提示
提示是人工智能交互中可重复使用的模板:
using Microsoft.Extensions.AI;
using ModelContextProtocol.Server;
namespace YourNamespace.Prompts;
[McpServerPromptType]
public class MyPrompts
{
[McpServerPrompt, Description("Creates a prompt for data analysis")]
public static ChatMessage AnalyzeData(
[Description("Data to analyze")] string data,
[Description("Analysis type")] string analysisType = "summary")
{
return new ChatMessage(ChatRole.User,
$"Please perform a {analysisType} analysis of this data: {data}");
}
}创建自定义资源
资源提供对数据的只读访问权限:
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
namespace YourNamespace.Resources;
[McpServerResourceType]
public class MyResources
{
[McpServerResource(UriTemplate = "data://users/{id}", Name = "User Data")]
public static ResourceContents GetUser(string id)
{
var userData = GetUserById(id); // Your data retrieval logic
return new BlobResourceContents
{
Blob = JsonSerializer.Serialize(userData),
MimeType = "application/json",
Uri = $"data://users/{id}"
};
}
}配置
服务器配置
配置服务器中的(设置/参数) appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
}
}
}
}环境变量
ASPNETCORE_ENVIRONMENT设置为Development用于增强日志记录ASPNETCORE_URLS覆盖默认监听URL
Docker 支持
使用 Docker 构建并运行
# Build the image
docker build -t my-mcp-server .
# Run the container
docker run -p 5000:5000 my-mcp-serverDocker Compose
version: '3.8'
services:
mcp-server:
build: .
ports:
- "5000:5000"
environment:
- ASPNETCORE_ENVIRONMENT=Production测试您的MCP服务器
1. 使用curl
测试服务器端点:
# Check server health
curl http://localhost:5000/health
# List available tools
curl -X POST http://localhost:5000/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'2. 使用MCP客户端
将您的MCP服务器连接到兼容的客户端,例如:
- Claude Desktop(中文可译为“克劳德桌面版”或根据具体语境简化为“克劳德桌面”,但通常直接保留原名以体现其品牌特色)
- 带有MCP扩展的VS Code
- 自定义MCP客户端
3. 测试模板生成
创建一个测试脚本来验证模板功能:
#!/bin/bash
# Test template generation
rm -rf test-output
dotnet new mcp-server -n TestServer -o test-output
cd test-output
dotnet build
dotnet run &
sleep 5
curl http://localhost:5000/health
pkill -f "TestServer"建筑学
依赖注入
该模板使用ASP.NET Core内置的依赖注入(DI)容器。常用服务已预先配置:
HttpClient在工具中进行HTTP请求ILogger用于应用程序中的日志记录- MCP服务器服务:自动注册
自动发现
MCP服务器自动发现:
- 在装饰有(特定属性或注解)的类中使用的工具
[McpServerToolType] - 课堂上的提示装饰着
[McpServerPromptType] - 在使用(特定装饰器)装饰的类中的资源
[McpServerResourceType]
错误处理
该模板包含了适当的错误处理机制:
- 工具异常被捕获并作为错误响应返回
- HTTP客户端错误得到妥善处理
- 验证错误已正确格式化
最佳实践
1. 工具设计
- 保持工具专注于单一职责
- 使用描述性名称和文档说明
- 验证输入参数
- 优雅地处理错误
- 在可能的情况下返回结构化数据
2. 安全性
- 验证所有输入
- 在生产环境中使用HTTPS
- 如需,请实施适当的认证措施
- 不要在错误消息中暴露敏感信息
3. 表现/性能
- 使用 async/await 进行 I/O 操作
- 缓存耗时的计算结果
- 实施适当的资源处置
- 监控内存使用情况
4. 文件记录
- 记录所有工具、提示和资源
- 提供清晰的参数描述
- 包含使用示例
- 维护API文档
示例实现
该模板包含全面的示例:
工具
- 回声简单的文本处理
- 计算数学运算
- 获取时间戳日期/时间工具
- 检查HTTP状态码HTTP 监控
- 生成UUID身份标识生成
提示
- 总结内容摘要
- 审查代码代码审查协助
- 解释代码代码解释
- 生成文档文档生成
- 翻译文本语言翻译
资源
- 配置服务器设置
- 系统状态健康监测
- API 文档交互式文档
故障排除
常见问题
- 端口已被使用更改端口中的
appsettings.json - 未找到程序集确保所有依赖项都已恢复
dotnet restore - 未发现工具验证
[McpServerToolType]属性存在 - JSON序列化错误检查返回类型并确保它们是可序列化的
调试
通过设置启用详细日志记录 ASPNETCORE_ENVIRONMENT=Development:
export ASPNETCORE_ENVIRONMENT=Development
dotnet run