MCP Toolbox 集成(Integrations)架构指南:通过 tools.yaml 定义 Source 解锁数据库与 HTTP 专用工具集
【免费下载链接】mcp-toolboxMCP Toolbox for Databases is an open source MCP server for databases.项目地址: https://gitcode.com/GitHub_Trending/ge/mcp-toolbox
MCP Toolbox for Databases 将"集成"抽象为一个清晰的三层模型:Integration(集成)→ Source(数据源连接)→ Tools(专用工具)。本文以 docs/en/integrations/_index.md 为骨架,结合仓库源码与预置配置,系统讲解如何在tools.yaml中定义一次数据源连接、如何让 MCP 客户端立即获得该数据源专属的工具集(查询数据、列出表、分析 Schema 等),并给出 BigQuery、HTTP 等典型集成的可运行配置示例。读完本文,你将掌握 Integration 的配置模型、注册机制、认证方式与只读约束,能够独立为任意受支持的数据库或 HTTP 服务编写完整的集成配置。
什么是 Integration:连接外部数据源并解锁工具集
根据 docs/en/integrations/_index.md 的定义:
AnIntegrationrepresents a connection to a database or a HTTP Server.
集成(Integration)的本质是 MCP Toolbox 与外部数据源(数据库或 HTTP 服务器)之间的一条连接。这条连接通过Source来承载:你只需要在tools.yaml配置文件中定义一次Source 连接,集成即宣告建立;此后该集成会解锁一组专门化的Tools(如执行查询、列出数据表、分析表结构等),MCP 客户端(IDE、Agent、CLI)可以立即调用这些工具。
这种"一次定义、多处复用"的设计让配置与工具注册解耦:连接参数只写一遍,工具由该 Source 类型自动派生,客户端无需关心底层驱动细节。
核心概念:Source、Tools 与 Group
从仓库源码可以确认,tools.yaml(服务端通过 cmd/internal/config.go 解析)是一份多文档 YAML,其中每种资源通过kind字段区分,支持以下类型:source、tool、authService、embeddingModel、prompt、resource、resourceTemplate、group(以及旧版toolset,解析时会自动折叠为 group)。
Source:数据源连接
kind: source定义一个到数据库或 HTTP 服务的连接,是集成的入口。其解析流程在 internal/server/config.go 中实现:先读取type字段,再通过sources.DecodeConfig在源注册表中查找对应的工厂函数完成解码。
internal/sources/sources.go 定义了源注册机制的核心接口:
type SourceConfig interface { SourceConfigType() string Initialize(ctx context.Context, tracer trace.Tracer) (Source, error) } type Source interface { SourceType() string ToConfig() SourceConfig IsReadOnly() bool }- 每个具体数据源(bigquery、postgres、mysql、http 等)通过
Register(sourceType, factory)将自己注册进sourceRegistry(重复注册会被拒绝,返回false); - 启动解析时,
DecodeConfig按type字符串查表并调用对应工厂;若类型未知,会返回unknown source type错误,并提示"无法将 source 解析为对应类型"; Source.Initialize负责真正建立连接池,且连接初始化会被埋入名为toolbox/server/source/connect的 OpenTelemetry span(携带source_type、source_name属性),用于可观测性追踪。
Tool:数据源解锁的专用能力
kind: tool声明一个可被客户端调用的工具,必须通过source字段关联到某个已定义的 Source。internal/tools/tools.go 中的Tool接口定义了工具的全部能力面,包括:
GetName()/GetDescription():工具的元信息;GetSourceName():工具绑定的数据源;GetAnnotations(source):返回 MCP 工具注解(如readOnlyHint、destructiveHint),用于客户端展示与权限提示;Invoke(...):执行工具逻辑,入参为parameters.ParamValues与可选的AccessToken;Authorized(verifiedAuthServices):结合authRequired判断调用是否被授权;ValidateSource(source):校验工具与数据源的兼容性。
工具同样通过注册表机制(toolRegistry+Register)实现类型分发,internal/tools/tools.go 中的ErrUnknownToolType会在类型未知时被抛出。为了让工具编写者少写样板代码,仓库提供了 BaseTool 泛型基类,默认实现元信息、Manifest、参数获取等方法,具体工具只需覆写需要定制的行为。
Group:把工具组织成语义分组
kind: group将若干工具聚合成一个命名集合,供客户端按场景发现和编排。以 internal/prebuiltconfigs/tools/bigquery.yaml 为例,BigQuery 集成把工具分成两组:
data组:execute_sql、list_dataset_ids、list_table_ids、get_dataset_info、get_table_info、search_catalog,用于大规模数据探索与数据集管理;analytics组:analyze_contribution、ask_data_insights、forecast、search_catalog,用于数据智能分析与预测。
分组描述即"何时该用这组工具"的语义提示,能被 Agent 直接当作技能选择依据。
编写你的第一个集成:BigQuery 示例
完整继承 docs/en/integrations/bigquery/source.md 中的示例,一个使用应用默认凭据(ADC)的 BigQuery Source 如下:
kind: source name: my-bigquery-source type: "bigquery" project: "my-project-id" # location: "US" # Optional: Specifies the location for query jobs. # readOnly: false # Optional: Enforces read-only mode across all tools (defaults writeMode to "blocked"). # writeMode: "allowed" # One of: allowed, blocked, protected. Defaults to "allowed". # allowedDatasets: # Optional: Restricts tool access to a specific list of datasets. # - "my_dataset_1" # - "other_project.my_dataset_2" # impersonateServiceAccount: "service-account@project-id.iam.gserviceaccount.com" # Optional: Service account to impersonate # scopes: # Optional: List of OAuth scopes to request. # - "https://www.googleapis.com/auth/bigquery" # - "https://www.googleapis.com/auth/drive.readonly" # maxQueryResultRows: 50 # Optional: Limits the number of rows returned by queries. Defaults to 50. # maximumBytesBilled: 10737418240 # Optional: Per-query bytes scanned cap (in bytes). # apiEndpoint: "http://localhost:9050" # Optional: Override the BigQuery API endpoint (proxy or local emulator).若希望以客户端/终端用户的 OAuth 访问令牌代发请求,则使用useClientOAuth:
kind: source name: my-bigquery-client-auth-source type: "bigquery" project: "my-project-id" useClientOAuth: true # location: "US" # Optional: Specifies the location for query jobs. # readOnly: false # Optional: Enforces read-only mode across all tools (defaults writeMode to "blocked"). # writeMode: "allowed" # One of: allowed, blocked, protected. Defaults to "allowed". # allowedDatasets: # Optional: Restricts tool access to a specific list of datasets. # - "my_dataset_1" # - "other_project.my_dataset_2" # impersonateServiceAccount: "service-account@project-id.iam.gserviceaccount.com" # Optional: Service account to impersonate # scopes: # Optional: List of OAuth scopes to request. # - "https://www.googleapis.com/auth/bigquery" # - "https://www.googleapis.com/auth/drive.readonly" # maxQueryResultRows: 50 # Optional: Limits the number of rows returned by queries. Defaults to 50. # maximumBytesBilled: 10737418240 # Optional: Per-query bytes scanned cap (in bytes). # apiEndpoint: "http://localhost:9050" # Optional: Override the BigQuery API endpoint (proxy or local emulator).BigQuery Source 参数参考
| field | type | required | description |
|---|---|---|---|
| type | string | true | 必须为"bigquery"。 |
| project | string | true | 用于计费与默认项目的 Google Cloud 项目 ID。 |
| location | string | false | 执行查询作业的位置(如us、asia-northeast1),必须与查询中引用表的位置一致;无法确定时默认使用表的位置或US。 |
| readOnly | boolean | false | 是否全 Toolbox 只读。readOnly: true会协同 MCP 只读注解与工具抑制,并把writeMode默认置为blocked(也允许protected);若同时提供writeMode,必须与readOnly一致,否则启动报配置错误。 |
| writeMode | string | false | 写行为控制。allowed(默认)放行全部查询;blocked强制严格只读,注册时抑制可写工具、只允许SELECT;protected启用会话级执行(所有工具共享同一个 BigQuery 会话,可用CREATE TEMP TABLE做有状态操作,但保护永久数据集;不能与useClientOAuth: true同用,会话在无活动 24 小时或 7 天后自动终止)。 |
| allowedDatasets | []string | false | 允许访问的数据集白名单,越权访问会被拒绝,同时禁止数据集级操作和无法静态分析表访问的操作(如EXECUTE IMMEDIATE)。 |
| useClientOAuth | string | false | 设为'true'时从默认Authorization头转发客户端 OAuth 令牌;也可设为自定义头名(如X-My-Auth);空串或'false'关闭。 |
| scopes | []string | false | 凭据使用的 OAuth 2.0 作用域,缺省时使用默认作用域。 |
| impersonateServiceAccount | string | false | 模拟的服务账号邮箱,调用 BigQuery/Dataplex API 时使用,认证主体需持有目标账号的roles/iam.serviceAccountTokenCreator。 |
| maxQueryResultRows | int | false | 单次查询最多返回行数,默认 50。 |
| maximumBytesBilled | int64 | false | 单次查询最大计费字节数,超限的查询在执行前即失败。 |
| apiEndpoint | string | false | 覆盖 BigQuery API 端点(可用于代理或本地模拟器)。 |
| sqlCommenter | boolean | false | 覆盖全局--sql-commenter标志;设置时优先,缺省时沿用全局配置。 |
结合源码看认证与安全细节
- ADC 与作用域:默认使用应用默认凭据(ADC),在 GCE/GKE 上可通过
scopes显式指定(如https://www.googleapis.com/auth/bigquery或 internal/sources/sources.go 中定义的云平台全局作用域)。 - 客户端令牌:
useClientOAuth开启后,internal/tools/tools.go 的AccessToken.ParseBearerToken会校验Authorization头必须符合Bearer <token>格式,否则返回 401 客户端错误。 - 工具注解:工具通过注解向 MCP 客户端声明语义,internal/tools/tools.go 提供了
NewReadOnlyAnnotations(只读)、NewWriteAnnotations(非破坏性写入)、NewDestructiveAnnotations(破坏性写入)三组预设。 - 只读抑制:internal/tools/tools.go 的
ShouldSuppress在数据源只读时自动抑制可写工具(ReadOnlyHint: false),并提示未标注ReadOnlyHint的工具补充注解,以节省 Agent 上下文窗口。
通过环境变量注入密钥
所有配置项都支持${ENV_NAME}形式的环境变量替换,也可以带默认值${ENV_NAME:default}。cmd/internal/config.go 中的parseEnv在 YAML 解析前完成替换(注释内的占位符不会被替换)。官方预置配置大量使用这一机制,例如 internal/prebuiltconfigs/tools/bigquery.yaml:
kind: source name: bigquery-source type: bigquery project: ${BIGQUERY_PROJECT} location: ${BIGQUERY_LOCATION:} readOnly: ${BIGQUERY_READONLY:} writeMode: ${BIGQUERY_WRITE_MODE:} useClientOAuth: ${BIGQUERY_USE_CLIENT_OAUTH:false} scopes: ${BIGQUERY_SCOPES:} maxQueryResultRows: ${BIGQUERY_MAX_QUERY_RESULT_ROWS:50} impersonateServiceAccount: ${BIGQUERY_IMPERSONATE_SERVICE_ACCOUNT:} maximumBytesBilled: ${BIGQUERY_MAXIMUM_BYTES_BILLED:0} apiEndpoint: ${BIGQUERY_ENDPOINT:} --- kind: tool name: execute_sql type: bigquery-execute-sql source: bigquery-source description: Use this tool to execute sql statement. --- kind: group name: data description: Use these skills when you need to handle large-scale data exploration and dataset management. tools: - execute_sql - list_dataset_ids - list_table_ids - get_dataset_info - get_table_info - search_catalog最佳实践:将密钥(如 API Key、密码)放进${ENV_NAME}占位符而非硬编码在配置文件中,同时避免在 YAML 注释中填写真实密钥——注释中的占位符不会被替换。
预置配置:开箱即用的工具集
仓库通过 Go embed 把一组官方配置编译进二进制。internal/prebuiltconfigs/prebuiltconfigs.go 使用//go:embed tools/*.yaml加载internal/prebuiltconfigs/tools/目录下全部 YAML,并以文件名(去掉.yaml)作为集成类型键。当前内置了超过 40 种数据源配置,覆盖 BigQuery、PostgreSQL、MySQL、Cloud SQL(mysql/mssql/postgres 及各自 admin 版)、Spanner、Snowflake、Looker、ClickHouse、MongoDB、Redis、Valkey、SQLite、HTTP 等,可通过GetPrebuiltSources()获取完整列表。
以bigquery-source的预置工具为例,一个 Source 即解锁 9 个专用工具:bigquery-execute-sql、bigquery-conversational-analytics(数据洞察问答)、bigquery-analyze-contribution(多维指标贡献分析)、bigquery-forecast(时序预测)、bigquery-get-dataset-info、bigquery-get-table-info、bigquery-list-dataset-ids、bigquery-list-table-ids、bigquery-search-catalog——与 docs/en/integrations/bigquery/tools/ 中逐工具的文档一一对应。
自定义工具与参数校验
在预置工具之外,你可以在tools.yaml中追加自定义kind: tool声明。internal/server/config.go 的UnmarshalYAMLToolConfig会执行若干启动期校验:
name必须为 1~128 字符,且仅含 ASCII 字母、数字、下划线、连字符与点(见 NameValidation);authRequired与useClientOAuth互斥,只能二选一;parameters中的valueFromParam引用必须指向已定义的同列表参数,且不允许自引用;- 若开启
ignoreUnknownTools,未知工具类型会被跳过并告警,而不是让服务启动失败。
HTTP 集成:连接任意 HTTP 服务
除数据库外,Integration 也支持连接 HTTP 服务器,让 Agent 能访问任意 Web API。docs/en/integrations/http/source.md 给出了完整示例:
kind: source name: my-http-source type: http baseUrl: https://api.example.com/data timeout: 10s # default to 30s headers: Authorization: Bearer ${API_KEY} Content-Type: application/json queryParams: param1: value1 param2: value2 # returnFullError: false # disableSslVerification: false字段含义:
| field | type | required | description |
|---|---|---|---|
| type | string | true | 必须为"http"。 |
| baseUrl | string | true | HTTP 请求的基础 URL。 |
| timeout | string | false | 请求超时(如5s、1m,遵循 Gotime.ParseDuration),默认 30s。 |
| headers | map[string]string | false | 默认请求头。 |
| queryParams | map[string]string | false | 默认查询参数。 |
| returnFullError | bool | false | 非 2xx 响应时是否在错误信息中包含原始响应体,默认false。 |
| disableSslVerification | bool | false | 禁用 SSL 证书校验,仅建议本地开发使用,默认false。 |
| allowPrivateNetworks | bool | false | 是否允许访问环回与私有网络(RFC 1918 / link-local),默认false。 |
| allowedIpRanges | []string | false | 显式放行的 IP 或 CIDR 白名单。 |
| customBlockedIpRanges | []string | false | 显式封禁的 IP 或 CIDR 列表。 |
SSRF 防护(SSRF Guard)
HTTP Source 默认内置严格的 SSRF 与 DNS Rebinding(TOCTOU)防护,自动拦截并阻断指向以下范围的连接:私有 IP 段、环回地址(如127.0.0.1)、link-local(如云元数据服务169.254.169.254)、RFC 6598 共享地址段(100.64.0.0/10,常见于 Kubernetes 节点与 Pod 网络)、RFC 6890 协议专用段(192.0.0.0/24,如 NAT64/DNS64 组件)。需要放行内网或封禁特定主机时,用三个覆盖字段配置:
kind: source name: my-http-source type: http baseUrl: https://internal.corp/api allowedIpRanges: - 10.0.0.0/24 # Explicitly trust internal subnet customBlockedIpRanges: - 10.0.0.99 # Block a specific sensitive host inside the subnet集成文档的组织方式:如何在仓库中查阅每个集成
docs/en/integrations/下每个集成一个目录(如bigquery/、http/、postgres/、cloud-sql-pg/、snowflake/等),统一采用"连接配置 + 工具清单"的组织结构:
source.md:该数据源的连接配置说明,含kind: sourceYAML 示例、字段参考表、认证方式(ADC / 客户端 OAuth / 服务账号模拟)与高级用法;tools/:该集成解锁的每个工具的独立文档(参数、行为、示例);prebuilt-configs/(部分集成):官方预置配置说明;samples/(部分集成):端到端示例。
索引页 docs/en/integrations/_index.md 通过{{< list-db >}}短代码自动渲染全部集成列表。按需选取:配置连接看source.md,了解具体能力看对应tools/下的工具文档,想快速起步则直接引用internal/prebuiltconfigs/tools/<source>.yaml并用环境变量替换占位符。
完整工作流:从配置到客户端调用
- 在
tools.yaml中声明kind: source(数据库或 HTTP 连接),可同时追加自定义kind: tool与kind: group; - 服务启动时,internal/server/config.go 的
UnmarshalPrimitiveConfig逐文档解析 YAML,通过注册表(sources.Register/tools.Register)校验类型并构建配置,重复声明同名资源会报错; - Source 通过
Initialize建立连接池;工具按source字段绑定数据源,只读源(readOnly: true/writeMode: blocked)会在注册阶段抑制可写工具; - 客户端(IDE / Agent)通过 MCP 协议拉取工具 Manifest,按
authRequired与注解完成鉴权后调用Invoke执行查询、元数据发现或数据分析; - 所有操作可通过 internal/telemetry 输出的 OpenTelemetry span(如
toolbox/server/source/connect)与 SQL Commenter 标签进行追踪审计。
小结
MCP Toolbox 的 Integration 模型用最少的配置成本打通了"外部数据源 → MCP 工具集"这条链路:一次kind: source声明即可解锁该数据源的全部专用工具,预置配置让 BigQuery、PostgreSQL、HTTP 等几十种数据源开箱即用,注册表机制保证了类型的可扩展性与启动期校验。理解 Source、Tool、Group 三者关系,并掌握环境变量注入、认证方式与只读/写模式约束,你就能在 docs/en/integrations/ 的指引下快速为任意受支持数据源编写生产可用的集成配置。
【免费下载链接】mcp-toolboxMCP Toolbox for Databases is an open source MCP server for databases.项目地址: https://gitcode.com/GitHub_Trending/ge/mcp-toolbox
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考