Cover image

用几行GO代码编写模型上下文协议服务器。 Docs Athttps://mcpgolang.com

3 years

Works with Finder

13

Github Watches

66

Github Forks

690

Github Stars

Statusphere logo

GitHub stars GitHub forks GitHub issues GitHub pull requests GitHub license GitHub contributors GitHub last commit GoDoc Go Report Card Tests

mcp-golang

mcp-golang is an unofficial implementation of the Model Context Protocol in Go.

Write MCP servers and clients in golang with a few lines of code.

Docs at https://mcpgolang.com

Highlights

  • 🛡️Type safety - Define your tool arguments as native go structs, have mcp-golang handle the rest. Automatic schema generation, deserialization, error handling etc.
  • 🚛 Custom transports - Use the built-in transports (stdio for full feature support, HTTP for stateless communication) or write your own.
  • Low boilerplate - mcp-golang generates all the MCP endpoints for you apart from your tools, prompts and resources.
  • 🧩 Modular - The library is split into three components: transport, protocol and server/client. Use them all or take what you need.
  • 🔄 Bi-directional - Full support for both server and client implementations through stdio transport.

Example Usage

Install with go get github.com/metoro-io/mcp-golang

Server Example

package main

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

// Tool arguments are just structs, annotated with jsonschema tags
// More at https://mcpgolang.com/tools#schema-generation
type Content struct {
	Title       string  `json:"title" jsonschema:"required,description=The title to submit"`
	Description *string `json:"description" jsonschema:"description=The description to submit"`
}
type MyFunctionsArguments struct {
	Submitter string  `json:"submitter" jsonschema:"required,description=The name of the thing calling this tool (openai, google, claude, etc)"`
	Content   Content `json:"content" jsonschema:"required,description=The content of the message"`
}

func main() {
	done := make(chan struct{})

	server := mcp_golang.NewServer(stdio.NewStdioServerTransport())
	err := server.RegisterTool("hello", "Say hello to a person", func(arguments MyFunctionsArguments) (*mcp_golang.ToolResponse, error) {
		return mcp_golang.NewToolResponse(mcp_golang.NewTextContent(fmt.Sprintf("Hello, %server!", arguments.Submitter))), nil
	})
	if err != nil {
		panic(err)
	}

	err = server.RegisterPrompt("promt_test", "This is a test prompt", func(arguments Content) (*mcp_golang.PromptResponse, error) {
		return mcp_golang.NewPromptResponse("description", mcp_golang.NewPromptMessage(mcp_golang.NewTextContent(fmt.Sprintf("Hello, %server!", arguments.Title)), mcp_golang.RoleUser)), nil
	})
	if err != nil {
		panic(err)
	}

	err = server.RegisterResource("test://resource", "resource_test", "This is a test resource", "application/json", func() (*mcp_golang.ResourceResponse, error) {
		return mcp_golang.NewResourceResponse(mcp_golang.NewTextEmbeddedResource("test://resource", "This is a test resource", "application/json")), nil
	})

	err = server.Serve()
	if err != nil {
		panic(err)
	}

	<-done
}

HTTP Server Example

You can also create an HTTP-based server using either the standard HTTP transport or Gin framework:

// Standard HTTP
transport := http.NewHTTPTransport("/mcp")
transport.WithAddr(":8080")
server := mcp_golang.NewServer(transport)

// Or with Gin framework
transport := http.NewGinTransport()
router := gin.Default()
router.POST("/mcp", transport.Handler())
server := mcp_golang.NewServer(transport)

Note: HTTP transports are stateless and don't support bidirectional features like notifications. Use stdio transport if you need those features.

Client Example

Checkout the examples/client directory for a more complete example.

package main

import (
    "context"
    "log"
    mcp "github.com/metoro-io/mcp-golang"
    "github.com/metoro-io/mcp-golang/transport/stdio"
)

// Define type-safe arguments
type CalculateArgs struct {
    Operation string `json:"operation"`
    A         int    `json:"a"`
    B         int    `json:"b"`
}

