Home > Backend Development > Golang > Write tools for LLMs with go - mcp-golang

Write tools for LLMs with go - mcp-golang

Mary-Kate Olsen
Release: 2024-12-23 20:48:11
Original
217 people have browsed it

Write tools for LLMs with go - mcp-golang

We just open-sourced mcp-golang!

A few weeks ago, Anthropic released Model Context Protocol - a protocol to allow LLMs to use tools and interact with the world.

The base sdks written by Anthropic were for Typescript and python, so if you wanted to use go, you were out of luck.

With mcp-golang you can now write tool servers in just a few lines of code in go.

The server below allows an LLM to understand the weather in any location.

package main

import (
    "fmt"
    mcp_golang "github.com/metoro-io/mcp-golang"
    "github.com/metoro-io/mcp-golang/transport/stdio"
    "io"
    "net/http"
)

type WeatherArguments struct {
    Longitude float64 `json:"longitude" jsonschema:"required,description=The longitude of the location to get the weather for"`
    Latitude  float64 `json:"latitude" jsonschema:"required,description=The latitude of the location to get the weather for"`
}

// This is explained in the docs at https://mcpgolang.com/tools
func main() {
    done := make(chan struct{})
    server := mcp_golang.NewServer(stdio.NewStdioServerTransport())
    err := server.RegisterTool("get_weather", "Get the weather forecast for temperature, wind speed and relative humidity", func(arguments WeatherArguments) (*mcp_golang.ToolResponse, error) {
        url := fmt.Sprintf("https://api.open-meteo.com/v1/forecast?latitude=%f&longitude=%f&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m", arguments.Latitude, arguments.Longitude)
        resp, err := http.Get(url)
        if err != nil {
            return nil, err
        }
        defer resp.Body.Close()
        output, err := io.ReadAll(resp.Body)
        if err != nil {
            return nil, err
        }
        return mcp_golang.NewToolReponse(mcp_golang.NewTextContent(string(output))), nil
    })
    err = server.Serve()
    if err != nil {
        panic(err)
    }
    <-done
}
Copy after login

Check out a demo at https://youtu.be/kffLqCgvvdE!

Happy coding!

The above is the detailed content of Write tools for LLMs with go - mcp-golang. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template