package mainimport ("context""errors""fmt""io""log""net""net/http""github.com/mark3labs/mcp-go/mcp""github.com/mark3labs/mcp-go/server")func main() {// Create MCP servers := server.NewMCPServer("ip-mcp","1.0.0",)// Add tooltool := mcp.NewTool("ip_query",mcp.WithDescription("query geo location of an IP address"),mcp.WithString("ip",mcp.Required(),mcp.Description("IP address to query"),),)// Add tool handlers.AddTool(tool, ipQueryHandler)// Start the stdio serverif err := server.ServeStdio(s); err != nil {fmt.Printf("Server error: %v\n", err)}}func ipQueryHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {ip, ok := request.Params.Arguments["ip"].(string)if !ok {return nil, errors.New("ip must be a string")}parsedIP := net.ParseIP(ip)if parsedIP == nil {log.Printf("invalid IP address: %s", ip)return nil, errors.New("invalid IP address")}resp, err := http.Get("https://ip.rpcx.io/api/ip?ip=" + ip)if err != nil {log.Printf("Error fetching IP information: %v", err)return nil, fmt.Errorf("Error fetching IP information: %v", err)}defer resp.Body.Close()data, err := io.ReadAll(resp.Body)if err != nil {log.Printf("Error reading response body: %v", err)return nil, fmt.Errorf("Error reading response body: %v", err)}return mcp.NewToolResultText(string(data)), nil}
package mainimport ("context""log""github.com/mark3labs/mcp-go/client""github.com/tmc/langchaingo/agents""github.com/tmc/langchaingo/chains""github.com/tmc/langchaingo/llms/openai"langchaingo_mcp_adapter "github.com/i2y/langchaingo-mcp-adapter")func main() {// Create an MCP client using stdiomcpClient, err := client.NewStdioMCPClient(// Path to an MCP server"./ip-mcp",nil, // Additional environment variables if needed)if err != nil {log.Fatalf("Failed to create MCP client: %v", err)}defer mcpClient.Close()// Create the adapteradapter, err := langchaingo_mcp_adapter.New(mcpClient)if err != nil {log.Fatalf("Failed to create adapter: %v", err)}// Get all tools from MCP servermcpTools, err := adapter.Tools()if err != nil {log.Fatalf("Failed to get tools: %v", err)}ctx := context.Background()llm, err := openai.New(openai.WithBaseURL("http://127.0.0.1:11434/v1/"),openai.WithToken("ollama"),openai.WithModel("deepseek-r1:1.5b"),)if err != nil {log.Fatalf("Create AI client: %v", err)}// Create a agent with the toolsagent := agents.NewOneShotAgent(llm,mcpTools,agents.WithMaxIterations(3),)executor := agents.NewExecutor(agent)// Use the agentquestion := "Can you help me query geo location of an IP address ip: 8.8.8.8 ?"result, err := chains.Run(ctx,executor,question,)if err != nil {log.Fatalf("Agent execution error: %v", err)}log.Printf("Agent result: %s", result)}
% go run ./langchain/go/exp17/main.go2025/04/12 13:32:43 Agent execution error: unmarshal input: invalid character 'O' after top-level value
{"ip": "8.8.8.8"}Observation::
{"ip": "8.8.8.8"}


文章转载自golang算法架构leetcode技术php,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




