Token导航 LogoToken导航TokenDH.com
Gin MCP logo
开发工具HTTP官方级别未说明来源级核验

Gin MCP

MCP Server

Enable MCP features for any Gin API with a line of code

工具数

0

提示词数

0

GitHub Stars

77

资源数

0
GoClaude开发工具Claude DesktopClaudeCursor

安装说明

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

作者 / 组织

ckanthony

提供方

ckanthony

最后核验

2026/5/18 04:04

快速接入

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

详细介绍

Gin-MCP:零配置Gin-MCP桥

![Go Reference](https://pkg.go.dev/github.com/ckanthony/gin-mcp) ![CI](https://github.com/ckanthony/gin-mcp/actions/workflows/ci.yml) ![codecov](https://codecov.io/gh/ckanthony/gin-mcp) ![](https://badge.mcpx.dev?type=dev "MCP Dev")

![Trust Score](https://archestra.ai/mcp-catalog/ckanthony__gin-mcp)

Enable MCP features for any Gin API with a line of code.

Gin-MCP is an opinionated, zero-configuration library that automatically exposes your existing Gin endpoints as Model Context Protocol (MCP) tools, making them instantly usable by MCP-compatible clients like Cursor, Claude Desktop, Continue, Zed, and other MCP-enabled tools.

Our philosophy is simple: minimal setup, maximum productivity. Just plug Gin-MCP into your Gin application, and it handles the rest.

为什么选择Gin MCP?

  • 轻松集成: 将您的Gin API连接到MCP客户,而无需编写冗长的样板文件代码。
  • 零配置(默认): 立即开始。Gin MCP自动发现路由并推断模式。
  • 开发人员生产力: 花更少的时间配置工具,花更多的时间构建功能。
  • 灵活性: 虽然默认配置为零,但需要时可以自定义模式和端点公开。
  • 现有API: 使用您现有的Ginneneneba API-无需更改任何代码。

演示

gin-mcp-example

特性

  • 自动发现: 智能查找所有已注册的杜松子酒路线。
  • 模式推断: 根据路由参数和请求/响应类型自动生成MCP工具模式(如果可能)。
  • 直接杜松子酒整合: 将MCP服务器直接装载到现有的 gin.Engine.
  • 参数保存: 在生成的MCP工具中准确反映您的Gin路由参数(路径、查询)。
  • 动态BaseURL解析: 支持具有每个用户/部署端点的代理环境(Quicknode、RAGFlow)。
  • 可定制的模式: 使用手动注册特定路由的模式 RegisterSchema 用于细粒度控制。
  • 选择性曝光: 使用操作ID或标记筛选公开的端点。
  • 灵活部署: 将MCP服务器安装在同一Gin应用程序中或单独部署。
  • 可流式HTTP传输: 选择MCP规范2025-03-26,用于无状态、负载均衡器友好的部署,不需要会话关联。
  • 授权标头转发: 自动转发客户端的 Authorization 每个内部工具执行调用的头部,使MCP能够访问受JWT保护的API。

安装

go get github.com/ckanthony/gin-mcp

基本用法:即时MCP服务器

用最少的代码让您的MCP服务器在几分钟内运行:

package main

import (
	"net/http"

	server "github.com/ckanthony/gin-mcp/"
	"github.com/gin-gonic/gin"
)

func main() {
	// 1. Create your Gin engine
	r := gin.Default()

	// 2. Define your API routes (Gin-MCP will discover these)
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "pong"})
	})

	r.GET("/users/:id", func(c *gin.Context) {
		// Example handler...
		userID := c.Param("id")
		c.JSON(http.StatusOK, gin.H{"user_id": userID, "status": "fetched"})
	})

	// 3. Create and configure the MCP server
	//    Provide essential details for the MCP client.
	mcp := server.New(r, &server.Config{
		Name:        "My Simple API",
		Description: "An example API automatically exposed via MCP.",
		// BaseURL is crucial! It tells MCP clients where to send requests.
		BaseURL: "http://localhost:8080",
	})

	// 4. Mount the MCP server endpoint
	mcp.Mount("/mcp") // MCP clients will connect here

	// 5. Run your Gin server
	r.Run(":8080") // Gin server runs as usual
}

