HTTP 转 MCP 自定义 yaml 配置教程
快速开始:自定义 YAML 结构示例
参考这个 YAML 结构示例模板,可以快速扩展你的配置。
本模板案例为:一个 HTTP Server,有三个接口:
- 查询 item
- 查询 item 列表
- 创建 item
现在将这个 HTTP Server 转为 MCP Server,并将原来的三个接口转为 MCP Tool。 其中,list_items API 有权限校验。
本文的附录部分,会附上该 HTTP 服务原本所有的 Swagger 接口文档。本案例是基于这个接口文档生成的自定义 YAML 基础之上进行的修改。
1server:
2 name: 你的MCP-SERVER名字
3 # 类型,必须有,而且值为rest
4 type: rest
5 # 如果 API 没有鉴权逻辑,securitySchemes 这一坨都可以删除。这里只是声明而已,如果 tools 里面没有引用,这里的 securitySchemes 都不会生效。
6 # defaultCredential 的值,就是校验值
7 # 如果你有服务器级别的默认认证配置需求,参考本文的 defaultUpstreamSecurity 和 defaultDownstreamSecurity 字段
8 securitySchemes:
9 - id: ApiKeyAuth
10 defaultCredential: '123456'
11 type: apiKey
12 in: header
13 name: X-API-Key
14 - id: BasicAuth
15 defaultCredential: admin:admin123
16 type: http
17 scheme: basic
18 - id: BearerAuth
19 defaultCredential: asdf
20 type: http
21 scheme: bearer
22 # 一些配置信息。可以被后面的字段引用,引用方式为{{.config.xxxx}}
23 config:
24 # 比如在这里可以声明 ContentType,在后面可以拿去引用
25 ContentType: 'application/json'
26
27# 工具配置。这里举例包含了:不需要鉴权的工具、需要鉴权的工具
28tools:
29 - args: # 工具的参数配置
30 - description: 商品ID # 参数的描述
31 # 参数名
32 name: id
33 # 参数位置
34 position: path
35 required: true
36 type: integer
37 # 工具描述
38 description: 获取商品 - 根据ID获取商品
39 # 工具名
40 name: get_item
41 # API的请求体
42 requestTemplate:
43 headers:
44 - key: Content-Type
45 value: '{{.config.ContentType}}'
46 method: GET
47 # 路径配置
48 url: '/api/items/{id}'
49 # API 响应模板
50 responseTemplate:
51 # 在响应体前面可以加一些文本内容,比如一些结构化的描述,能让 LLM 更好理解。如果你使用了prependBody,就不能使用body,因为互斥。
52 prependBody: |
53 以下是响应内容
54 - args:
55 # 工具描述
56 description: 获取items列表,需要鉴权
57 # 工具名
58 name: list_item
59 # 在这一层配置security,是在你调用 MCP 工具时需要做的鉴权。如果没有,则不用配置security字段。
60 security:
61 # 引用的id是上面securitySchemes的id,注意一定要匹配id
62 id: BasicAuth
63 # API的请求体
64 requestTemplate:
65 # 这一层配置的就是对RestFul API的鉴权了。如果没有,则不用配置security字段
66 security:
67 id: BearerAuth
68 method: GET
69 url: '/api/items'
70 # API 响应模板
71 responseTemplate:
72 # 注意,如果不配置body的值,默认使用 API 的响应体的值。如果配置了,则使用你配置的值。想要读取原本响应体的值,需要使用模板语法。
73 # 如果你使用了body,就不能使用prependBody或appendBody,因为互斥。
74 body: |
75 {{range $index, $item := .data}}
76 id: {{$item.id}}
77 name: {{$item.name}}
78 描述: {{$item.description}}
79 价格: {{$item.price}}
80 {{end}}
81 - args: # POST请求的实例
82 - description: 商品描述
83 name: description
84 # 注意到这个参数位置到body了
85 position: body
86 type: string
87 - description: 商品名称
88 name: name
89 position: body
90 required: true
91 type: string
92 - description: 商品价格
93 name: price
94 position: body
95 required: true
96 type: number
97 description: 创建商品 - 创建一个新的商品
98 name: create_item
99 requestTemplate:
100 headers:
101 - key: Content-Type
102 value: 'application/json'
103 method: POST
104 url: '/api/items'
105 # 什么都不配就使用原生Restful API的响应体
106 responseTemplate:
更多使用说明见下文。
HTTP 转 MCP 配置
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
|---|---|---|---|---|
tools |
array of object | 选填 | [] | HTTP 转 MCP 工具配置列表 |
tools[].name |
string | 必填 | - | 工具名称 |
tools[].description |
string | 必填 | - | 工具功能描述 |
tools[].args |
array of object | 必填 | [] | 工具参数定义 |
tools[].args[].name |
string | 必填 | - | 参数名称 |
tools[].args[].description |
string | 必填 | - | 参数描述 |
tools[].args[].type |
string | 选填 | string | 参数类型(string, number, integer, boolean, array, object) |
tools[].args[].required |
boolean | 选填 | false | 参数是否必需 |
tools[].args[].default |
any | 选填 | - | 参数默认值 |
tools[].args[].enum |
array | 选填 | - | 参数允许的值列表 |
tools[].args[].items |
object | 选填 | - | 数组项的模式(当type为array时) |
tools[].args[].properties |
object | 选填 | - | 对象属性的模式(当type为object时) |
tools[].args[].position |
string | 选填 | - | 参数在请求中的位置(query, path, header, cookie, body) |
tools[].requestTemplate |
object | 必填 | - | HTTP 请求模板 |
tools[].requestTemplate.url |
string | 必填 | - | 请求 URL 模板 |
tools[].requestTemplate.method |
string | 必填 | - | HTTP 方法(GET/POST等) |
tools[].requestTemplate.headers |
array of object | 选填 | [] | 请求头模板 |
tools[].requestTemplate.headers[].key |
string | 必填 | - | 请求头名称 |
tools[].requestTemplate.headers[].value |
string | 必填 | - | 请求头值模板 |
tools[].requestTemplate.body |
string | 选填 | - | 请求体模板(与argsToJsonBody、argsToUrlParam、argsToFormBody互斥) |
tools[].requestTemplate.argsToJsonBody |
boolean | 选填 | false | 当为true时,参数将直接用作JSON请求体(与body、argsToUrlParam、argsToFormBody互斥) |
tools[].requestTemplate.argsToUrlParam |
boolean | 选填 | false | 当为true时,参数将作为查询参数添加到URL中(与body、argsToJsonBody、argsToFormBody互斥) |
tools[].requestTemplate.argsToFormBody |
boolean | 选填 | false | 当为true时,参数将以application/x-www-form-urlencoded格式编码在请求体中(与body、argsToJsonBody、argsToUrlParam互斥) |
tools[].responseTemplate |
object | 必填 | - | HTTP 响应转换模板 |
tools[].responseTemplate.body |
string | 选填 | - | 响应体转换模板(与prependBody和appendBody互斥) |
tools[].responseTemplate.prependBody |
string | 选填 | - | 在响应体前插入的文本(与body互斥) |
tools[].responseTemplate.appendBody |
string | 选填 | - | 在响应体后插入的文本(与body互斥) |
tools[].security |
object | 选填 | - | 工具级别安全配置,用于定义 MCP Client 和 MCP Server 之间的认证方式,并支持凭证透传。 |
tools[].security.id |
string | 当 tools[].security 配置时必填 |
- | 引用在 server.securitySchemes 中定义的认证方案 ID。 |
tools[].security.passthrough |
boolean | 选填 | false | 是否启用透明认证。如果为 true,则从 MCP Client 请求中提取的凭证将用于 requestTemplate.security 定义的认证方案。 |
tools[].requestTemplate.security |
object | 选填 | - | HTTP 请求模板的安全配置,用于定义 MCP Server 和 REST API 之间的认证方式。 |
tools[].requestTemplate.security.id |
string | 当tools[].requestTemplate.security 配置时必填 |
- | 引用在 server.securitySchemes 中定义的认证方案 ID。 |
tools[].requestTemplate.security.credential |
string | 选填 | - | 覆盖 server.securitySchemes 中定义的默认凭证。如果同时启用了 tools[].security.passthrough,则此字段将被忽略,优先使用透传的凭证。 |
tools[].errorResponseTemplate |
string | 选填 | - | HTTP响应Status>=300 或 Status <200 时的错误响应转换模板 |
认证与安全
本服务支持灵活的认证配置,以确保与后端 REST API 通信的安全性。支持认证配置:
- HTTP 转 MCP (
rest类型):将客户端请求转换为 REST API 调用 它支持两层认证机制:
- 客户端到网关认证:验证调用 MCP Server 的客户端身份
- 网关到后端认证:MCP Server 调用后端服务时的认证方式
定义认证方案 (server.securitySchemes)
您可以在服务器级别定义一组可重用的认证方案。这些方案之后可以被各个工具引用,用于配置 MCP Server 向后端 REST API 发起请求时的认证方式。
配置字段 (server.securitySchemes[]):
| 名称 | 数据类型 | 填写要求 | 描述 |
|---|---|---|---|
id |
string | 必填 | 认证方案的唯一标识符,供工具配置引用。 |
type |
string | 必填 | 认证类型,支持 http (用于 Basic 和 Bearer认证) 和 apiKey。 |
scheme |
string | 选填 | 当 type 为 http 时指定具体的方案,如 basic 或 bearer。 |
in |
string | 选填 | 当 type 为 apiKey 时指定 API 密钥的位置,如 header 或 query。 |
name |
string | 选填 | 当 type 为 apiKey 时指定 Header 名称或查询参数名称。 |
defaultCredential |
string | 选填 | 此方案的默认凭证。例如,对于 Basic Auth,可以是 "user:password";对于 Bearer Token,是 Token 本身;对于 API Key,是 Key 本身。 |
示例 (server.securitySchemes):
1server:
2 name: my-api-server
3 securitySchemes:
4 - id: MyBasicAuth
5 type: http
6 scheme: basic
7 defaultCredential: "admin:secretpassword" # 默认的用户名和密码
8 - id: MyBearerToken
9 type: http
10 scheme: bearer
11 defaultCredential: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # 默认的Bearer Token
12 - id: MyApiKeyInHeader
13 type: apiKey
14 in: header
15 name: X-Custom-API-Key # API Key 在名为 X-Custom-API-Key 的 Header 中
16 defaultCredential: "abcdef123456" # 默认的 API Key
17 - id: MyApiKeyInQuery
18 type: apiKey
19 in: query
20 name: "api_token" # API Key 在名为 api_token 的查询参数中
21 defaultCredential: "uvwxyz789012"
在工具中应用认证方案
定义了 server.securitySchemes 后,您可以在每个工具的 requestTemplate.security 中通过 id 引用这些方案,以指定 MCP Server 调用后端 REST API 时使用的认证方式。
tools[].requestTemplate.security.id: 引用server.securitySchemes中定义的认证方案的id。tools[].requestTemplate.security.credential: 可选。如果提供,它将覆盖所引用方案中的defaultCredential。这允许您为特定工具使用不同的凭证,即使它们共享相同的认证机制。 示例:
1tools:
2- name: get-user-details
3 # ... 其他工具配置 ...
4 requestTemplate:
5 url: "https://api.example.com/users/{{.args.userId}}"
6 method: GET
7 security:
8 id: MyBearerToken # 使用上面定义的 MyBearerToken 方案
9 # credential: "override_token_for_this_tool" # 可选:为此工具覆盖默认Token
10# ...
11- name: update-inventory
12 # ... 其他工具配置 ...
13 requestTemplate:
14 url: "https://api.example.com/inventory/{{.args.itemId}}"
15 method: POST
16 security:
17 id: MyApiKeyInHeader # 使用 MyApiKeyInHeader 方案
18 # 此工具将使用 MyApiKeyInHeader 中定义的 defaultCredential
透明认证 (Passthrough Authentication)
透明认证功能允许将 MCP Client (例如 AI 助手) 调用 MCP Server 时提供的凭证,透传给 MCP Server 调用后端 REST API 时的认证过程。
配置方式:
- 确保相关认证方案已在
server.securitySchemes中定义。这包括客户端用于连接到 MCP Server 的方案,以及 MCP Server 用于连接到后端 REST API 的方案。 - 配置工具级别认证 (
tools[].security): 在需要透传凭证的工具中,配置security字段: id: xxxx # 引用 server.securitySchemes 中定义的、用于 MCP Client 与 MCP Server 之间的认证方案。插件将根据此方案从客户端请求中提取凭证,并清理原始请求中的该凭证。 passthrough: true # 启用透明认证。 - 配置请求模板认证 (
tools[].requestTemplate.security): 在工具的requestTemplate中,配置security字段: id: 引用 server.securitySchemes 中定义的、用于 MCP Server 与后端 REST API 之间的认证方案。 当 tools[].security.passthrough 为 true 时,从客户端提取的凭证将根据此 requestTemplate.security 方案应用于对后端 REST API 的调用。
示例: 假设 MCP Client 使用 Bearer Token 调用 MCP Server,而 MCP Server 需要使用 API Key 调用后端的 REST API。
1server:
2 name: product-api-server
3 securitySchemes:
4 - id: ClientSideBearer # 客户端使用Bearer Token
5 type: http
6 scheme: bearer
7 - id: BackendApiKey # 后端API使用X-API-Key
8 type: apiKey
9 in: header
10 name: X-API-Key
11 # defaultCredential: "optional_default_backend_key"
12tools:
13- name: get-product-securely
14 description: "获取产品信息(安全透传)"
15 security: # 客户端 -> MCP Server 认证配置
16 id: ClientSideBearer # MCP Server期望客户端使用此方案,并会尝试提取此类型的凭证
17 passthrough: true # 启用透传
18 args:
19 - name: product_id
20 description: "产品ID"
21 type: string
22 required: true
23 requestTemplate:
24 security: # MCP Server -> 后端 REST API 认证配置
25 id: BackendApiKey # 后端API需要此方案。透传的凭证将按此方案应用。
26 url: "https://api.example.com/products/{{.args.product_id}}"
27 method: GET
工作流程:
- MCP Client 发起请求到 MCP Server 的
get-product-securely工具,并在Authorization头中携带Bearer <client_token>。 - MCP Server 根据
tools[].security(id:ClientSideBearer) 识别出客户端使用的是 Bearer Token。它会从请求中提取<client_token>并移除原始的Authorization头。 - 因为
passthrough: true,提取出的<client_token>被标记为透传凭证。 - MCP Server 准备调用后端 REST API。它查看
requestTemplate.security(id:BackendApiKey)。 - 由于启用了透传,MCP Server 将之前提取的
<client_token>作为凭证值,按照BackendApiKey方案(即作为名为X-API-Key的 HTTP Header)添加到对https://api.example.com/products/...的请求中。 - 后端 REST API 收到请求,其中
X-API-KeyHeader 的值为<client_token>。 注意事项:
- 当
tools[].security.passthrough为true时,requestTemplate.security.credential字段会被忽略,优先使用透传的凭证。 - 透传的凭证值会直接用于
requestTemplate.security指定的认证方案。请确保凭证的格式与目标认证方案兼容。extractAndRemoveIncomingCredential函数会尝试提取核心凭证部分(例如,Bearer token 值,Basic auth 的 base64 编码部分)。
服务器级别默认认证配置
为了简化配置和确保一致性,本 YAML 配置支持在服务器级别设置默认的认证配置。这些默认配置将应用于所有工具和非工具特定的接口(如 tools/list)。
server.defaultDownstreamSecurity
定义客户端到网关的默认认证配置。这个配置将应用于:
- 所有没有明确配置
security字段的工具 tools/list请求(获取工具列表)- 其他非工具特定的 MCP 协议接口 配置字段:
id:引用server.securitySchemes中定义的认证方案 IDpassthrough:是否启用透明认证(可选,默认为 false)
server.defaultUpstreamSecurity
定义网关到后端的默认认证配置。这个配置将应用于:
- 所有没有明确配置
requestTemplate.security字段的工具 tools/list等需要访问后端服务的请求 配置字段:id:引用server.securitySchemes中定义的认证方案 IDcredential:覆盖默认凭证(可选)
优先级规则
认证配置的优先级从高到低:
- 工具级别配置(
tools[].security和tools[].requestTemplate.security) - 服务器级别默认配置(
server.defaultDownstreamSecurity和server.defaultUpstreamSecurity) - 认证方案中的默认凭证(
server.securitySchemes[].defaultCredential)
使用场景
服务器级别默认认证特别适用于以下场景:
- 统一认证策略:所有工具都使用相同的认证方式
- MCP 代理服务器:需要为
tools/list等非工具特定请求提供认证 - 简化配置:减少每个工具重复配置相同的认证信息
参数类型支持
HTTP 转 MCP 工具支持多种参数类型,使您可以更精确地定义工具参数:
- string: 字符串类型(默认)
- number: 数字类型(浮点数)
- integer: 整数类型
- boolean: 布尔类型(true/false)
- array: 数组类型,使用
items字段定义数组元素的模式 - object: 对象类型,使用
properties字段定义对象属性的模式 示例:
1args:
2- name: query
3 description: "搜索关键词"
4 type: string
5 required: true
6- name: limit
7 description: "返回结果数量"
8 type: integer
9 default: 10
10- name: filters
11 description: "过滤条件"
12 type: object
13 properties:
14 category:
15 type: string
16 enum: ["food", "hotel", "attraction"]
17 price:
18 type: integer
19 minimum: 0
20- name: coordinates
21 description: "坐标点列表"
22 type: array
23 items:
24 type: object
25 properties:
26 lat:
27 type: number
28 lng:
29 type: number
参数位置控制
HTTP 转 MCP 的工具支持通过 position 字段精确控制每个参数在请求中的位置。这使您可以更灵活地构建 API 请求,例如同时使用路径参数、查询参数和请求体参数。
支持的位置类型
- query: 参数将作为查询参数添加到 URL 中
- path: 参数将替换 URL 中的路径占位符,例如
/pet/{petId}中的{petId} - header: 参数将作为 HTTP 头添加到请求中
- cookie: 参数将作为 Cookie 添加到请求中
- body: 参数将添加到请求体中(根据内容类型自动格式化为 JSON 或表单)
使用示例
1args:
2- name: petId
3 description: "宠物ID"
4 type: string
5 required: true
6 position: path
7- name: token
8 description: "认证令牌"
9 type: string
10 required: true
11 position: header
12- name: sessionId
13 description: "会话ID"
14 type: string
15 position: cookie
16- name: limit
17 description: "返回结果数量"
18 type: integer
19 default: 10
20 position: query
21- name: tags
22 description: "标签列表"
23 type: array
24 position: body
在上面的示例中:
petId将替换 URL 中的{petId}占位符token将作为 HTTP 头添加到请求中sessionId将作为 Cookie 添加到请求中limit将作为查询参数添加到 URL 中tags将添加到请求体中
与批量参数处理选项的关系
当使用 position 指定参数位置时,这些参数将按照指定的位置处理,而不会受到批量参数处理选项(argsToJsonBody、argsToUrlParam、argsToFormBody)的影响。只有未指定 position 的参数才会受到这些批量选项的影响。
例如,如果您同时使用了 position 和 argsToJsonBody:
- 指定了
position: query的参数会添加到 URL 查询字符串中 - 指定了
position: header的参数会添加到 HTTP 头中 - 指定了
position: path的参数会替换 URL 中的占位符 - 指定了
position: cookie的参数会添加到 Cookie 中 - 指定了
position: body的参数会添加到 JSON 请求体中 - 未指定
position的参数会通过argsToJsonBody添加到 JSON 请求体中 此外,如果在requestTemplate中明确指定了body,则所有position: body的参数都将被忽略,以避免冲突。
请求参数传递方式
除了使用 position 精确控制每个参数的位置外,HTTP 转 MCP 的工具还支持四种批量参数处理方式,这些选项是互斥的,只能选择其中一种:
- body: 使用模板手动构建请求体。这是最灵活的方式,允许您完全控制请求体的格式。
1requestTemplate:
2 body: |
3 {
4 "query": "{{.args.query}}",
5 "filters": {{toJson .args.filters}},
6 "options": {
7 "limit": {{.args.limit}}
8 }
9 }
- argsToJsonBody: 当设置为
true时,未指定position的参数将直接作为 JSON 对象发送到请求体中,并自动添加Content-Type: application/json; charset=utf-8头。
1requestTemplate:
2 argsToJsonBody: true
- argsToUrlParam: 当设置为
true时,未指定position的参数将作为查询参数添加到 URL 中。
1requestTemplate:
2 argsToUrlParam: true
- argsToFormBody: 当设置为
true时,未指定position的参数将以application/x-www-form-urlencoded格式编码在请求体中,并自动添加相应的 Content-Type 头。
1requestTemplate:
2 argsToFormBody: true
这些选项简化了常见 API 调用模式的配置,无需手动构建请求体或 URL 参数。请注意,这四个选项是互斥的,在一个工具配置中只能使用其中一种。如果同时配置了多个选项,系统会报错并拒绝加载该工具配置。
模板语法
HTTP 转 MCP 功能使用的模板渲染,结合了 Go 的模板语法和 GJSON 的强大路径语法:
请求模板
用于构造 HTTP 请求 URL、头部和正文:
- 访问配置值:
.config.字段名 - 访问工具参数:
.args.参数名
响应模板
用于将 HTTP 响应转换为适合 AI 消费的格式:
- 使用 GJSON 路径语法访问 JSON 响应字段
- 使用模板函数如
add、upper、lower等 - 使用控制结构如
if、range等 GJSON Template 包含了所有 Sprig 的函数,提供了 70+ 种用于字符串操作、数学运算、日期格式化等的模板函数,功能等同于 Helm 的模板能力。 常用的 Sprig 函数包括: - 字符串操作:
trim、upper、lower、replace、plural、nospace - 数学运算:
add、sub、mul、div、max、min - 日期格式化:
now、date、dateInZone、dateModify - 列表操作:
list、first、last、uniq、sortAlpha - 字典操作:
dict、get、set、hasKey、pluck - 流程控制:
ternary、default、empty、coalesce - 类型转换:
toString、toJson、toPrettyJson、toRawJson - 编码/解码:
b64enc、b64dec、urlquery、urlqueryescape - UUID 生成:
uuidv4有关所有可用函数的完整参考,请参阅 Helm 函数文档,因为 GJSON Template 包含了相同的函数集。
GJSON 路径语法
GJSON 提供了强大的 JSON 查询能力:
- 点表示法:
address.city - 数组索引:
users.0.name - 数组迭代:
users.#.name - 数组过滤:
users.#(age>=30)#.name - 修饰符:
users.@reverse.#.name - 多路径:
{name:users.0.name,count:users.#} - 转义字符:
path.with\.dot对于更复杂的查询,可以使用gjson函数:
1<!-- 使用 gjson 函数进行复杂查询 -->
2活跃用户: {{gjson "users.#(active==true)#.name"}}
3<!-- 带有多个条件的数组过滤 -->
430岁以上的活跃开发者: {{gjson "users.#(active==true && age>30)#.name"}}
5<!-- 使用修饰符 -->
6用户名(倒序): {{gjson "users.@reverse.#.name"}}
7<!-- 迭代过滤结果 -->
8管理员:
9{{range $user := gjson "users.#(roles.#(==admin)>0)#"}}
10 - {{$user.name}} ({{$user.age}})
11{{end}}
完整的 GJSON 路径语法参考可查看 GJSON 文档。
配置示例
基础配置示例:转换高德地图 API
1server:
2 name: rest-amap-server
3 config:
4 apiKey: your-api-key-here
5tools:
6- name: maps-geo
7 description: "将详细的结构化地址转换为经纬度坐标。支持对地标性名胜景区、建筑物名称解析为经纬度坐标"
8 args:
9 - name: address
10 description: "待解析的结构化地址信息"
11 type: string
12 required: true
13 - name: city
14 description: "指定查询的城市"
15 type: string
16 required: false
17 - name: output
18 description: "输出格式"
19 type: string
20 enum: ["json", "xml"]
21 default: "json"
22 requestTemplate:
23 url: "https://restapi.amap.com/v3/geocode/geo"
24 method: GET
25 argsToUrlParam: true
26 headers:
27 - key: x-api-key
28 value: "{{.config.apiKey}}"
29 responseTemplate:
30 body: |
31 # 地理编码信息
32 {{- range $index, $geo := .geocodes }}
33 ## 地点 {{add $index 1}}
34 - **国家**: {{ $geo.country }}
35 - **省份**: {{ $geo.province }}
36 - **城市**: {{ $geo.city }}
37 - **城市代码**: {{ $geo.citycode }}
38 - **区/县**: {{ $geo.district }}
39 - **街道**: {{ $geo.street }}
40 - **门牌号**: {{ $geo.number }}
41 - **行政编码**: {{ $geo.adcode }}
42 - **坐标**: {{ $geo.location }}
43 - **级别**: {{ $geo.level }}
44 {{- end }}
此配置将高德地图的地理编码 API 转换为 AI 可调用的工具。当 AI 调用此工具时:
- 使用提供的地址和城市参数构建 API 请求
- 调用高德地图 API
- 将 JSON 响应转换为易于阅读的 Markdown 格式
- 将格式化后的结果返回给 AI 助手
高级配置示例:带有条件逻辑的复杂响应处理
1server:
2 name: weather-api-server
3 config:
4 apiKey: your-weather-api-key
5tools:
6- name: get-weather
7 description: "获取指定城市的天气预报信息"
8 args:
9 - name: city
10 description: "城市名称"
11 type: string
12 required: true
13 - name: days
14 description: "天数(1-7)"
15 type: integer
16 required: false
17 default: 3
18 - name: include_hourly
19 description: "是否包含每小时预报"
20 type: boolean
21 default: true
22 requestTemplate:
23 url: "https://api.weatherapi.com/v1/forecast.json"
24 method: GET
25 argsToUrlParam: true
26 headers:
27 - key: x-api-key
28 value: "{{.config.apiKey}}"
29 responseTemplate:
30 body: |
31 # {{.location.name}}, {{.location.country}} 天气预报
32 **当前温度**: {{.current.temp_c}}°C
33 **体感温度**: {{.current.feelslike_c}}°C
34 **天气状况**: {{.current.condition.text}}
35 **湿度**: {{.current.humidity}}%
36 **风速**: {{.current.wind_kph}} km/h
37 ## 未来预报
38 {{range $index, $day := .forecast.forecastday}}
39 ### {{$day.date}} ({{dateFormat "Monday" $day.date_epoch | title}})
40
41 {{if gt $day.day.maxtemp_c 30}}**高温预警!**{{end}}
42 {{if lt $day.day.mintemp_c 0}}**低温预警!**{{end}}
43
44 - **最高温度**: {{$day.day.maxtemp_c}}°C
45 - **最低温度**: {{$day.day.mintemp_c}}°C
46 - **降水概率**: {{$day.day.daily_chance_of_rain}}%
47 - **天气状况**: {{$day.day.condition.text}}
48
49 #### 分时预报
50 {{range $hour := slice $day.hour 6 24 3}}
51 - **{{dateFormat "15:04" $hour.time_epoch}}**: {{$hour.temp_c}}°C, {{$hour.condition.text}}
52 {{end}}
53 {{end}}
此示例展示了:
- 使用条件语句 (
if) 进行温度警告 - 使用日期格式化函数 (
dateFormat) - 使用数组切片 (
slice) 选择特定时间的天气 - 嵌套循环遍历多天和多时段的天气数据
使用 PrependBody 和 AppendBody 的示例:OpenAPI 转换
当您想保留原始 API 响应但添加额外的上下文信息时,prependBody 和 appendBody 字段非常有用。这在将 OpenAPI/Swagger 规范转换为 MCP 工具时特别有价值,因为您可以保留原始 JSON 响应,同时为 AI 助手提供字段含义的说明。
1server:
2 name: product-api-server
3 config:
4 apiKey: your-api-key-here
5tools:
6- name: get-product
7 description: "获取产品详细信息"
8 args:
9 - name: product_id
10 description: "产品ID"
11 type: string
12 required: true
13 requestTemplate:
14 url: "https://api.example.com/products/{{.args.product_id}}"
15 method: GET
16 headers:
17 - key: Authorization
18 value: "Bearer {{.config.apiKey}}"
19 responseTemplate:
20 prependBody: |
21 # 产品信息
22
23 以下是产品的详细信息,以JSON格式返回。字段说明:
24
25 - **id**: 产品唯一标识符
26 - **name**: 产品名称
27 - **description**: 产品描述
28 - **price**: 产品价格(美元)
29 - **category**: 产品类别
30 - **inventory**: 库存信息
31 - **quantity**: 当前库存数量
32 - **warehouse**: 仓库位置
33 - **ratings**: 用户评分列表
34 - **score**: 评分(1-5)
35 - **comment**: 评论内容
36
37 原始JSON响应:
38
39 appendBody: |
40
41 您可以使用这些信息来了解产品的详细信息、价格、库存状态和用户评价。
此示例展示了:
- 使用
prependBody在原始 JSON 响应前添加字段说明 - 使用
appendBody在响应末尾添加使用建议 - 保留原始 JSON 响应,使 AI 助手可以直接访问所有数据
使用 errorResponseTemplate自定义错误响应的示例
errorResponseTemplate用于在HTTP响应status code>=300 || <200时自定义响应转换模板。支持通过_headers访问map结构的header key value, 以便在errorResponseTemplate中引用header中的值自定义错误响应结果。
1server:
2 config:
3 appCode: ""
4 name: "银行卡二三四要素"
5tools:
6- args:
7 - description: "银行卡号"
8 name: "cardno"
9 position: "query"
10 required: true
11 type: "string"
12 - description: "姓名(注意UrlEncode编码)"
13 name: "name"
14 position: "query"
15 required: false
16 type: "string"
17 - description: "预留手机号"
18 name: "mobile"
19 position: "query"
20 required: false
21 type: "string"
22 - description: "身份证号码"
23 name: "idcard"
24 position: "query"
25 required: false
26 type: "string"
27 description: "验证卡号、姓名、手机号、证件号是否一致"
28 errorResponseTemplate: |-
29 statusCode: {{gjson "_headers.\\:status"}}
30 errorCode: {{gjson "_headers.x-ca-error-code"}}
31 data: {{.data.value}}
32 name: "银行卡二三四要素验证"
33 requestTemplate:
34 argsToFormBody: false
35 argsToJsonBody: false
36 argsToUrlParam: true
37 method: "GET"
38 url: "https://ckid.market.xxx.com/lundear/verifyBank"
39 responseTemplate:
40 appendBody: |2-
41 - 以下是返回参数说明
42 - 参数名称: code, 参数类型: integer, 参数描述: 响应状态码
43 - 参数名称: desc, 参数类型: string, 参数描述: 描述信息
44 - 参数名称: data, 参数类型: object, 参数描述: 无描述
45 - 参数名称: data.bankId, 参数类型: string, 参数描述: 银行编码
46 - 参数名称: data.bankName, 参数类型: string, 参数描述: 银行名称
47 - 参数名称: data.abbr, 参数类型: string, 参数描述: 银行英文缩写
48 - 参数名称: data.cardName, 参数类型: string, 参数描述: 卡名称
49 - 参数名称: data.cardType, 参数类型: string, 参数描述: 卡类型
50 - 参数名称: data.cardBin, 参数类型: string, 参数描述: 卡bin
51 - 参数名称: data.binLen, 参数类型: integer, 参数描述: 卡bin长度
52 - 参数名称: data.area, 参数类型: string, 参数描述: 卡所在地区
53 - 参数名称: data.bankPhone, 参数类型: string, 参数描述: 银行电话
54 - 参数名称: data.bankUrl, 参数类型: string, 参数描述: 银行网址
55 - 参数名称: data.bankLogo, 参数类型: string, 参数描述: 银行logo
此示例展示了:
- {{gjson "_headers.:status"}} -> 访问HTTP响应code
- {{gjson "_headers.x-ca-error-code"}} -> 访问Header中"x-ca-error-code"的值
- {{.data.value}} -> 访问响应体 (e.g., JSON 字段 "data.value")
AI 提示词生成模板
在与 AI 助手一起生成 HTTP 转 MCP 配置的模板时,您可以使用以下提示词:
1请帮我创建一个 AI 原生网关 的 MCP 服务器配置。支持:
21. **HTTP 转 MCP 服务器**:将 REST API 转换为 MCP 工具
3## 配置格式
4### HTTP 转 MCP 服务器配置
5```yaml
6server:
7 name: rest-api-server
8 type: rest # 可选,默认为 rest
9 config:
10 apiKey: 您的API密钥
11 # 服务器级别默认认证(可选)
12 defaultDownstreamSecurity:
13 id: ClientAuth
14 defaultUpstreamSecurity:
15 id: BackendAuth
16 securitySchemes:
17 - id: ClientAuth
18 type: http
19 scheme: bearer
20 - id: BackendAuth
21 type: apiKey
22 in: header
23 name: X-API-Key
24 defaultCredential: 您的后端API密钥
25tools:
26- name: tool-name
27 description: "详细描述这个工具的功能"
28 security: # 工具级别客户端认证(可选,覆盖服务器默认)
29 id: ClientAuth
30 passthrough: true # 启用透明认证
31 args:
32 - name: arg1
33 description: "参数1的描述"
34 type: string # 可选类型: string, number, integer, boolean, array, object
35 required: true
36 position: path # 可选位置: query, path, header, cookie, body
37 - name: arg2
38 description: "参数2的描述"
39 type: integer
40 required: false
41 default: 10
42 position: query
43 requestTemplate:
44 url: "https://api.example.com/endpoint"
45 method: POST
46 security: # 工具级别后端认证(可选,覆盖服务器默认)
47 id: BackendAuth
48 credential: "特定工具的凭证" # 可选,覆盖默认凭证
49 # 以下四个选项互斥,只能选择其中一种
50 argsToUrlParam: true # 将参数添加到URL查询参数
51 # 或者其他选项...
52 headers:
53 - key: x-api-key
54 value: "{{.config.apiKey}}"
55 responseTemplate:
56 body: |
57 # 结果
58 {{- range $index, $item := .items }}
59 ## 项目 {{add $index 1}}
60 - **名称**: {{ $item.name }}
61 - **值**: {{ $item.value }}
62 {{- end }}
附录
Swagger 文档参考
这里是快速开始的自定义 YAML 对应的全量接口的 Swagger 文档。
注意我这里面 servers[0].url 设置为空字符串即可,因为你的目标服务地址已经在 MCP 服务的后端服务配置过了。
1openapi: 3.0.3
2info:
3 title: RESTful API 示例项目
4 version: 1.0.0
5 description: 这是一个使用Gin框架构建的RESTful API示例项目,展示了CRUD操作和多种认证方式
6
7servers:
8 - url: ''
9 description: 本地开发服务器
10
11tags:
12 - name: items
13 description: 项目管理相关接口
14 - name: auth
15 description: 认证示例接口
16
17paths:
18 /api/items:
19 get:
20 summary: 列出所有项目
21 description: 获取所有项目列表
22 operationId: listItems
23 tags:
24 - items
25 responses:
26 '200':
27 description: 成功返回项目列表
28 content:
29 application/json:
30 schema:
31 $ref: '#/components/schemas/ItemListResponse'
32 post:
33 summary: 创建新项目
34 description: 创建一个新的项目
35 operationId: createItem
36 tags:
37 - items
38 requestBody:
39 required: true
40 content:
41 application/json:
42 schema:
43 $ref: '#/components/schemas/CreateItemRequest'
44 responses:
45 '201':
46 description: 项目创建成功
47 content:
48 application/json:
49 schema:
50 $ref: '#/components/schemas/ItemResponse'
51 '400':
52 description: 请求参数错误
53 content:
54 application/json:
55 schema:
56 $ref: '#/components/schemas/ErrorResponse'
57
58 /api/items/{id}:
59 get:
60 summary: 获取单个项目
61 description: 根据ID获取项目详情
62 operationId: getItem
63 tags:
64 - items
65 parameters:
66 - name: id
67 in: path
68 required: true
69 description: 项目ID
70 schema:
71 type: integer
72 example: 1
73 responses:
74 '200':
75 description: 成功返回项目详情
76 content:
77 application/json:
78 schema:
79 $ref: '#/components/schemas/ItemResponse'
80 '404':
81 description: 项目不存在
82 content:
83 application/json:
84 schema:
85 $ref: '#/components/schemas/ErrorResponse'
86 put:
87 summary: 更新项目
88 description: 根据ID更新项目信息
89 operationId: updateItem
90 tags:
91 - items
92 parameters:
93 - name: id
94 in: path
95 required: true
96 description: 项目ID
97 schema:
98 type: integer
99 example: 1
100 requestBody:
101 required: true
102 content:
103 application/json:
104 schema:
105 $ref: '#/components/schemas/UpdateItemRequest'
106 responses:
107 '200':
108 description: 项目更新成功
109 content:
110 application/json:
111 schema:
112 $ref: '#/components/schemas/ItemResponse'
113 '400':
114 description: 请求参数错误
115 content:
116 application/json:
117 schema:
118 $ref: '#/components/schemas/ErrorResponse'
119 '404':
120 description: 项目不存在
121 content:
122 application/json:
123 schema:
124 $ref: '#/components/schemas/ErrorResponse'
125 delete:
126 summary: 删除项目
127 description: 根据ID删除项目
128 operationId: deleteItem
129 tags:
130 - items
131 parameters:
132 - name: id
133 in: path
134 required: true
135 description: 项目ID
136 schema:
137 type: integer
138 example: 1
139 responses:
140 '200':
141 description: 删除成功
142 content:
143 application/json:
144 schema:
145 $ref: '#/components/schemas/Response'
146 '400':
147 description: 请求参数错误
148 content:
149 application/json:
150 schema:
151 $ref: '#/components/schemas/ErrorResponse'
152 '404':
153 description: 项目不存在
154 content:
155 application/json:
156 schema:
157 $ref: '#/components/schemas/ErrorResponse'
158
159 /api/auth/basic:
160 get:
161 summary: Basic认证示例接口
162 description: 需要提供Basic认证(用户名:admin,密码:admin123)
163 operationId: basicAuthDemo
164 tags:
165 - auth
166 security:
167 - BasicAuth: []
168 responses:
169 '200':
170 description: 认证成功
171 content:
172 application/json:
173 schema:
174 $ref: '#/components/schemas/Response'
175 '401':
176 description: 认证失败
177 content:
178 application/json:
179 schema:
180 $ref: '#/components/schemas/ErrorResponse'
181
182 /api/auth/bearer:
183 get:
184 summary: Bearer Token认证示例接口
185 description: '需要在Authorization header中提供Bearer Token(Token: secret-token-12345)'
186 operationId: bearerAuthDemo
187 tags:
188 - auth
189 security:
190 - BearerAuth: []
191 responses:
192 '200':
193 description: 认证成功
194 content:
195 application/json:
196 schema:
197 $ref: '#/components/schemas/Response'
198 '401':
199 description: 认证失败
200 content:
201 application/json:
202 schema:
203 $ref: '#/components/schemas/ErrorResponse'
204
205 /api/auth/custom:
206 get:
207 summary: 自定义Header认证示例接口
208 description: '需要在X-API-Key header中提供API Key(Key: my-api-key-67890)'
209 operationId: customHeaderAuthDemo
210 tags:
211 - auth
212 security:
213 - ApiKeyAuth: []
214 responses:
215 '200':
216 description: 认证成功
217 content:
218 application/json:
219 schema:
220 $ref: '#/components/schemas/Response'
221 '401':
222 description: 认证失败
223 content:
224 application/json:
225 schema:
226 $ref: '#/components/schemas/ErrorResponse'
227components:
228 schemas:
229 Item:
230 type: object
231 properties:
232 id:
233 type: integer
234 example: 1
235 name:
236 type: string
237 example: 示例商品
238 description:
239 type: string
240 example: 这是一个示例商品描述
241 price:
242 type: number
243 format: float
244 example: 99.99
245
246 CreateItemRequest:
247 type: object
248 properties:
249 name:
250 type: string
251 example: 示例商品
252 description:
253 type: string
254 example: 这是一个示例商品描述
255 price:
256 type: number
257 format: float
258 example: 99.99
259
260 UpdateItemRequest:
261 type: object
262 properties:
263 name:
264 type: string
265 example: 更新后的商品
266 description:
267 type: string
268 example: 更新后的描述
269 price:
270 type: number
271 format: float
272 example: 149.99
273
274 Response:
275 type: object
276 properties:
277 code:
278 type: integer
279 example: 200
280 message:
281 type: string
282 example: success
283 data:
284 type: object
285
286 ItemResponse:
287 type: object
288 properties:
289 code:
290 type: integer
291 example: 200
292 message:
293 type: string
294 example: success
295 data:
296 $ref: '#/components/schemas/Item'
297
298 ItemListResponse:
299 type: object
300 properties:
301 code:
302 type: integer
303 example: 200
304 message:
305 type: string
306 example: success
307 data:
308 type: array
309 items:
310 $ref: '#/components/schemas/Item'
311
312 ErrorResponse:
313 type: object
314 properties:
315 code:
316 type: integer
317 example: 400
318 message:
319 type: string
320 example: 请求参数错误
321
322 securitySchemes:
323 BasicAuth:
324 type: http
325 scheme: basic
326 description: Basic认证(用户名:admin,密码:admin123)
327
328 BearerAuth:
329 type: http
330 scheme: bearer
331 bearerFormat: JWT
332 description: 'Bearer Token认证(Token: secret-token-12345)'
333
334 ApiKeyAuth:
335 type: apiKey
336 in: header
337 name: X-API-Key
338 description: '自定义API Key认证(Key: my-api-key-67890)'
