快速开始
快速上手 MCP-Go。本指南将引导你创建第一个 MCP 服务端和客户端。
Hello World 服务端
让我们从最简单的 MCP 服务端开始 - 一个 "hello world" 工具:
go
package main
import (
"context"
"fmt"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
func main() {
// Create a new MCP server
s := server.NewMCPServer(
"Hello World Server",
"1.0.0",
server.WithToolCapabilities(true),
)
// Define a simple tool
tool := mcp.NewTool("hello_world",
mcp.WithDescription("Say hello to someone"),
mcp.WithString("name",
mcp.Required(),
mcp.Description("Name of the person to greet"),
),
)
// Add tool handler
s.AddTool(tool, helloHandler)
// Start the stdio server
if err := server.ServeStdio(s); err != nil {
fmt.Printf("Server error: %v\n", err)
}
}
func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
arguments := request.GetArguments()
name, ok := arguments["name"].(string)
if !ok {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: "Error: name parameter is required and must be a string",
},
},
IsError: true,
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Hello, %s! 👋", name),
},
},
}, nil
}将此保存为 hello-server/main.go 并运行:
bash
cd hello-server
go mod init hello-server
go get github.com/mark3labs/mcp-go
go run main.go运行你的第一个服务端
使用 Claude Desktop 测试
从 Anthropic 网站 下载并安装 Claude Desktop
配置你的服务端,编辑 Claude 的配置文件:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:%APPDATA%\Claude\claude_desktop_config.jsonjson{ "mcpServers": { "hello-world": { "command": "go", "args": ["run", "/path/to/your/hello-server/main.go"] } } }重启 Claude Desktop,查找表示 MCP 连接的 🔌 图标
测试你的工具,向 Claude 提问:"使用 hello_world 工具向 Alice 打招呼"
使用 MCP Inspector 测试
用于调试和开发,请使用 MCP Inspector:
bash
# 安装 MCP Inspector
npm install -g @modelcontextprotocol/inspector
# 使用 inspector 运行你的服务端
mcp-inspector go run main.go这会打开一个 Web 界面,你可以在其中交互式地测试你的工具。
基本客户端示例
你也可以创建 MCP 客户端来连接其他服务端:
go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/client/transport"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Create stdio transport
stdioTransport := transport.NewStdio("go", nil, "run", "path/to/server/main.go")
// Create client with the transport
c := client.NewClient(stdioTransport)
// Start the client
if err := c.Start(ctx); err != nil {
log.Fatalf("Failed to start client: %v", err)
}
defer c.Close()
// Initialize the client
initRequest := mcp.InitializeRequest{}
initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
initRequest.Params.ClientInfo = mcp.Implementation{
Name: "Hello World Client",
Version: "1.0.0",
}
initRequest.Params.Capabilities = mcp.ClientCapabilities{}
serverInfo, err := c.Initialize(ctx, initRequest)
if err != nil {
log.Fatalf("Failed to initialize: %v", err)
}
fmt.Printf("Connected to server: %s (version %s)\n",
serverInfo.ServerInfo.Name,
serverInfo.ServerInfo.Version)
// List available tools
if serverInfo.Capabilities.Tools != nil {
toolsRequest := mcp.ListToolsRequest{}
toolsResult, err := c.ListTools(ctx, toolsRequest)
if err != nil {
log.Fatalf("Failed to list tools: %v", err)
}
fmt.Printf("Available tools: %d\n", len(toolsResult.Tools))
for _, tool := range toolsResult.Tools {
fmt.Printf("- %s: %s\n", tool.Name, tool.Description)
}
// Call a tool
callRequest := mcp.CallToolRequest{}
callRequest.Params.Name = "hello_world"
callRequest.Params.Arguments = map[string]interface{}{
"name": "World",
}
result, err := c.CallTool(ctx, callRequest)
if err != nil {
log.Fatalf("Failed to call tool: %v", err)
}
// Print the result
for _, content := range result.Content {
if textContent, ok := content.(mcp.TextContent); ok {
fmt.Printf("Result: %s\n", textContent.Text)
}
}
}
}StreamableHTTP 客户端示例
对于基于 StreamableHTTP 的服务端,请使用 StreamableHTTP 客户端:
go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/client/transport"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Create HTTP transport
httpTransport, err := transport.NewStreamableHTTP("http://localhost:8080/mcp")
if err != nil {
log.Fatalf("Failed to create HTTP transport: %v", err)
}
// Create client with the transport
c := client.NewClient(httpTransport)
defer c.Close()
// Initialize the client
initRequest := mcp.InitializeRequest{}
initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
initRequest.Params.ClientInfo = mcp.Implementation{
Name: "StreamableHTTP Client",
Version: "1.0.0",
}
initRequest.Params.Capabilities = mcp.ClientCapabilities{}
serverInfo, err := c.Initialize(ctx, initRequest)
if err != nil {
log.Fatalf("Failed to initialize: %v", err)
}
fmt.Printf("Connected to server: %s (version %s)\n",
serverInfo.ServerInfo.Name,
serverInfo.ServerInfo.Version)
// Call a tool
if serverInfo.Capabilities.Tools != nil {
callRequest := mcp.CallToolRequest{}
callRequest.Params.Name = "hello_world"
callRequest.Params.Arguments = map[string]interface{}{
"name": "StreamableHTTP World",
}
result, err := c.CallTool(ctx, callRequest)
if err != nil {
log.Fatalf("Failed to call tool: %v", err)
}
fmt.Printf("Tool result: %+v\n", result)
}
}下一步
现在你已经有了一个可工作的 MCP 服务端和客户端:
常见问题
服务端无法启动
- 检查端口是否已被占用
- 验证 Go 模块依赖是否已安装
- 确保文件权限正确
客户端连接失败
- 验证服务端正在运行且可访问
- 检查 StreamableHTTP 客户端的网络连接
- 验证 stdio 客户端的命令路径
工具调用失败
- 验证工具参数类型与模式匹配
- 检查工具函数中的错误处理
- 使用 MCP Inspector 进行调试