就是这样!您的MCP工具现在可以在 http://localhost:8080/mcp.Gin MCP自动创建了以下工具 /ping/users/:id.

关于 BaseURL:始终提供明确的 BaseURL当客户机执行工具时,这个消息告诉MCP服务器转发API请求的正确地址。没有它,自动检测可能会失败,特别是在具有代理或不同内部/外部URL的环境中。

高级用法

虽然Gin MCP努力实现零配置,但您可以自定义其行为。

用注释注释处理程序

Gin MCP自动从处理程序函数注释中提取元数据,以生成丰富的工具描述。使用这些注释使您的MCP工具更易于发现和使用:

// listProducts retrieves a paginated list of products
// @summary List all products
// @description Returns a paginated list of products with optional filtering by price, tags, and availability
// @param page Page number for pagination (default: 1)
// @param limit Number of items per page (default: 10, max: 100)
// @param minPrice Minimum price filter
// @param tag Filter products by tag
// @tags public catalog
func listProducts(c *gin.Context) {
    // Handler implementation...
}

支持的注释:

  • @summary -简短的一行描述成为工具的主要描述
  • @description -摘要后附有额外的详细解释
  • @param -将描述性文本附加到生成的架构中的特定输入参数
  • @tags -用于筛选工具的空格或逗号分隔标签(请参阅下面的“筛选暴露的端点”)
  • @operationId -工具的自定义操作ID(覆盖默认值 METHOD_path 命名方案)。在所有路线中必须是唯一的;重复项将被跳过(第一个声明获胜),并记录警告。

所有注释都是可选的,但使用它们可以使您的API工具在像Claude Desktop和Cursor这样的MCP客户端中更加友好。

自定义操作ID:

默认情况下,Gin MCP使用以下格式生成操作ID METHOD_path (例如。, GET_users_id).对于路径很长的路线,您可以使用 @operationId 要指定一个更短、更易于管理的名称:

// getUserProfile retrieves a user's profile with extended metadata
// @summary Get user profile
// @operationId getUserProfile
// @param id User identifier
func getUserProfile(c *gin.Context) {
    // Instead of the default "GET_api_v2_users_userId_profile_extended"
    // this tool will be named "getUserProfile"
}

重要提示: 操作ID必须是唯一的。如果两个处理程序使用相同的 @operationId,将完全跳过重复项(第一个声明获胜),并始终记录警告。这确保了工具列表和操作图之间的一致性。

细粒度模式控制 RegisterSchema

有时,自动模式推理是不够的。 RegisterSchema 允许您显式定义查询参数的模式或特定路由的请求体。这在以下情况下很有用:

  • 您使用复杂结构作为查询参数(ShouldBindQuery).
  • 您希望为请求体定义不同的模式(例如,用于POST/PUT)。
  • 自动推理不会捕获您希望在MCP工具定义中公开的特定约束(枚举、描述等)。
package main

import (
	// ... other imports
	"github.com/ckanthony/gin-mcp/pkg/server"
	"github.com/gin-gonic/gin"
)

// Example struct for query parameters
type ListProductsParams struct {
	Page  int    `form:"page,default=1" json:"page,omitempty" jsonschema:"description=Page number,minimum=1"`
	Limit int    `form:"limit,default=10" json:"limit,omitempty" jsonschema:"description=Items per page,maximum=100"`
	Tag   string `form:"tag" json:"tag,omitempty" jsonschema:"description=Filter by tag"`
}

// Example struct for POST request body
type CreateProductRequest struct {
	Name  string  `json:"name" jsonschema:"required,description=Product name"`
	Price float64 `json:"price" jsonschema:"required,minimum=0,description=Product price"`
}

func main() {
	r := gin.Default()

	// --- Define Routes ---
	r.GET("/products", func(c *gin.Context) { /* ... handler ... */ })
	r.POST("/products", func(c *gin.Context) { /* ... handler ... */ })
	r.PUT("/products/:id", func(c *gin.Context) { /* ... handler ... */ })

	// --- Configure MCP Server ---
	mcp := server.New(r, &server.Config{
		Name:        "Product API",
		Description: "API for managing products.",
		BaseURL:     "http://localhost:8080",
	})

	// --- Register Schemas ---
	// Register ListProductsParams as the query schema for GET /products
	mcp.RegisterSchema("GET", "/products", ListProductsParams{}, nil)

	// Register CreateProductRequest as the request body schema for POST /products
	mcp.RegisterSchema("POST", "/products", nil, CreateProductRequest{})

	// You can register schemas for other methods/routes as needed
	// e.g., mcp.RegisterSchema("PUT", "/products/:id", nil, UpdateProductRequest{})

	mcp.Mount("/mcp")
	r.Run(":8080")
}

