Token导航 LogoToken导航TokenDH.com
Golang MCP Server SDK logo
AI代理未说明官方级别未说明来源级核验

Golang MCP Server SDK

MCP Server

一个用于构建MCP服务器的Golang SDK,支持多种传输协议和工具集成。

工具数

2

提示词数

0

GitHub Stars

5

资源数

0
服务器开发Go模型集成Session认证

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

FreePeak

提供方

FreePeak

最后核验

2026/5/17 20:21

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

Golang MCP服务器SDK

![License: MIT](https://opensource.org/licenses/MIT) ![Go Report Card](https://goreportcard.com/report/github.com/FreePeak/golang-mcp-server-sdk) ![Go Reference](https://pkg.go.dev/github.com/FreePeak/golang-mcp-server-sdk) ![Build Status](https://github.com/FreePeak/golang-mcp-server-sdk/actions/workflows/go.yml) ![Contributors](https://github.com/FreePeak/golang-mcp-server-sdk/graphs/contributors)

目录

- 服务器 - 工具 - 资源 - 鼓励

- 标准输入输出 - HTTP与SSE - 多协议 - 测试和调试

- 回声服务器 - 计算器服务器

概述

模型上下文协议允许应用程序以标准化的方式为LLM提供上下文,将提供上下文的关注点与实际的LLM交互分开。此Golang SDK实现了完整的MCP规范,使其易于:

  • 构建公开资源和工具的MCP服务器
  • 使用标准传输方式,如stdio和服务器发送事件(SSE)
  • 处理所有MCP协议消息和生命周期事件
  • 遵循Go最佳实践和干净架构原则
注: 此SDK始终会更新,以符合最新的MCP规范 spec.modelcontextprotocol.io/最新

安装

go get github.com/FreePeak/golang-mcp-server-sdk

快速启动

让我们创建一个简单的MCP服务器,它公开了一个echo工具:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/FreePeak/golang-mcp-server-sdk/pkg/server"
	"github.com/FreePeak/golang-mcp-server-sdk/pkg/tools"
)

func main() {
	// Create the server
	mcpServer := server.NewMCPServer("Echo Server Example", "1.0.0")

	// Create an echo tool
	echoTool := tools.NewTool("echo",
		tools.WithDescription("Echoes back the input message"),
		tools.WithString("message",
			tools.Description("The message to echo back"),
			tools.Required(),
		),
	)

	// Add the tool to the server with a handler
	ctx := context.Background()
	err := mcpServer.AddTool(ctx, echoTool, handleEcho)
	if err != nil {
		log.Fatalf("Error adding tool: %v", err)
	}

	// Start the server
	fmt.Println("Starting Echo Server...")
	fmt.Println("Send JSON-RPC messages via stdin to interact with the server.")
	
	// Serve over stdio
	if err := mcpServer.ServeStdio(); err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
}

// Echo tool handler
func handleEcho(ctx context.Context, request server.ToolCallRequest) (interface{}, error) {
	// Extract the message parameter
	message, ok := request.Parameters["message"].(string)
	if !ok {
		return nil, fmt.Errorf("missing or invalid 'message' parameter")
	}

	// Return the echo response in the format expected by the MCP protocol
	return map[string]interface{}{
		"content": []map[string]interface{}{
			{
				"type": "text",
				"text": message,
			},
		},
	}, nil
}

什么是MCP?

模型上下文协议(MCP) 是一种标准化协议,允许应用程序以安全有效的方式为LLM提供上下文。它将提供上下文和工具的关注点与实际的LLM交互分开。MCP服务器可以:

  • 通过以下方式公开数据 资源 (只读数据端点)
  • 通过以下方式提供功能 工具 (可执行功能)
  • 通过以下方式定义交互模式 鼓励 (可重复使用的模板)
  • 支持多种传输方式(stdio、HTTP/SSE)

核心概念

服务器

MCP服务器是MCP协议的核心接口。它处理连接管理、协议合规性和消息路由:

// Create a new MCP server
mcpServer := server.NewMCPServer("My App", "1.0.0")

工具

工具允许LLM通过您的服务器执行操作。与资源不同,工具被期望执行计算并具有副作用:

