微信扫码
添加专属顾问
我要投稿
快速掌握MCP协议,用Go语言构建服务器。 核心内容: 1. MCP协议简介及其在LLM通信中的作用 2. MCP协议架构的详细解析,包括Host、MCP Server等组件 3. 使用Go语言构建MCP Server的实战指南
MCP 协议的架构包含多个关键组件:Host(宿主程序)、MCP Client(MCP 客户端)、MCP Server(MCP 服务器)、Local Data Source(本地数据源)和 Remote Service(远程服务)。对于普通用户而言,Host 是主要关注点;而开发者则可能更关注 MCP Server。
Host 通常是与用户直接交互的桌面应用程序,例如Claude 客户端、Chatbox、Cline 等。这些应用程序内置了 MCP Client,能够通过手动配置或 Host 提供的市场安装可用的 MCP Server。
内置的 MCP Client 可以与 MCP Server 建立连接,用于后续的 RPC 通信,协议为 JSON RPC。
MCP Server 主要通过 MCP 协议暴露其功能,供 Host 调用。其功能包括提示词模板构建和工具链方法调用等。MCP Server 可以提供三种主要类型的功能:
资源(Resources):可以被客户端读取的类文件数据,如 API 响应或文件内容。
工具(Tools):可以被 LLM 调用的函数,需要用户批准。
提示(Prompts):预先编写的模板,帮助用户完成特定任务。
MCP Server 是 MCP 架构中的关键组件,它通过标准化的模型上下文协议为 AI 应用提供丰富的上下文信息和操作能力,从而增强 LLM 的实用性和灵活性
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
}
currentTimeHandler 返回对应时区的当前时间。
server.ServeStdio 表示通过标准 I/O 进行 PRC 通信。
通过 go build 生成一个叫做 mcp-go-server 的可执行程序,后面手动配置会用到。
告诉我北京时间
总结
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2024-08-13
2024-06-13
2024-09-23
2024-08-21
2024-07-31
2024-05-28
2024-08-04
2024-04-26
2024-07-09
2024-09-17
2025-03-12
2025-03-12
2025-03-10
2025-03-10
2025-03-10
2025-03-10
2025-03-08
2025-03-08