func main() {
   cmd := exec.Command("go", "run", "./server/main.go")
   stdin, err := cmd.StdinPipe()
   if err != nil {
    log.Fatalf("Failed to get stdin pipe: %v", err)
   }
   stdout, err := cmd.StdoutPipe()
   if err != nil {
    log.Fatalf("Failed to get stdout pipe: %v", err)
   }

   if err := cmd.Start(); err != nil {
    log.Fatalf("Failed to start server: %v", err)
   }
   defer cmd.Process.Kill()
    // Create and initialize client
    transport := stdio.NewStdioServerTransportWithIO(stdout, stdin)
    client := mcp.NewClient(transport)
    
    if _, err := client.Initialize(context.Background()); err != nil {
        log.Fatalf("Failed to initialize: %v", err)
    }

    // Call a tool with typed arguments
    args := CalculateArgs{
        Operation: "add",
        A:         10,
        B:         5,
    }
    
    response, err := client.CallTool(context.Background(), "calculate", args)
    if err != nil {
        log.Fatalf("Failed to call tool: %v", err)
    }
    
    if response != nil && len(response.Content) > 0 {
        log.Printf("Result: %s", response.Content[0].TextContent.Text)
    }
}

Using with Claude Desktop

Create a file in ~/Library/Application Support/Claude/claude_desktop_config.json with the following contents:

{
"mcpServers": {
  "golang-mcp-server": {
      "command": "<your path to golang MCP server go executable>",
      "args": [],
      "env": {}
    }
  }
}

Contributions

Contributions are more than welcome! Please check out our contribution guidelines.

Discord

Got any suggestions, have a question on the api or usage? Ask on the discord server. A maintainer will be happy to help you out.

Examples

Some more extensive examples using the library found here:

  • Metoro - Query and interact with kubernetes environments monitored by Metoro

Open a PR to add your own projects!

Server Feature Implementation

Tools

  • Tool Calls
  • Native go structs as arguments
  • Programatically generated tool list endpoint
  • Change notifications
  • Pagination

Prompts

  • Prompt Calls
  • Programatically generated prompt list endpoint
  • Change notifications
  • Pagination

Resources

  • Resource Calls
  • Programatically generated resource list endpoint
  • Change notifications
  • Pagination

Transports

  • Stdio - Full support for all features including bidirectional communication
  • HTTP - Stateless transport for simple request-response scenarios (no notifications support)
  • Gin - HTTP transport with Gin framework integration (stateless, no notifications support)
  • SSE
  • Custom transport support
  • HTTPS with custom auth support - in progress. Not currently part of the spec but we'll be adding experimental support for it.

Client

  • Call tools
  • Call prompts
  • Call resources
  • List tools
  • List prompts
  • List resources

相关推荐

  • Elijah Ng Shi Yi
  • Advanced software engineer GPT that excels through nailing the basics.

  • Alexandru Strujac
  • Efficient thumbnail creator for YouTube videos

  • https://zenepic.net
  • Embark on a thrilling diplomatic quest across a galaxy on the brink of war. Navigate complex politics and alien cultures to forge peace and avert catastrophe in this immersive interstellar adventure.

  • Beria Joey
  • 你的职业规划师,不走弯路就问我。Sponsor:小红书“ ItsJoe就出行 ”

  • Benedikt Ess
  • FindetundanalysiertOnlineProdukteeinschlielichAmazonnachVolumenBewertungenundPreis

  • pontusab
  • 光标与风浪冲浪社区,查找规则和MCP

  • av
  • 毫不费力地使用一个命令运行LLM后端,API,前端和服务。

  • GeyserMC
  • 与Minecraft客户端/服务器通信的库。

  • 1Panel-dev
  • 🔥1Panel提供了直观的Web接口和MCP服务器,用于在Linux服务器上管理网站,文件,容器,数据库和LLMS。

  • awslabs
  • AWS MCP服务器 - 将AWS最佳实践直接带入您的开发工作流程的专门MCP服务器

  • WangRongsheng
  • 🧑‍🚀 llm 资料总结(数据处理、模型训练、模型部署、 o1 模型、mcp 、小语言模型、视觉语言模型)|摘要世界上最好的LLM资源。

  • appcypher
  • 很棒的MCP服务器 - 模型上下文协议服务器的策划列表

  • GLips
  • MCP服务器向像光标这样的AI编码代理提供FIGMA布局信息

  • idosal
  • 结束幻觉! GITMCP是任何GitHub项目的免费,开源的远程MCP服务器

  • Byaidu
  • PDF科学纸翻译带有保留格式的pdf -基于ai完整保留排版的pdf文档全文双语翻译

    Reviews

    1 (1)
    Avatar
    user_EK79jeA3
    2025-04-17

    I've been using mcp-golang by metoro-io and it has truly impressed me. It's a robust tool for Golang enthusiasts, offering great features and smooth performance. The GitHub repository is well-documented, making it easy to get started. Highly recommend checking it out!