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

MCP Gin

MCP Server

MCP-Gin是一个Go库,将Gin Web应用程序转换为Model Context Protocol (MCP)服务器,使AI工具能够无缝与API交互。

工具数

0

提示词数

0

GitHub Stars

0

资源数

0
API转换GoClineGo语言Cline

安装说明

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

作者 / 组织

landmaster135

提供方

landmaster135

最后核验

2026/5/17 20:19

快速接入

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

详细介绍

MCP杜松子酒

Go Coverage License

MCP杜松子酒 是一个Go库,可以转换您的 金酒 web应用程序进入 模型上下文协议(MCP) 服务器,使AI工具能够与您的API无缝交互。

特性

  • 🚀 自动路线转换:将现有的Gin HTTP路由自动转换为MCP工具
  • 🔧 MCP专用工具:创建不需要HTTP端点直接执行的工具
  • 📋 模式自动生成:使用反射从Go结构生成JSON模式
  • 🎯 灵活的配置:筛选工具、设置基本URL和自定义行为
  • 🔒 环境变量支持:通过环境变量进行安全令牌处理
  • 📖 丰富的示例:包括完整的实施示例

安装

go get github.com/landmaster135/mcp-gin

快速开始

基本HTTP路由转换

package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
    server "github.com/landmaster135/mcp-gin"
)

type Product struct {
    ID    int     `json:"id" jsonschema:"readOnly"`
    Name  string  `json:"name" jsonschema:"required,description=Product name"`
    Price float64 `json:"price" jsonschema:"required,minimum=0,description=Price in USD"`
}

func main() {
    r := gin.Default()
    
    // Regular Gin routes
    r.GET("/products", listProducts)
    r.POST("/products", createProduct)
    
    // Initialize MCP server
    mcp := server.New(r, &server.Config{
        Name:        "Product API",
        Description: "API for managing products",
        BaseURL:     "http://localhost:8080",
    })
    
    // Register schemas for automatic conversion
    mcp.RegisterSchema("GET", "/products", nil, nil)
    mcp.RegisterSchema("POST", "/products", nil, Product{})
    
    // Mount MCP endpoint
    mcp.Mount("/mcp")
    
    r.Run(":8080")
}

func listProducts(c *gin.Context) {
    // Your existing handler logic
    c.JSON(http.StatusOK, []Product{})
}

func createProduct(c *gin.Context) {
    // Your existing handler logic
    c.JSON(http.StatusCreated, Product{})
}

MCP专用工具(高级)

创建无需HTTP端点即可直接执行的工具:

type CalculateRequest struct {
    A int `json:"a" jsonschema:"required,description=First number"`
    B int `json:"b" jsonschema:"required,description=Second number"`
}

func main() {
    r := gin.Default()
    mcp := server.New(r, &server.Config{
        Name: "Calculator API",
    })
    
    // Register MCP-only tool
    mcp.RegisterMCPTool(
        "calculate",
        "Perform arithmetic calculations",
        CalculateRequest{},
        func(params map[string]any) (any, error) {
            a := int(params["a"].(float64))
            b := int(params["b"].(float64))
            return map[string]int{"result": a + b}, nil
        },
    )
    
    mcp.Mount("/mcp")
    r.Run(":8080")
}

环境变量集成

对于安全的令牌处理:

type SecureRequest struct {
    Data string `json:"data" jsonschema:"required,description=Data to process"`
}

func secureHandler(params map[string]any) (any, error) {
    // Get token from environment variable
    token := os.Getenv("API_TOKEN")
    if token == "" {
        return nil, fmt.Errorf("API_TOKEN environment variable not set")
    }
    
    // Process with token
    data := params["data"].(string)
    return map[string]string{"processed": data}, nil
}

func main() {
    r := gin.Default()
    mcp := server.New(r, &server.Config{Name: "Secure API"})
    
    mcp.RegisterMCPTool("secure-process", "Process data securely", 
        SecureRequest{}, secureHandler)
    
    mcp.Mount("/mcp")
    r.Run(":8080")
}

配置

服务器配置

config := &server.Config{
    Name:              "My API",
    Description:       "Description of my API",
    BaseURL:           "http://localhost:8080",
    IncludeOperations: []string{"GET_products", "POST_products"}, // Only include these
    ExcludeOperations: []string{"DELETE_products"},              // Exclude these
}

架构注册

使用 jsonschema 用于生成富模式的标签:

type User struct {
    ID       int    `json:"id" jsonschema:"readOnly"`
    Name     string `json:"name" jsonschema:"required,description=User's full name"`
    Email    string `json:"email" jsonschema:"required,format=email,description=Email address"`
    Age      int    `json:"age" jsonschema:"minimum=0,maximum=150,description=Age in years"`
    IsActive bool   `json:"is_active" jsonschema:"required,description=Account status"`
}

