go + vscode + cline + qwen 快速构建 MCP Server
go code :
package main
import (
"context"
"fmt"
"time"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
func main() {
// Create MCP server
s := server.NewMCPServer(
"Demo ?",
"1.0.0",
)
// Add tool
tool := mcp.NewTool("current time",
mcp.WithDescription("Get current time with timezone, Asia/Shanghai is default"),
mcp.WithString("timezone",
mcp.Required(),
mcp.Description("current time timezone"),
),
)
// Add tool handler
s.AddTool(tool, currentTimeHandler)
// Start the stdio server
if err := server.ServeStdio(s); err != nil {
fmt.Printf("Server error: %v\n", err)
}
}
//func currentTimeHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
// timezone, ok := request.Params.Arguments["timezone"].(string)
// if !ok {
// return mcp.NewToolResultError("timezone must be a string"), nil
// }
//
// loc, err := time.LoadLocation(timezone)
// if err != nil {
// return mcp.NewToolResultError(fmt.Sprintf("parse timezone with error: %v", err)), nil
// }
// return mcp.NewToolResultText(fmt.Sprintf(`current time is %s`, time.Now().In(loc))), nil
//}
func currentTimeHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
// 先断言为 map[string]any
args, ok := request.Params.Arguments.(map[string]any)
if !ok {
return mcp.NewToolResultError("invalid arguments type, must be object"), nil
}
// 从 map 中取 "timezone"
timezone, ok := args["timezone"].(string)
if !ok {
return mcp.NewToolResultError("timezone must be a string"), nil
}
// 加载时区
loc, err := time.LoadLocation(timezone)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("parse timezone with error: %v", err)), nil
}
// 返回结果
return mcp.NewToolResultText(fmt.Sprintf("current time is %s", time.Now().In(loc).Format("2006-01-02 15:04:05"))), nil
}
命令生成:
win:go build -o current-time-tool.exe .\current_time.go mac:go build -o mcp_tool mcp_tool.go
阿里云百炼平台获取大模型 api key
https://bailian.console.aliyun.com/#/home
vscode插件市场安装cline
配置 千问大模型 API Provider 选择 OPENAI Compatiable Base URL 设置为 https://dashscope.aliyuncs.com/compatible-mode/v1 API Key 设置为 从阿里云百炼平台获取的大模型 api key Model ID 设置为 qwen-max-latest
MCP Servers配置 current time tool
{ "mcpServers": { "current-time-tool": { "command": "E:\\GolangProjects\\src\\mcp-learning\\current_time\\current-time-tool.exe", "args": [], "env": {} } } }
Auto-approve 选择 Use MCP Servers
输入 “上海时间现在是多少”
输出之后,点击 Approve, 可以发现已经使用了 current-time-tool