Azure功能MCP服务器模板
中用于构建具有MCP(模型上下文协议)服务器功能的Azure函数的标准化模板。网8。
特性
- Azure OpenAI集成:GPT-4和GPT-3.5型号的内置适配器
- 双模式操作:作为Azure Function或独立MCP服务器运行
- 干净的建筑:独立的核心、服务、功能和测试项目
- MCP协议实施:完整的基于JSON-RPC的MCP服务器
- HTTP弹性:内置重试和断路器策略
- 综合测试:单元和集成测试基础设施
- 配置管理:基于环境的配置,带有选项模式
- 日志记录:支持控制台和Application Insights的结构化日志记录
项目结构
AzureFunctionMCPTemplate/
├── src/
│ ├── Template.Core/ # Domain models and interfaces
│ ├── Template.Functions/ # Azure Functions and MCP server
│ ├── Template.Services/ # Business logic and external clients
│ └── Template.Tests/ # Unit and integration tests
├── scripts/
│ ├── run-mcp-server.sh # Run as MCP server
│ ├── run-azure-function.sh # Run as Azure Function
│ └── test-mcp-server.sh # Test MCP protocol
├── docs/ # Additional documentation
└── Template.sln # Solution file先决条件
🚀 将模板转换为MCP应用程序
按照以下步骤将此模板转换为您自己的MCP应用程序:
步骤1:克隆和重命名
# Clone the template
cp -r ~/DevProjects/AzureFunctionMCPTemplate ~/DevProjects/YourAppMCP
# Navigate to your new project
cd ~/DevProjects/YourAppMCP
# Rename solution file
mv Template.sln YourApp.sln步骤2:更新项目名称
- 重命名项目目录和文件:
# Rename directories
mv src/Template.Core src/YourApp.Core
mv src/Template.Functions src/YourApp.Functions
mv src/Template.Services src/YourApp.Services
mv src/Template.Tests src/YourApp.Tests
# Rename project files
mv src/YourApp.Core/Template.Core.csproj src/YourApp.Core/YourApp.Core.csproj
mv src/YourApp.Functions/Template.Functions.csproj src/YourApp.Functions/YourApp.Functions.csproj
mv src/YourApp.Services/Template.Services.csproj src/YourApp.Services/YourApp.Services.csproj
mv src/YourApp.Tests/Template.Tests.csproj src/YourApp.Tests/YourApp.Tests.csproj- 更新所有C#文件中的命名空间:
# On macOS/Linux
find . -name "*.cs" -type f -exec sed -i '' 's/Template\.Core/YourApp.Core/g' {} +
find . -name "*.cs" -type f -exec sed -i '' 's/Template\.Functions/YourApp.Functions/g' {} +
find . -name "*.cs" -type f -exec sed -i '' 's/Template\.Services/YourApp.Services/g' {} +
find . -name "*.cs" -type f -exec sed -i '' 's/Template\.Tests/YourApp.Tests/g' {} +
# Update project references
find . -name "*.csproj" -type f -exec sed -i '' 's/Template\./YourApp./g' {} +- 更新解决方案文件:
sed -i '' 's/Template/YourApp/g' YourApp.sln步骤3:定义您的域名
- 创建您的域模型 在……里面
src/YourApp.Core/Models/:
// src/YourApp.Core/Models/YourDomainModels.cs
namespace YourApp.Core.Models;
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
// Add your properties
}- 定义您的服务接口 在……里面
src/YourApp.Core/Interfaces/:
// src/YourApp.Core/Interfaces/ICustomerService.cs
namespace YourApp.Core.Interfaces;
public interface ICustomerService
{
Task GetCustomerAsync(string id);
Task CreateCustomerAsync(Customer customer);
Task UpdateCustomerAsync(string id, Customer customer);
Task DeleteCustomerAsync(string id);
}步骤4:实施MCP工具
- 更新MCP服务器 在……里面
src/YourApp.Functions/MCP/McpServer.cs:
private readonly List _tools = new()
{
new Tool
{
Name = "get_customer",
Description = "Get customer information by ID",
InputSchema = new
{
type = "object",
properties = new
{
customerId = new { type = "string", description = "The customer ID" }
},
required = new[] { "customerId" }
}
},
new Tool
{
Name = "create_customer",
Description = "Create a new customer",
InputSchema = new
{
type = "object",
properties = new
{
name = new { type = "string", description = "Customer name" },
email = new { type = "string", description = "Customer email" }
},
required = new[] { "name", "email" }
}
}
// Add more tools as needed
};- 实施工具处理程序:
[JsonRpcMethod("tools/call")]
public async Task CallToolAsync(ToolCallParams toolParams)
{
var result = toolParams.Name switch
{
"get_customer" => await HandleGetCustomerAsync(toolParams.Arguments),
"create_customer" => await HandleCreateCustomerAsync(toolParams.Arguments),
// Add more tool handlers
_ => throw new Exception($"Unknown tool: {toolParams.Name}")
};
// Return result...
}
private async Task HandleGetCustomerAsync(Dictionary? arguments)
{
var customerId = arguments?["customerId"]?.ToString();
var customer = await _customerService.GetCustomerAsync(customerId);
return new { success = true, customer };
}步骤5:实施您的服务
- 创建服务实现 在……里面
src/YourApp.Services/Services/:
// src/YourApp.Services/Services/CustomerService.cs
using YourApp.Core.Interfaces;
using YourApp.Core.Models;
namespace YourApp.Services.Services;
public class CustomerService : ICustomerService
{
private readonly ILogger _logger;
private readonly IApiClient _apiClient;
public CustomerService(ILogger logger, IApiClient apiClient)
{
_logger = logger;
_apiClient = apiClient;
}
public async Task GetCustomerAsync(string id)
{
// Implement your business logic
return await _apiClient.GetAsync($"/customers/{id}");
}
// Implement other methods...
}步骤6:配置您的应用程序
- 更新配置 在……里面
src/YourApp.Functions/Configuration/AppConfiguration.cs:
public class YourAppConfiguration
{
public string ApiUrl { get; set; } = "https://your-api.com";
public string ApiKey { get; set; } = string.Empty;
public string DatabaseConnection { get; set; } = string.Empty;
// Add your configuration properties
}- 更新本地设置 在……里面
src/YourApp.Functions/local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"YourApp__ApiUrl": "https://your-api.com",
"YourApp__ApiKey": "your-api-key",
"YourApp__DatabaseConnection": "your-connection-string"
}
}步骤7:注册依赖关系
更新 Program.cs 注册您的服务:
private static void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
// Register your configuration
services.Configure(context.Configuration.GetSection("YourApp"));
// Register your services
services.AddScoped();
services.AddScoped();
// Add more service registrations
// Register MCP server with your services
services.AddScoped();
// Existing registrations...
}步骤8:添加Azure函数(可选)
在中创建HTTP触发函数 src/YourApp.Functions/Functions/:
public class CustomerFunction
{
private readonly ICustomerService _customerService;
public CustomerFunction(ICustomerService customerService)
{
_customerService = customerService;
}
[Function("GetCustomer")]
public async Task GetCustomer(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "customers/{id}")]
HttpRequestData req,
string id)
{
var customer = await _customerService.GetCustomerAsync(id);
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(customer);
return response;
}
}步骤9:测试您的MCP应用程序
- 构建解决方案:
dotnet build- 以MCP服务器运行:
./scripts/run-mcp-server.sh- 根据样品请求进行测试:
# Initialize
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"0.1.0"}}' | \
dotnet run --project src/YourApp.Functions -- --mcp
# List tools
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | \
dotnet run --project src/YourApp.Functions -- --mcp
# Call a tool
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_customer","arguments":{"customerId":"123"}}}' | \
dotnet run --project src/YourApp.Functions -- --mcp步骤10:配置MCP客户端
添加到Claude Desktop的配置中(~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"yourapp-server": {
"command": "dotnet",
"args": ["run", "--project", "/path/to/YourApp.Functions", "--", "--mcp"],
"env": {
"YourApp__ApiUrl": "https://your-api.com",
"YourApp__ApiKey": "your-api-key"
}
}
}
}快速入门指南
从模板到工作应用程序只需10分钟
- 复制模板并重命名:
cp -r AzureFunctionMCPTemplate MyAwesomeMCP
cd MyAwesomeMCP- 运行重命名脚本 (创建此助手):
#!/bin/bash
OLD_NAME="Template"
NEW_NAME="$1"
# Rename files and directories
find . -depth -name "*${OLD_NAME}*" | while read file; do
mv "$file" "${file//${OLD_NAME}/${NEW_NAME}}"
done
# Replace in files
find . -type f \( -name "*.cs" -o -name "*.csproj" -o -name "*.sln" -o -name "*.json" \) \
-exec sed -i '' "s/${OLD_NAME}/${NEW_NAME}/g" {} +- 定义你的第一个工具 在McpServer.cs中
- 实施工具处理程序
- 运行和测试:
./scripts/run-mcp-server.sh开发指南
添加新的MCP工具
- 在中定义工具
McpServer.cs:
new Tool
{
Name = "your_tool",
Description = "Tool description",
InputSchema = new
{
type = "object",
properties = new
{
param1 = new { type = "string", description = "Parameter description" }
},
required = new[] { "param1" }
}
}- 添加处理程序方法:
private async Task HandleYourToolAsync(Dictionary? arguments)
{
// Tool implementation
}- 在switch语句中注册:
"your_tool" => await HandleYourToolAsync(toolParams.Arguments),添加新的Azure功能
在中创建新类 src/Template.Functions/Functions/:
public class YourFunction
{
private readonly ILogger _logger;
private readonly IYourService _service;
public YourFunction(ILogger logger, IYourService service)
{
_logger = logger;
_service = service;
}
[Function("YourFunction")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "your-route")]
HttpRequestData req)
{
// Function implementation
}
}添加服务
- 在中定义接口
Template.Core/Interfaces/:
public interface IYourService
{
Task DoSomethingAsync(YourRequest request);
}- 实施中
Template.Services/Services/:
public class YourService : IYourService
{
// Implementation
}- 注册
Program.cs:
services.AddScoped();测试
运行所有测试
dotnet test跑步有保障
dotnet test --collect:"XPlat Code Coverage"测试MCP服务器
./scripts/test-mcp-server.sh部署
Azure部署
- 创建Azure功能应用程序:
az functionapp create --resource-group myResourceGroup \
--consumption-plan-location westus \
--runtime dotnet-isolated \
--runtime-version 8 \
--functions-version 4 \
--name myFunctionApp \
--storage-account mystorageaccount- 部署:
cd src/Template.Functions
func azure functionapp publish myFunctionAppDocker部署
创建一个 Dockerfile:
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish "src/Template.Functions/Template.Functions.csproj" -c Release -o /app/publish
FROM mcr.microsoft.com/azure-functions/dotnet-isolated:4-dotnet-isolated8.0
WORKDIR /home/site/wwwroot
COPY --from=build /app/publish .
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
AzureFunctionsJobHost__Logging__Console__IsEnabled=trueAI模型支持
此模板通过不同的适配器支持多种AI模型:
克劳德(通过MCP协议)
- 通过claude_desktop_config json支持原生MCP
- 直接工具集成
- 流媒体支持
Azure OpenAI(通过HTTP适配器)
- GPT-4 型号(gpt-4、gpt-4-32k、gpt-4涡轮、gpt-4o)
- GPT-3.5 型号(gpt-35-turbo、gpt-35-durbo-16k)
- 函数调用支持
- 视觉能力(gpt-4-turbo、gpt-4o)
其他人工智能服务
- 任何AI服务的通用HTTP端点
- OpenAPI/Swagger兼容
- 批处理工具执行
有关Azure OpenAI集成的详细说明,请参阅 docs/AZURE_OPENAI_INTEGRATION.md.
MCP客户端配置
克劳德桌面
增添 claude_desktop_config.json:
{
"mcpServers": {
"template-server": {
"command": "dotnet",
"args": ["run", "--project", "/path/to/Template.Functions", "--", "--mcp"],
"env": {
"App__ApiUrl": "https://your-api.com",
"App__ApiKey": "your-api-key"
}
}
}
}故障排除
常见问题
- 构建错误:确保。NET 8.0 SDK已安装
- 函数运行时错误:检查Azure功能核心工具版本
- MCP连接问题:验证JSON-RPC格式和工具名称
- HTTP客户端错误:检查API配置和网络连接
调试MCP服务器
启用详细日志记录:
services.AddLogging(builder =>
{
builder.AddConsole();
builder.SetMinimumLevel(LogLevel.Debug);
});调试Azure函数
使用Visual Studio或VS Code调试功能 launch.json 配置。
贡献
- 分叉存储库
- 创建要素分支
- 进行更改
- 添加测试
- 提交拉取请求
许可证
此模板按原样提供,供您在项目中使用。根据需要自定义许可证。