说明:

  • mcp.RegisterSchema(method, path, querySchema, bodySchema)
  • method:HTTP方法(例如“GET”、“POST”)。
  • path:金路线路径(例如,“/products”、“/products/:id”)。
  • querySchema:用于查询参数的结构的实例(或 nil 如果没有)。Gin MCP使用反射和 jsonschema 标签来生成模式。
  • bodySchema:用于请求正文的结构体的实例(或 nil 如果没有)。

过滤暴露的端点

使用操作ID或标签控制哪些Gin端点成为MCP工具。标签来自 @tags 在处理程序注释中添加注释(请参阅上面的“注释处理程序”)。

基于标签的过滤

标签在处理函数注释中使用 @tags 注释。您可以指定用空格、逗号或两者分隔的标签:

// listUsers handles user listing
// @summary List all users
// @tags public users
func listUsers(c *gin.Context) {
    // Implementation...
}

// deleteUser handles user deletion
// @summary Delete a user
// @tags admin, internal
func deleteUser(c *gin.Context) {
    // Implementation...
}

筛选配置

// Only include specific operations by their Operation ID
mcp := server.New(r, &server.Config{
    // ... other config ...
    IncludeOperations: []string{"GET_users", "POST_users"},
})

// Exclude specific operations
mcp := server.New(r, &server.Config{
    // ... other config ...
    ExcludeOperations: []string{"DELETE_users_id"}, // Don't expose delete tool
})

// Only include operations tagged with "public" or "users"
// A tool is included if it has ANY of the specified tags
mcp := server.New(r, &server.Config{
    // ... other config ...
    IncludeTags: []string{"public", "users"},
})

// Exclude operations tagged with "admin" or "internal"
// A tool is excluded if it has ANY of the specified tags
mcp := server.New(r, &server.Config{
    // ... other config ...
    ExcludeTags: []string{"admin", "internal"},
})

筛选规则:

  • 您只能使用 夹杂物过滤器(IncludeOperations IncludeTags).

- 如果两者都被设置, IncludeOperations 优先,并记录警告。

  • 您只能使用 排除过滤器(ExcludeOperations ExcludeTags).

- 如果两者都被设置, ExcludeOperations 优先,并记录警告。

  • 将包含过滤器与排除过滤器结合使用(例如,包含标签“public”,但排除操作“legacyPublicOp”)。
  • 排斥总是赢:如果一个工具同时匹配包含和排除筛选器,则将被排除。
  • 标签匹配:如果工具有以下情况,则包含/排除该工具 任何 指定标签的OR逻辑。

示例:

// Include all "public" endpoints but exclude those also tagged "internal"
mcp := server.New(r, &server.Config{
    IncludeTags: []string{"public"},
    ExcludeTags: []string{"internal"},
})

// Include specific operations but exclude admin endpoints
mcp := server.New(r, &server.Config{
    IncludeOperations: []string{"GET_users", "GET_products"},
    ExcludeTags:       []string{"admin"},  // This will be ignored (precedence rule)
})

自定义模式描述(不太常见)

对于如何在生成的工具中描述响应模式的高级控制(通常不需要):

mcp := server.New(r, &server.Config{
    // ... other config ...
    DescribeAllResponses:    true, // Include *all* possible response schemas (e.g., 200, 404) in tool descriptions
    DescribeFullResponseSchema: true, // Include the full JSON schema object instead of just a reference
})

示例

examples 用于展示各种功能的完整、可运行示例的目录:

基本使用示例

代理场景的动态BaseURL

对于每个用户/部署都有不同端点的环境(如Quicknode或RAGFlow),您可以配置动态BaseURL解析:

