使用说明
mcpgen:将OpenAPI API无缝转换为AI代理工具
mcpgen 是一个命令行工具,可以根据您的OpenAPI规范无缝生成生产就绪的模型上下文协议(MCP)服务器样板,使您能够轻松地将现有的API作为AI代理的强大工具公开。
主要特点
- OpenAPI兼容性: 读取和处理YAML或JSON格式的OpenAPI规范,支持版本 3.0.
- 全面的MCP服务器生成: 生成设置MCP服务器所需的完整Go样板,包括服务器初始化、工具注册和处理程序框架。
- 准确的模式翻译: 自动将OpenAPI模式定义转换为必要的 JSON模式 用于工具输入(与MCP兼容),并生成基于详细标记的 响应模板(提示) 用于各种状态代码和内容类型,为AI模型提供丰富的上下文。
- 高级架构支持: 处理复杂的OpenAPI模式构造,包括:
- 数组和嵌套结构
- 类型工会和
oneOf/anyOf/allOf连接符 - 递归类型定义
- 验证约束(例如。,
minimum,maximum,maxLength,pattern)
- 多种内容类型处理: 正确处理和生成用于定义多种请求和响应内容类型的操作的模板。
- 生成代码质量: 使用嵌入式模式和提示生成结构良好、符合习惯的Go代码,利用常量实现清晰性和可维护性。
- 可选客户端和类型生成: 可以根据OpenAPI模式选择性地生成Go HTTP客户端和相应的Go类型,简化生成的MCP处理程序中的实现逻辑。
- 开发者友好: 提供清晰的处理程序函数框架,并指导在何处集成核心逻辑以连接到实际的后端API。
- 久经考验的基础: 代码生成逻辑得到了广泛测试的支持,确保了高可靠性(94%的覆盖率和200%的测试量证明了这一点)。
安装
go install github.com/lyeslabs/mcpgen/cmd/mcpgen@latest
默认情况下,二进制文件安装到 $HOME/go/bin (或 %USERPROFILE%\go\bin 在Windows上)。
确保此目录位于您的 PATH.
用法
mcpgen --input openapi.yaml --output generated-server
所需标志
-
--inputOpenAPI规范文件的路径(YAML或JSON)。 -
--output生成的MCP服务器样板的输出目录。
可选标志
-
--validation启用OpenAPI验证(默认值:false). -
--package生成的Go包的名称(默认值:mcpgen). -
--includes以逗号分隔的生成代码的其他包含项列表。使用httpclient,types生成HTTP客户端和类型。
示例
mcpgen --input api/openapi.yaml --output ./generated-server --validation --package myserver --includes=httpclient,types
运作原理
mcpgen 充当声明性OpenAPI规范和MCP服务器所需的编程Go代码之间的桥梁。它读取您的OpenAPI定义,并自动生成必要的样板,包括有效的AI代理交互所必需的结构化模式和提示。
让我们用OpenAPI中定义的中等复杂端点的示例来说明这一点:
# This is a snippet from your OpenAPI specification
/todos:
get:
tags:
- Todos
summary: List all todo items
description: Retrieves a list of todo items, optionally filtered by status.
operationId: listTodos
parameters:
- name: status
in: query
description: Filter todos by status (e.g., "pending", "completed")
required: false
schema:
type: string
enum: [pending, completed, in-progress]
- name: token
in: cookie
description: Token for authentication
required: false
schema:
type: integer
format: int32
minimum: 1
default: 20
- name: limit
in: query
description: Maximum number of todos to return
required: false
schema:
type: integer
format: int32
minimum: 1
default: 20
- name: offset
in: query
description: Number of todos to skip for pagination
required: false
schema:
type: integer
format: int32
minimum: 0
default: 0
responses:
'200':
description: A list of todo items.
content:
application/json:
schema:
type: array
items:
oneOf:
- $ref: '#/components/schemas/Todo'
- $ref: '#/components/schemas/NewTodo'
'400':
$ref: '#/components/responses/BadRequest'
'500':
$ref: '#/components/responses/InternalServerError'
# ... (The full spec would include components for #/components/schemas/Todo,
# #/components/schemas/NewTodo, #/components/responses/BadRequest, etc.)
当你奔跑时 mcpgen --input your_openapi.yaml --output generated-server (以及可选 --includes=httpclient,types), mcpgen 分析此操作(operationId: listTodos)并生成Go代码。这包括:
-
输入的JSON模式: 一个包含JSON模式的常量字符串,表示
listTodos工具:// Input Schema for the ListTodos tool const listTodosInputSchema = `{ "properties": { "limit": { "default": 20, "description": "Maximum number of todos to return", "format": "int32", "minimum": 1, "type": "integer" }, "offset": { "default": 0, "description": "Number of todos to skip for pagination", "format": "int32", "minimum": 0, "type": "integer" }, "status": { "description": "Filter todos by status (e.g., \"pending\", \"completed\")", "enum": [ "pending", "completed", "in-progress" ], "type": "string" }, "token": { "default": 20, "description": "Token for authentication", "format": "int32", "minimum": 1, "type": "integer" } }, "type": "object" }` -
响应的Markdown模板: 常量字符串,包含每个潜在响应的详细标记提示(基于状态代码和内容类型),描述数据的结构和含义。这对于LLM理解工具的输出至关重要:
// Response Template for the ListTodos tool (Status: 200, Content-Type: application/json) const ListTodosResponseTemplate_A = `# API Response Information ... (detailed markdown describing the 200 response structure including the oneOf combining Todo and NewTodo schemas) ... ` // Response Template for the ListTodos tool (Status: 400, Content-Type: application/json) const ListTodosResponseTemplate_B = `# API Response Information ... (detailed markdown describing the 400 error response structure) ... ` // Response Template for the ListTodos tool (Status: 500, Content-Type: application/json) const ListTodosResponseTemplate_C = `# API Response Information ... (detailed markdown describing the 500 error response structure) ... `注意:markdown模板的全部内容是广泛的,并且是基于OpenAPI响应模式生成的。
-
MCP工具注册: 创建和配置
mcp.Tool实例,嵌入操作的描述和生成的输入模式:// NewListTodosMCPTool creates the MCP Tool instance for ListTodos func NewListTodosMCPTool() mcp.Tool { return mcp.NewToolWithRawSchema( "ListTodos", // Operation ID becomes the Tool Name "List all todo items - Retrieves a list of todo items, optionally filtered by status.", // Summary + Description []byte(listTodosInputSchema), // Embedded Input Schema ) } -
处理程序函数骨架: 一个占位符函数,您将在其中编写代码来处理工具调用。此功能接收
mcp.CallToolRequest(包含JSON形式的输入有效负载),并且是您将与实际后端API集成的地方:// ListTodosHandler is the handler function for the ListTodos tool. // This function is automatically generated. Users should implement the actual // logic within this function body to integrate with backend APIs. // You can generate types, http client and helpers for parsing request params to facilitate the implementation. func ListTodosHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { // IMPORTANT: Replace the following placeholder implementation with your actual logic. // Use the 'request' parameter to access tool call arguments. // Make HTTP calls or interact with services as needed. // Return an *mcp.CallToolResult with the response payload, or an error. // Example placeholder implementation: // Extract the parameters from the request and parse them. // Call your backend API or perform the necessary operations using 'params'. // Handle the response and errors accordingly. return nil, fmt.Errorf("ListTodos handler not implemented") // Placeholder until you add your logic }
通过生成所有这些结构化的样板代码, mcpgen 允许您只专注于在生成的处理程序函数中实现核心集成逻辑-解析输入有效负载(可能因生成的类型而简化),调用现有的后端API(可能因产生的客户端而简化)并将后端响应映射到预期的MCP CallToolResult 格式。
许可证
该项目根据 MIT许可证.
