客户端

MCP 客户端连接到服务器以访问工具、资源和提示。MCP-Go 为所有支持的传输方式提供客户端实现,使您能够轻松地将 MCP 功能集成到应用程序中。

客户端分为以下几类:

STDIO Client

Best for:

  • 命令行应用程序

  • 桌面软件集成

  • 本地开发和测试

  • 单服务器连接

// Create STDIO client
client, err := client.NewStdioMCPClient("server-command", "arg1", "arg2")

StreamableHTTP Client

Best for:

  • Web 应用程序

  • 微服务架构

  • 负载均衡部署

  • 类似 REST 的交互

// Create StreamableHTTP client
client := client.NewStreamableHttpClient("http://localhost:8080/mcp")

func createStreamableHTTPClient() client.Client {
    // Basic StreamableHTTP client
	httpTransport, err := transport.NewStreamableHTTP(server.URL,
		// Set timeout
		transport.WithHTTPTimeout(30*time.Second),
		// Set custom headers
		transport.WithHTTPHeaders(map[string]string{
			"X-Custom-Header": "custom-value",
			"Y-Another-Header": "another-value",
		}),
		// With custom HTTP client
		transport.WithHTTPBasicClient(&http.Client{}),
	)
    if err != nil {
        log.Fatalf("Failed to create StreamableHTTP transport: %v", err)
    }
    c := client.NewClient(httpTransport)
    return c
}

客户端生命周期

客户端的生命周期大致可以分为:

  1. Creation - Instantiate the client 创建 - 实例化客户端

  2. Initialization - Establish connection and exchange capabilities 初始化 - 建立连接并交换能力

  3. Operation - Use tools, resources, and prompts 操作 - 使用工具、资源和提示

  4. Cleanup - Close connections and free resources 清理 - 关闭连接并释放资源

初始化建立MCP连接并交换功能:

优雅关闭

最后更新于