// Register for automatic schema generation
mcp.RegisterSchema("POST", "/users", nil, User{})

MCP客户端连接

与Cline(VS代码扩展)一起使用

添加到MCP设置中:

{
  "mcpServers": {
    "my-gin-api": {
      "command": "go",
      "args": ["run", "main.go"],
      "cwd": "/path/to/your/project",
      "env": {
        "API_TOKEN": "your-secret-token"
      }
    }
  }
}

远程连接

如果您的服务器已在运行:

{
  "mcpServers": {
    "my-gin-api": {
      "command": "npx",
      "args": ["mcp-remote", "http://localhost:8080/mcp"]
    }
  }
}

api参考

核心类型

GinMCP

管理MCP功能的主服务器实例。

type GinMCP struct {
    // Internal fields
}

// Create new instance
func New(engine *gin.Engine, config *Config) *GinMCP

// Register HTTP route schema
func (m *GinMCP) RegisterSchema(method, path string, queryType, bodyType any)

// Register MCP-only tool
func (m *GinMCP) RegisterMCPTool(name, description string, schema any, 
    handler func(map[string]any) (any, error))

// Mount MCP endpoint
func (m *GinMCP) Mount(mountPath string)

Config

MCP服务器的配置选项。

type Config struct {
    Name              string   // Server name
    Description       string   // Server description
    BaseURL           string   // Base URL for HTTP requests
    IncludeOperations []string // Only include these operations
    ExcludeOperations []string // Exclude these operations
}

MCPTool

表示仅MCP工具。

type MCPTool struct {
    Name        string
    Description string
    Schema      any
    Handler     func(map[string]any) (any, error)
}

架构标签

使用这些 jsonschema 用于生成富模式的标签:

  • required -根据需要标记字段
  • description=text -添加字段描述
  • minimum=n -设置数字的最小值
  • maximum=n -设置数字的最大值
  • format=email -设置字符串格式
  • readOnly -将字段标记为只读
  • enum=val1,enum=val2 -定义允许的值

例子

完整的REST API示例

examples/simple/main.go 完整的实施方式包括:

  • 产品CRUD操作
  • 搜索和过滤
  • 分页和排序
  • 全面的模式定义
  • MCP集成

运行示例

cd examples/simple
go run main.go

服务器将于启动 http://localhost:8080 MCP端点位于 /mcp.

高级用法

自定义工具筛选

config := &server.Config{
    Name: "Filtered API",
    IncludeOperations: []string{
        "GET_products",
        "POST_products",
    },
}

复杂模式类型

type SearchParams struct {
    Query    string   `json:"query" jsonschema:"description=Search query"`
    Tags     []string `json:"tags" jsonschema:"description=Filter by tags"`
    MinPrice float64  `json:"min_price" jsonschema:"minimum=0,description=Minimum price"`
    MaxPrice float64  `json:"max_price" jsonschema:"minimum=0,description=Maximum price"`
    Page     int      `json:"page" jsonschema:"minimum=1,default=1,description=Page number"`
    Limit    int      `json:"limit" jsonschema:"minimum=1,maximum=100,default=10,description=Items per page"`
}

MCP工具中的错误处理

func myToolHandler(params map[string]any) (any, error) {
    value, ok := params["required_field"].(string)
    if !ok {
        return nil, fmt.Errorf("required_field must be a string")
    }
    
    if value == "" {
        return nil, fmt.Errorf("required_field cannot be empty")
    }
    
    // Process and return result
    return map[string]string{"result": value}, nil
}

故障排除

常见问题

  1. 工具未出现:确保 RegisterSchema 被调用之前 Mount
  2. 架构生成失败:检查您的结构是否使用导出的字段
  3. MCP连接失败:验证服务器是否正在运行以及端点是否可访问
  4. 环境变量不起作用:确保在MCP客户端配置中设置变量

调试模式

启用Gin调试模式以进行详细日志记录:

gin.SetMode(gin.DebugMode)

日志记录

图书馆使用 成就 用于日志记录。当Gin处于调试模式时,会自动记录调试信息。

贡献

  1. 分叉存储库
  2. 创建功能分支(git checkout -b feature/amazing-feature)
  3. 提交您的更改(git commit -m 'Add some amazing feature')
  4. 推到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

运行测试

go test ./...

测试覆盖率

go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

许可证

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

致谢

相关项目

目录标签

目录标签

API转换GoClineGo语言本地部署MCP协议Gin框架AI集成

支持客户端

Cline

接入字段

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

未说明

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

token

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

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

0

权限和风险

未说明token部署方式未说明

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

安装前确认

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

仍需确认:installCommand

来源信息

继续浏览同类 MCP