// Quicknode example - resolves user-specific endpoints
mcp := server.New(r, &server.Config{
    Name: "Your API",
    Description: "API with dynamic Quicknode endpoints",
    // No static BaseURL needed!
})

resolver := server.NewQuicknodeResolver("http://localhost:8080")
mcp.SetExecuteToolFunc(func(operationID string, parameters map[string]interface{}) (interface{}, error) {
    return mcp.ExecuteToolWithResolver(operationID, parameters, resolver)
})

支持的环境变量:

  • Quicknode: QUICKNODE_USER_ENDPOINT, USER_ENDPOINT, HOST
  • RAGFlow 的: RAGFLOW_ENDPOINT, RAGFLOW_WORKFLOW_URL, RAGFLOW_BASE_URL + WORKFLOW_ID

这消除了在启动时对静态BaseURL配置的需要,非常适合多租户代理环境!

可流式HTTP传输(水平扩展)

默认情况下,Gin MCP使用 SSE运输 (MCP规范2024-11-05),它要求将持久GET连接路由到 同一吊舱 作为后续的POST请求。这迫使负载平衡器使用会话关联(粘性会话),这与水平自动缩放不兼容,也不受许多托管负载平衡器(如GCP、AWS ALB)的支持。

可流式HTTP传输 (MCP规范2025-03-26)解决了这个问题:每个POST都直接在HTTP正文中返回JSON-RPC响应。不需要事先进行GET连接或pod关联。

mcp := server.New(r, &server.Config{
    Name:          "My API",
    BaseURL:       "https://api.example.com",
    TransportType: server.TransportTypeStreamableHTTP,
})
mcp.Mount("/mcp")

MCP客户端与单个 POST /mcp --不需要事先GET。

源验证(DNS重新绑定保护)

MCP规范2025-03-26§安全,服务器应验证 Origin 头球使用 AllowedOrigins 要限制浏览器发起的请求,请执行以下操作:

mcp := server.New(r, &server.Config{
    Name:          "My API",
    BaseURL:       "https://api.example.com",
    TransportType: server.TransportTypeStreamableHTTP,
    // Only allow requests from this browser origin.
    // Omit (or leave nil) when authentication already prevents unauthorised access.
    AllowedOrigins: []string{"https://app.example.com"},
})
  • 请求: 随着Origin 标题不在列表中→ 403 Forbidden.
  • 请求: 没有Origin 标头(服务器到服务器: curl、Node.js等)→ 总是允许的。
  • 空/无 AllowedOrigins → 允许所有来源(需要Bearer令牌时适用)。

授权标头转发

当您的Gin端点受到JWT Bearer令牌的保护时,您可以转发客户端的 Authorization 每个内部工具执行HTTP调用的标头:

mcp := server.New(r, &server.Config{
    Name:               "My API",
    BaseURL:            "https://api.example.com",
    ForwardAuthHeaders: true,
})
mcp.Mount("/mcp")
  • SSE运输:在SSE连接时捕获一次标头,并将其重新用于该连接上的所有后续工具调用。
  • 可流式HTTP传输:每个POST请求都会捕获标头(每个调用都是独立的)。
  • 违约: false (禁用,用于向后兼容性)。

连接MCP客户端

一旦您的Gin应用程序与Gin MCP一起运行:

  1. 启动您的应用程序。
  2. 在您的MCP客户端中,提供您安装MCP服务器的URL(例如。, http://localhost:8080/mcp):

- SSE传输(默认):作为SSE端点连接(GET然后POST到同一路径)。 - 可流式HTTP传输:作为普通HTTP端点连接(仅限POST)。 - 光标:设置→ MCP → 添加服务器 - 克劳德桌面版:添加到MCP配置文件 - 继续:在VS代码设置中配置 - 泽德:添加到MCP设置

  1. 客户端将连接并自动发现可用的API工具。

贡献

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

目录标签

目录标签

GoClaude开发工具developer-toolsAPI桥接本地部署零配置Gin框架MCP协议开发者工具

支持客户端

Claude DesktopClaudeCursor

接入字段

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

HTTP

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

none

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

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

0

权限和风险

HTTPnone部署方式未说明

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

安装前确认

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

仍需确认:installCommand

来源信息

继续浏览同类 MCP