资讯动态

MCP Toolbox 的 MongoDB 数据源接入指南:配置、连接与九大数据操作工具实战

发布时间:2026/9/14 23:26:04 来源:尧图企业网站定制
MCP Toolbox 的 MongoDB 数据源接入指南配置、连接与九大数据操作工具实战【免费下载链接】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 中的 MongoDB 集成从最核心的mongodb类型 Source 配置入手完整讲解连接串URI的定义方式、连接初始化与连通性校验的源码实现并逐一剖析基于该数据源暴露给 LLM 的 9 个 MongoDB 操作工具find / find-one / aggregate / insert-one / insert-many / update-one / update-many / delete-one / delete-many的配置字段、模板参数与实战示例。读完本文你将能够在 MCP Toolbox 配置体系中独立声明一个 MongoDB 数据源并为你的 Agent 编排一套安全、可参数化的 MongoDB 增删改查工具。为什么选择 MongoDB 作为 Toolbox 数据源MongoDB 是一款广受欢迎的 NoSQL 数据库以灵活的、类 JSON 的文档document形式存储数据天然契合 MCP Toolbox 的把数据库能力暴露给 LLM的设计目标文档结构无需预定义 schema便于开发与水平扩展。此外MongoDB 平台不仅能承载通用业务数据需求还支持向量搜索VectorSearch使得业务数据与检索所用的向量嵌入embeddings可以存放在同一份文档中这为基于 Toolbox 构建检索增强生成RAG类 Agent 提供了便利。在 MCP Toolbox 中MongoDB 被实现为一种Source数据源Source 负责建立并维护与 MongoDB 实例的连接而工具Tool则通过引用该 Source 来执行具体操作。两者通过 YAML 配置文件声明核心说明见 docs/en/integrations/mongodb/source.md。快速开始声明一个 MongoDB Source在 Toolbox 的配置体系中数据源通过kind: source的 YAML 片段声明。官方文档给出的 MongoDB 最小配置如下kind: source name: my-mongodb type: mongodb uri: mongodbsrv://username:passwordhost.mongodb.net字段参考fieldtyperequireddescriptiontypestringtrue必须为mongodb。uristringtrue连接 MongoDB 实例所用的连接串connection string。其中name字段如示例中的my-mongodb为数据源的唯一标识后续所有引用该数据源的工具都通过source: my-mongodb来关联它。从源码看配置解析MongoDB Source 的配置结构体定义在 internal/sources/mongodb/mongodb.gotype Config struct { Name string yaml:name validate:required Type string yaml:type validate:required Uri string yaml:uri validate:required // MongoDB Atlas connection URI }三个字段均标记了validate:required即name、type、uri缺一不可Uri字段的注释明确指出其形态是 MongoDB Atlas 连接 URI。源码中通过init()将mongodb类型注册进全局 Source 注册表func init() { if !sources.Register(SourceType, newConfig) { panic(fmt.Sprintf(source type %q already registered, SourceType)) } }其中SourceType常量定义为mongodb。注册表机制实现在 internal/sources/sources.gosources.Register以类型名为 key 保存配置工厂函数若类型重复注册则返回false并触发 panic。启动时 Toolbox 会依据type: mongodb找到newConfig工厂通过 YAML 解码器将配置片段反序列化为上述Config结构体。连接串URI说明uri即标准的 MongoDB 连接串。示例中使用了 MongoDB Atlas 的 SRV 格式mongodbsrv://username:passwordhost.mongodb.net其含义是mongodbsrv://使用 DNS SRV 记录自动发现副本集或分片集群成员Atlas 推荐username:password认证凭据可替换为 Atlas 数据库用户host.mongodb.netAtlas 集群的 SRV 主机名。同时该连接串也兼容自托管 MongoDB 的标准格式mongodb://host:port。连接串中还可以追加认证数据库、TLS、副本集等标准查询参数具体由 MongoDB 官方驱动解析。连接初始化与连通性校验源码级解析当配置被解析成功后Toolbox 会调用Config.Initialize()建立真实连接。该方法的实现同样位于 internal/sources/mongodb/mongodb.go核心流程如下创建驱动客户端调用initMongoDBClient()使用options.Client().ApplyURI(uri).SetAppName(userAgent)构建mongo.Client来自go.mongodb.org/mongo-driver/v2。SetAppName将请求上下文中携带的 User-Agent 附加到客户端便于在 MongoDB 服务端识别连接来源服务于遥测与审计。创建追踪 Span连接初始化会被包裹在名为toolbox/server/source/connect的 OpenTelemetry span 中属性包含source_type与source_name使连接过程可观测见 internal/sources/sources.go 的InitConnectionSpan。Ping 校验client.Ping(ctx, nil)验证连通性若失败则主动Disconnect并返回unable to connect successfully错误。这保证了配置错误如凭据无效、网络不通在启动阶段即可被发现而不是等到工具被调用时才暴露。连接建立后Source结构体持有Config与*mongo.Client并通过MongoClient()方法向工具层暴露驱动客户端。此外IsReadOnly()返回false表明该数据源支持写操作插入、更新、删除这也是下方写类工具存在的前提。可用工具总览在 MCP Toolbox 中mongodb数据源配套了 9 个工具完整目录见 docs/en/integrations/mongodb/tools/工具类型分类功能简述mongodb-find查询按过滤器检索多个文档支持投影、排序、限量mongodb-find-one查询检索匹配过滤器的第一个文档mongodb-aggregate查询执行多阶段聚合管道支持$out/$merge写保护mongodb-insert-one写入插入单个新文档返回新文档_idmongodb-insert-many写入批量插入多个文档返回每个新文档的_idmongodb-update-one更新更新匹配过滤器的第一个文档支持 upsertmongodb-update-many更新更新所有匹配过滤器的文档支持 upsertmongodb-delete-one删除删除匹配过滤器的第一个文档mongodb-delete-many删除删除所有匹配过滤器的文档每个工具都通过kind: tool的 YAML 片段声明type取上表中的工具类型source指向数据源名称my-mongodb。下面按功能分类逐一展开。查询类工具mongodb-find灵活的多文档检索mongodb-find用于查询集合并检索匹配指定过滤器的文档支持通过**投影projection**挑选字段、**排序sorting**定义顺序、**限量limiting**控制返回条数返回匹配文档的 JSON 数组。完整参考见 docs/en/integrations/mongodb/tools/mongodb-find.md。示例从customers集合中查找居住在指定城市的用户最多返回 10 条按姓氏排序仅返回姓、名、邮箱kind: tool name: find_local_customers type: mongodb-find source: my-mongo-source description: Finds customers by city, sorted by last name. database: crm collection: customers limit: 10 filterPayload: | { address.city: {{json .city}} } filterParams: - name: city type: string description: The city to search for customers in. projectPayload: | { first_name: 1, last_name: 1, email: 1, _id: 0 } sortPayload: | { last_name: {{json .sort_order}} } sortParams: - name: sort_order type: integer description: The sort order (1 for ascending, -1 for descending).核心字段参考fieldtyperequireddescriptiontypestringtrue必须为mongodb-find。sourcestringtrue要使用的mongodb数据源名称。descriptionstringtrue传递给 LLM 的工具描述。databasestringtrue要查询的 MongoDB 数据库名。collectionstringfalse要查询的集合名。与collectionAllowedValues互斥若省略必须在运行时通过collection参数提供并可用collectionAllowedValues限制可选值。collectionAllowedValueslistfalse当collection在运行时提供时允许 Agent 选择的集合名列表。仅在省略collection时配置。filterPayloadstringtrue选择返回文档的 MongoDB 查询过滤器文档使用{{json .param_name}}做模板替换。filterParamslistfalse定义filterPayload中所用变量的参数对象列表。projectPayloadstringfalse可选投影文档指定结果中包含1或排除0的字段。projectParamslistfalse供projectPayload使用的参数对象列表。sortPayloadstringfalse可选的排序文档1 为升序-1 为降序。sortParamslistfalse供sortPayload使用的参数对象列表。limitintegerfalse可选整数指定返回文档的最大数量。模板机制说明{{json .param_name}}是 Go 模板语法运行时由 LLM 以参数形式如city、sort_order传入实际值经json函数安全地序列化后嵌入过滤器文档从而避免拼串导致的注入风险。filterPayload与projectPayload、sortPayload均为字符串字段语法上完全等价于 MongoDB 原生的查询/投影/排序文档。源码实现Find()方法见 internal/sources/mongodb/mongodb.go先用bson.UnmarshalExtJSON将过滤器字符串解析为bson.D再调用驱动的Collection.Find()最终经parseData()将游标结果序列化为 JSON 数组返回。mongodb-find-one单文档精确检索mongodb-find-one检索匹配过滤器的第一个文档。若过滤器匹配多个文档仅返回数据库找到的第一条。其配置字段与mongodb-find相同filterPayload / filterParams / database / collection 等返回结果为包含单个文档的 JSON 数组。对应源码FindOne()internal/sources/mongodb/mongodb.go直接使用驱动的Collection.FindOne()并把解码后的文档转换为 Extended JSON 后再转为普通 JSON 返回。mongodb-aggregate最强大的多阶段聚合mongodb-aggregate是 MongoDB 最强大的查询工具通过多阶段管道对数据进行分组、过滤、重塑和计算。管道的核心是pipelinePayload必须是一个JSON 数组的管道阶段文档字符串返回管道最终阶段产出的 JSON 数组。完整参考见 docs/en/integrations/mongodb/tools/mongodb-aggregate.md。示例统计每个分类下状态为 active 的产品的平均价格与总数并按均价降序排列kind: tool name: get_category_stats type: mongodb-aggregate source: my-mongo-source description: Calculates average price and count of products, grouped by category. database: ecommerce collection: products readOnly: true pipelinePayload: | [ { $match: { status: {{json .status_filter}} } }, { $group: { _id: $category, average_price: { $avg: $price }, item_count: { $sum: 1 } } }, { $sort: { average_price: -1 } } ] pipelineParams: - name: status_filter type: string description: The product status to filter by (e.g., active).字段参考fieldtyperequireddescriptiontypestringtrue必须为mongodb-aggregate。sourcestringtrue要使用的mongodb数据源名称。descriptionstringtrue传递给 LLM 的工具描述。databasestringtrue包含集合的 MongoDB 数据库名。collectionstringfalse运行聚合的集合名与collectionAllowedValues互斥。collectionAllowedValueslistfalse运行时集合名白名单。pipelinePayloadstringtrue聚合阶段文档的 JSON 数组字符串支持{{json .param_name}}模板。pipelineParamslisttrue定义pipelinePayload中变量的参数对象列表。canonicalboolfalse决定管道字符串使用 MongoDB 的 Canonical 还是 Relaxed Extended JSON 格式解析。readOnlyboolfalse若为true管道包含写阶段$out或$merge时工具直接失败。默认false。readOnly 安全机制源码级Aggregate()方法internal/sources/mongodb/mongodb.go在readOnly为真时会遍历管道每个 stage检查是否出现$merge或$out键一旦发现即返回this is not a read-only pipeline错误从源头阻断通过聚合管道向集合写入数据的风险。这是值得在所有对外暴露的聚合工具上启用的安全开关。写入类工具mongodb-insert-one插入单文档mongodb-insert-one向指定集合插入单个新文档唯一必填运行时参数为data——一个包含待插入 JSON 对象的字符串。成功插入后返回新文档的唯一_id。配置示例见 docs/en/integrations/mongodb/tools/mongodb-insert-one.mdkind: tool name: create_new_user type: mongodb-insert-one source: my-mongo-source description: Creates a new user record in the database. database: user_data collection: users canonical: falseLLM 调用时通过data参数传入 JSON 字符串tool_code: create_new_user(data{email: new.userexample.com, name: Jane Doe, status: active})字段参考fieldtyperequireddescriptiontypestringtrue必须为mongodb-insert-one。sourcestringtrue要使用的mongodb数据源名称。descriptionstringtrue传递给 LLM 的工具描述。databasestringtrue包含集合的数据库名。collectionstringfalse插入文档的集合名与collectionAllowedValues互斥。collectionAllowedValueslistfalse运行时集合名白名单。canonicalboolfalse决定data字符串使用 Canonical 还是 Relaxed Extended JSON 解析默认false。mongodb-insert-many批量插入mongodb-insert-many通过单次批量操作向集合插入多个新文档适合一次性灌入大量数据。data参数必须是 JSON 数组字符串成功插入后返回每个新文档_id组成的 JSON 数组。配置示例见 docs/en/integrations/mongodb/tools/mongodb-insert-many.mdkind: tool name: log_batch_events type: mongodb-insert-many source: my-mongo-source description: Inserts a batch of event logs into the database. database: logging collection: events canonical: trueLLM 调用示例tool_code: log_batch_events(data[{event: login, user: user1}, {event: click, user: user2}, {event: logout, user: user1}])字段参考与mongodb-insert-one一致仅type必须为mongodb-insert-many。源码层面InsertMany()internal/sources/mongodb/mongodb.go调用Collection.InsertMany()并返回res.InsertedIDs即每个新文档的_id列表InsertOne()同文件 L215-L227返回单个res.InsertedID。更新类工具mongodb-update-one更新单文档mongodb-update-one通过filterPayload定位文档并应用updatePayload中的修改若过滤器匹配多个文档仅更新第一个。upsert: true时若无匹配文档则新建一条。配置示例见 docs/en/integrations/mongodb/tools/mongodb-update-one.mdkind: tool name: update_inventory_item type: mongodb-update-one source: my-mongo-source description: Use this tool to update an items stock and status in the inventory. database: products collection: inventory filterPayload: | { item: {{json .item_name}} } filterParams: - name: item_name type: string description: The name of the item to update. updatePayload: | { $set: { stock: {{json .new_stock}}, status: {{json .new_status}} } } updateParams: - name: new_stock type: integer description: The new stock quantity. - name: new_status type: string description: The new status of the item (e.g., In Stock, Backordered). canonical: false upsert: true字段参考fieldtyperequireddescriptiontypestringtrue必须为mongodb-update-one。sourcestringtrue要使用的mongodb数据源名称。descriptionstringtrue传递给 LLM 的工具描述。databasestringtrue包含集合的数据库名。collectionstringfalse更新文档的集合名与collectionAllowedValues互斥。collectionAllowedValueslistfalse运行时集合名白名单。filterPayloadstringtrue选择待更新文档的查询过滤器Go 模板语法用{{json .param_name}}插入参数。filterParamslistfalse定义filterPayload变量的参数列表。updatePayloadstringtrueMongoDB 更新文档常使用$set等更新操作符同样支持模板。updateParamslisttrue定义updatePayload变量的参数列表。canonicalboolfalse决定updatePayload的解析格式。Canonical对类型表示更严格如{$numberInt: 42}Relaxed更宽松如直接写42。默认false。upsertboolfalse若为true没有文档匹配filterPayload时创建新文档。默认false。源码UpdateOne()internal/sources/mongodb/mongodb.go最终返回res.ModifiedCount被修改的文档数并通过options.UpdateOne().SetUpsert(upsert)透传 upsert 语义。mongodb-update-many批量更新mongodb-update-many更新集合中所有匹配过滤器的文档返回由三个整数组成的数组[ModifiedCount, UpsertedCount, MatchedCount]——即被修改数、被 upsert 数、被匹配数便于 Agent 感知操作的精确影响面。配置示例见 docs/en/integrations/mongodb/tools/mongodb-update-many.mdkind: tool name: apply_category_discount type: mongodb-update-many source: my-mongo-source description: Use this tool to apply a discount to all items in a given category. database: products collection: inventory filterPayload: | { category: {{json .category_name}} } filterParams: - name: category_name type: string description: The category of items to update. updatePayload: | { $mul: { price: {{json .discount_multiplier}} }, $set: { on_sale: true } } updateParams: - name: discount_multiplier type: number description: The multiplier to apply to the price (e.g., 0.8 for a 20% discount). canonical: false upsert: false字段参考与mongodb-update-one相同仅type必须为mongodb-update-manycanonical同时作用于filterPayload与updatePayload的解析。源码UpdateMany()internal/sources/mongodb/mongodb.go返回[]any{res.ModifiedCount, res.UpsertedCount, res.MatchedCount}与文档描述完全一致。删除类工具mongodb-delete-one删除单文档mongodb-delete-one是破坏性操作删除集合中匹配过滤器的第一个文档适合按唯一 ID 移除指定用户账号或单个库存条目。返回被删除的文档数找到并删除则为1无匹配则为0。配置示例见 docs/en/integrations/mongodb/tools/mongodb-delete-one.mdkind: tool name: delete_user_account type: mongodb-delete-one source: my-mongo-source description: Permanently deletes a user account by their email address. database: user_data collection: users filterPayload: | { email: {{json .email_address}} } filterParams: - name: email_address type: string description: The email of the user account to delete.字段参考fieldtyperequireddescriptiontypestringtrue必须为mongodb-delete-one。sourcestringtrue要使用的mongodb数据源名称。descriptionstringtrue传递给 LLM 的工具描述。databasestringtrue包含集合的数据库名。collectionstringfalse删除文档的集合名与collectionAllowedValues互斥。collectionAllowedValueslistfalse运行时集合名白名单。filterPayloadstringtrue选择待删除文档的过滤器文档支持{{json .param_name}}模板。filterParamslistfalse定义filterPayload变量的参数列表。mongodb-delete-many批量删除mongodb-delete-many删除集合中所有匹配过滤器的文档返回被删除的文档总数。与delete-one不同的是源码DeleteMany()internal/sources/mongodb/mongodb.go在删除数量为 0 时会返回no document found错误帮助 Agent 明确感知未找到目标这一业务状态而非静默返回 0。由于删除是不可逆操作建议在description中明确标注永久删除等警示语并尽量让filterPayload绑定到唯一字段如_id、email降低误删风险。底层实现BSON 与 Extended JSON 的双重转换细心的读者会发现多个工具都涉及canonical字段。这源于 MongoDB 驱动与 JSON 之间的类型映射问题。源码中所有入参过滤器、管道、文档数据均通过bson.UnmarshalExtJSON解析出参则统一经过parseData()internal/sources/mongodb/mongodb.go处理先用bson.MarshalExtJSON将 BSON 文档转为 Extended JSON再json.Unmarshal为普通 Go 结构后返回给调用方。Relaxed Extended JSONcanonical: false默认允许以自然形式书写类型如42、2024-01-01更易读、更贴近普通 JSON适合绝大多数场景Canonical Extended JSONcanonical: true强制显式类型包装如{$numberInt: 42}、{$date: ...}类型语义更严格适合需要精确控制类型表示的场景。正是这一层转换保证了 LLM 传入的字符串参数可以被严格解析为 MongoDB 原生类型如将{{json .item_name}}安全地嵌入过滤器同时返回结果也始终是标准 JSON便于 LLM 理解。从源码结构看可扩展性与约束从 internal/sources/mongodb/mongodb.go 的整体结构可以推断出以下设计要点接口契约清晰Config实现了sources.SourceConfig接口SourceConfigType()与Initialize()Source实现了sources.Source接口SourceType()、ToConfig()、IsReadOnly()与 internal/sources/sources.go 中定义的数据源抽象完全对齐新增其他数据库数据源只需遵循同一套契约读写统一但可控IsReadOnly()返回false表示支持全部操作但可通过mongodb-aggregate的readOnly: true单独收紧某工具的写能力实现数据源整体可写、特定工具只读的细粒度安全策略集合范围控制collectionAllowedValues允许在运行时由 LLM 动态选择集合名同时把可选集合限定在白名单内避免 Agent 触碰敏感集合——这是一种值得推广的访问控制模式可观测性内置连接初始化自动纳入 OpenTelemetry 追踪配合SetAppName注入的 User-Agent连接与调用链均可被监控与审计。小结在 MCP Toolbox 中接入 MongoDB 仅需两步先用kind: sourcetype: mongodb声明数据源并给出连接串再通过 9 个mongodb-*工具为 LLM 编排查询、聚合、插入、更新、删除能力。官方文档docs/en/integrations/mongodb/source.md 及各工具文档提供了全部字段参考与可复制示例而源码 internal/sources/mongodb/mongodb.go 则揭示了连接校验、Extended JSON 解析、只读保护与返回语义等底层细节。建议在实际部署时为uri使用环境变量或密钥管理避免明文凭据、为聚合工具开启readOnly: true、为所有写/删工具设计窄化且带白名单的过滤器从而让 MongoDB 数据源在 Agent 场景下既强大又可控。【免费下载链接】mcp-toolboxMCP Toolbox for Databases is an open source MCP server for databases.项目地址: https://gitcode.com/GitHub_Trending/ge/mcp-toolbox创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价