// Define a calculator tool
calculatorTool := tools.NewTool("calculator",
    tools.WithDescription("Performs basic arithmetic"),
    tools.WithString("operation",
        tools.Description("The operation to perform (add, subtract, multiply, divide)"),
        tools.Required(),
    ),
    tools.WithNumber("a", 
        tools.Description("First number"),
        tools.Required(),
    ),
    tools.WithNumber("b",
        tools.Description("Second number"),
        tools.Required(),
    ),
)

// Add tool to server with a handler
mcpServer.AddTool(ctx, calculatorTool, handleCalculator)

资源

资源是您向LLM公开数据的方式。它们类似于REST API中的GET端点-它们提供数据,但不应执行显著的计算或产生副作用:

// Create a resource (Currently using the internal API)
resource := &domain.Resource{
    URI:         "sample://hello-world",
    Name:        "Hello World Resource",
    Description: "A sample resource for demonstration purposes",
    MIMEType:    "text/plain",
}

// Note: Resource support is being updated in the public API

鼓励

提示是可重用的模板,可帮助LLM与您的服务器有效交互:

// Create a prompt (Currently using the internal API)
codeReviewPrompt := &domain.Prompt{
    Name:        "review-code",
    Description: "A prompt for code review",
    Template:    "Please review this code:\n\n{{.code}}",
    Parameters: []domain.PromptParameter{
        {
            Name:        "code",
            Description: "The code to review",
            Type:        "string",
            Required:    true,
        },
    },
}

// Note: Prompt support is being updated in the public API

运行服务器

Go中的MCP服务器可以根据您的用例连接到不同的传输方式:

标准输入输出

对于命令行工具和直接集成:

// Start a stdio server
if err := mcpServer.ServeStdio(); err != nil {
    fmt.Fprintf(os.Stderr, "Error: %v\n", err)
    os.Exit(1)
}

HTTP与SSE

对于web应用程序,您可以使用服务器发送事件(SSE)进行实时通信:

// Configure the HTTP address
mcpServer.SetAddress(":8080")

// Start an HTTP server with SSE support
if err := mcpServer.ServeHTTP(); err != nil {
    log.Fatalf("HTTP server error: %v", err)
}

// For graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := mcpServer.Shutdown(ctx); err != nil {
    log.Fatalf("Server shutdown error: %v", err)
}

多协议

您还可以同时运行多个协议服务器:

// Configure server for both HTTP and stdio
mcpServer := server.NewMCPServer("Multi-Protocol Server", "1.0.0")
mcpServer.SetAddress(":8080")
mcpServer.AddTool(ctx, echoTool, handleEcho)

// Start HTTP server in a goroutine
go func() {
    if err := mcpServer.ServeHTTP(); err != nil {
        log.Fatalf("HTTP server error: %v", err)
    }
}()

// Start stdio server in the main thread
if err := mcpServer.ServeStdio(); err != nil {
    log.Fatalf("Stdio server error: %v", err)
}

测试和调试

为了测试您的MCP服务器,您可以使用 MCP检查员 或者直接发送JSON-RPC消息:

# Test an echo tool with stdio
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"echo","parameters":{"message":"Hello, World!"}}}' | go run your_server.go

例子

看看 examples 完整示例服务器的目录:

回声服务器

一个简单的echo服务器示例可在 examples/echo_server.go:

# Run the example
go run examples/echo_server.go

计算器服务器

一个同时具有HTTP和stdio模式的更高级的计算器示例可在 examples/calculator/:

# Run in HTTP mode
go run examples/calculator/main.go --mode http

# Run in stdio mode
go run examples/calculator/main.go --mode stdio

封装结构

SDK的组织遵循干净的架构原则:

golang-mcp-server-sdk/
├── pkg/                    # Public API (exposed to users)
│   ├── builder/            # Public builder pattern for server construction
│   ├── server/             # Public server implementation
│   ├── tools/              # Utilities for creating MCP tools
│   └── types/              # Shared types and interfaces
├── internal/               # Private implementation details
├── examples/               # Example code snippets and use cases
└── cmd/                    # Example MCP server applications

pkg/ 该目录包含SDK用户应与之交互的所有公开API。

贡献

欢迎投稿!请随时提交拉取请求。

许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

📧 支持与联系

目录标签

目录标签

服务器开发Go模型集成Session认证GolangSDK本地部署MCP协议LLM集成

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

session

工具数量(toolCount,工具数)

2

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明session部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP