MCP服务器模板(Go)
用于构建的生产就绪模板 模型上下文协议(MCP) Go中的服务器,遵循官方最佳实践和指导方针。
特性
- 完成MCP实施 -工具、资源和提示
- 生产准备就绪 -优雅的关机、信号处理和错误处理
- 测试良好 -带示例的单元和集成测试
- 可配置的 -基于YAML的配置与验证
- 安全 -输入验证、净化和最佳实践
- Docker支持 -已准备好进行集装箱化部署
- 最佳实践 -遵循官方MCP实施指南
快速开始
先决条件
- 达到1.23或更高
- Make(可选,用于使用Makefile命令)
安装
- 克隆或使用此模板:
git clone
cd mcp-server-template- 安装依赖项:
go mod download- 🚨 重要提示:清理模板示例
此模板包括示例工具、资源和提示。 在开始项目之前,您应该删除这些。
看 CLAUDE.md 有关以下内容的详细说明:
- 要删除哪些文件 - 如何清理注册表功能 - 如何更新配置 - 如何为您的项目自定义CLAUDE.md
快速清理:
# Remove example implementations
rm internal/tools/{search,calculate,analyze}.go
rm internal/tools/{search,calculate,analyze}_test.go
rm internal/resources/files.go internal/resources/files_test.go
rm internal/prompts/greet.go internal/prompts/greet_test.go
rm tests/integration/server_test.go tests/testdata/fixtures.json- 配置服务器:
# Edit configs/config.yaml to customize
nano configs/config.yaml- 构建并运行:
make build
make serve或者直接:
go run ./cmd/server serve用法
此服务器提供两个接口: MCP服务器模式 用于与MCP客户端集成,以及 CLI工具模式 用于直接命令行执行。
作为MCP服务器
使用stdio传输作为MCP服务器运行,以与MCP客户端集成(如Claude Desktop):
# Using make
make serve
# Or directly
./bin/server serve服务器将在前台运行,并通过stdin/stdout进行通信。按Ctrl+C进行优雅关机。
作为CLI工具
直接从命令行执行工具:
# Get help
./bin/server --help
./bin/server --version
# Get help for a specific command
./bin/server search --help
# Execute tools (examples - replace with your actual tools)
./bin/server search --query "golang testing" --limit 5
./bin/server calculate --operation add --a 10 --b 20
# Different output formats
./bin/server search --query "golang" --output json
./bin/server search --query "golang" --output yaml
./bin/server search --query "golang" --output text # default
# Quiet mode (exit code only, no output)
./bin/server search --query "golang" --quiet
echo $? # Check exit code注: 上面的示例命令假设您已经实现了以下工具 search 和 calculate。根据您的实际工具实现调整命令。
配置
MCP服务器模式和CLI工具模式都使用相同的配置文件:
# Use default config (configs/config.yaml)
./bin/server serve
# Use custom config
./bin/server --config /path/to/config.yaml serve
./bin/server --config /path/to/config.yaml search --query "test"项目结构
mcp-server-template/
├── cmd/
│ └── server/
│ └── main.go # Entry point with graceful shutdown
├── internal/
│ ├── tools/ # MCP tools (one per file)
│ │ ├── register.go # Tool registration
│ │ ├── search.go # Search tool
│ │ ├── search_test.go # Search tests (same package)
│ │ ├── calculate.go # Calculate tool
│ │ ├── calculate_test.go # Calculate tests
│ │ ├── analyze.go # Analyze tool
│ │ └── analyze_test.go # Analyze tests
│ ├── resources/ # MCP resources
│ │ ├── register.go # Resource registration
│ │ ├── files.go # File system resources
│ │ └── files_test.go # File tests
│ ├── prompts/ # MCP prompts
│ │ ├── register.go # Prompt registration
│ │ ├── greet.go # Greeting prompt
│ │ └── greet_test.go # Greeting tests
│ ├── config/ # Configuration management
│ │ ├── config.go # Config loading and validation
│ │ └── config_test.go # Config tests
│ └── services/ # Business logic (add your services here)
├── tests/
│ ├── integration/ # Integration tests
│ │ └── server_test.go # Full server tests
│ └── testdata/ # Test fixtures
│ └── fixtures.json
├── configs/
│ └── config.yaml # Server configuration
├── docs/
│ └── MCP_SERVER_IMPLEMENTATION_GUIDE.md # Complete implementation guide
├── go.mod # Go module definition
├── go.sum # Dependency checksums
├── Makefile # Build automation
├── Dockerfile # Container image
├── README.md # This file
└── CLAUDE.md # Instructions for Claude Code包括示例
工具
- 搜索 -搜索具有可配置限制的信息
- 计算 -执行算术运算(加、减、乘、除)
- 分析 -使用各种方法(情感、关键字、摘要)分析文本
资源
- 文件系统 -通过访问本地文件
file:///URI
提示
- 问候 -生成不同风格的个性化问候
配置
编辑 configs/config.yaml:
server:
name: "your-server-name"
version: "1.0.0"
port: 8080
features:
enable_tools: true
enable_resources: true
enable_prompts: true
environment: "dev" # dev, staging, production
tools:
search_enabled: true
analyze_enabled: true
calculate_enabled: true使用环境变量
对于机密和敏感数据,请使用环境变量:
# configs/config.yaml
database:
password: ${DB_PASSWORD}
api:
api_key: ${API_KEY}然后在运行前设置它们:
export DB_PASSWORD="your-password"
export API_KEY="your-api-key"
./bin/server发展
运行测试
# All tests with coverage
make test
# Unit tests only
make test-unit
# Integration tests only
make test-integration
# Generate coverage report
make coverage建筑
# Build binary
make build
# Run locally
make run
# Clean build artifacts
make clean代码质量
# Format code
make fmt
# Run linters (requires golangci-lint)
make lint码头工人
# Build image
make docker-build
# Run container
make docker-run添加新功能
添加新工具
- 创建
internal/tools/mytool.go:
package tools
import (
"context"
"fmt"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
type MyToolInput struct {
Query string `json:"query" jsonschema:"required,description=Your query"`
}
type MyToolOutput struct {
Result string `json:"result" jsonschema:"description=The result"`
}
func registerMyTool(server *mcp.Server) {
mcp.AddTool(server, &mcp.Tool{
Name: "mytool",
Description: "Description of what your tool does",
}, myToolHandler)
}
func myToolHandler(ctx context.Context, req *mcp.CallToolRequest, input MyToolInput) (
*mcp.CallToolResult, MyToolOutput, error,
) {
// Validate inputs
if input.Query == "" {
return nil, MyToolOutput{}, fmt.Errorf("query is required")
}
// Check context cancellation
select {
case <-ctx.Done():
return nil, MyToolOutput{}, ctx.Err()
default:
}
// Your implementation here
result := processQuery(input.Query)
return nil, MyToolOutput{Result: result}, nil
}- 创建
internal/tools/mytool_test.go(同一包装内)
- 更新
internal/tools/register.go:
func Register(server *mcp.Server, cfg *config.Config) {
// ...
registerMyTool(server)
}- 在中添加配置选项
configs/config.yaml:
tools:
mytool_enabled: true- 运行测试:
make test添加资源或提示
遵循相同的模式 internal/resources/ 或 internal/prompts/.
测试
此模板包括全面的测试:
- 单元测试 -测试单个函数和处理程序
- 集成测试 -测试具有所有功能的完整服务器
- 表驱动测试 -易于添加新的测试用例
- 错误测试 -验证错误处理
- 上下文测试 -验证上下文取消
提交前运行测试:
make test部署
标准传输(默认)
该模板默认使用stdio传输,适用于:
- CLI工具
- 本地集成
- 子流程沟通
HTTP传输
要使用HTTP传输,请修改 cmd/server/main.go:
// Change from stdio to HTTP
handler := mcp.NewStreamableHTTPHandler(
func(r *http.Request) *mcp.Server { return server },
nil,
)
log.Fatal(http.ListenAndServe(":8080", handler))Docker部署
# Build image
docker build -t your-server:latest .
# Run container (stdio)
docker run -i your-server:latest
# Run container (HTTP)
docker run -p 8080:8080 your-server:latest安全最佳实践
此模板遵循安全最佳实践:
- ✅ 所有工具的输入验证
- ✅ 文件路径清理
- ✅ 参数化查询(使用数据库时)
- ✅ 上下文取消支持
- ✅ 使用上下文包装时出错
- ✅ 没有硬编码的秘密
- ✅ Docker中的非root用户
始终:
- 验证并净化所有输入
- 对SQL使用参数化查询
- 永远不要将秘密提交给版本控制
- 对敏感数据使用环境变量
定制
重命名模块
- 更新
go.mod:
module your-module-name- 更新所有文件中的导入:
import "your-module-name/internal/config"- 运行:
go mod tidy删除示例功能
要删除示例工具/资源/提示:
- 从中删除相应的文件
internal/ - 更新
register.go文件 - 更新
configs/config.yaml - 运行测试以验证
文档
- 实施指南:参见
docs/MCP_SERVER_IMPLEMENTATION_GUIDE.md获取全面的指导方针 - MCP规范: https://modelcontextprotocol.io/specification
- Go SDK文档: https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk
贡献
欢迎投稿!拜托:
- 遵循现有的代码结构
- 为新功能添加测试
- 更新文档
- 跑
make test和make lint提交前
建筑原理
此模板遵循严格的架构原则:
- 每个文件一个工具 -可维护性和清晰度
- 注册模式 -集中功能注册
- 未导出处理程序 -清洁公共API
- 同一包装单元测试 -进入内部
- 单独的集成测试 -端到端测试
- 配置驱动 -没有硬编码值
- 上下文感知 -适当的取消支持
- 包装错误 -完整的错误上下文
看 CLAUDE.md 了解详细的架构指南。
许可证
\[您的许可证在这里\]
支持
如有疑问或问题:
- 查看中的实施指南
docs/ - 查看中的示例代码
internal/ - 在GitHub上打开一个问题
致谢
按照官方规定建造 MCP Go SDK 以及实施指南。
