跳转到内容

用于 ADK 的 MongoDB MCP 工具

在 ADK 中得到支持。PythonTypeScriptGo

The MongoDB MCP Server 将您的 ADK 代理连接到…… MongoDB 数据库以及 MongoDB Atlas 集群。这种集成功能使您的代理能够通过自然语言查询集合、管理数据库,并与 MongoDB Atlas 基础设施进行交互。

使用场景

  • 数据探索与分析:使用自然语言查询 MongoDB 集合,执行聚合操作,并分析文档结构,而无需手动编写复杂的查询语句。

  • 数据库管理:通过对话式命令列出数据库和集合、创建索引、管理用户以及监控数据库统计信息。

  • Atlas基础设施管理(Atlas Infrastructure Management):创建和管理 MongoDB Atlas 集群,配置访问权限列表,并直接从您的代理程序中查看性能建议。

先决条件

  • 用于数据库访问:一个 MongoDB 连接字符串(用于本地环境、自托管服务器或 Atlas 集群)
  • 用于 Atlas 的管理操作: A MongoDB Atlas 具有 API 凭据(客户端 ID 和密钥)的服务账户

与代理程序(agent)一起使用。

from google.adk.agents import Agent
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
from mcp import StdioServerParameters

# For database access, use a connection string:
CONNECTION_STRING = "mongodb://localhost:27017/myDatabase"

# For Atlas management, use API credentials:
# ATLAS_CLIENT_ID = "YOUR_ATLAS_CLIENT_ID"
# ATLAS_CLIENT_SECRET = "YOUR_ATLAS_CLIENT_SECRET"

root_agent = Agent(
    model="gemini-flash-latest",
    name="mongodb_agent",
    instruction="Help users query and manage MongoDB databases",
    tools=[
        McpToolset(
            connection_params=StdioConnectionParams(
                server_params=StdioServerParameters(
                    command="npx",
                    args=[
                        "-y",
                        "mongodb-mcp-server",
                        "--readOnly",  # Remove for write operations
                    ],
                    env={
                        # For database access, use:
                        "MDB_MCP_CONNECTION_STRING": CONNECTION_STRING,
                        # For Atlas management, use:
                        # "MDB_MCP_API_CLIENT_ID": ATLAS_CLIENT_ID,
                        # "MDB_MCP_API_CLIENT_SECRET": ATLAS_CLIENT_SECRET,
                    },
                ),
                timeout=30,
            ),
        )
    ],
)
import { LlmAgent, MCPToolset } from "@google/adk";

// For database access, use a connection string:
const CONNECTION_STRING = "mongodb://localhost:27017/myDatabase";

// For Atlas management, use API credentials:
// const ATLAS_CLIENT_ID = "YOUR_ATLAS_CLIENT_ID";
// const ATLAS_CLIENT_SECRET = "YOUR_ATLAS_CLIENT_SECRET";

const rootAgent = new LlmAgent({
    model: "gemini-flash-latest",
    name: "mongodb_agent",
    instruction: "Help users query and manage MongoDB databases",
    tools: [
        new MCPToolset({
            type: "StdioConnectionParams",
            serverParams: {
                command: "npx",
                args: [
                    "-y",
                    "mongodb-mcp-server",
                    "--readOnly", // Remove for write operations
                ],
                env: {
                    // For database access, use:
                    MDB_MCP_CONNECTION_STRING: CONNECTION_STRING,
                    // For Atlas management, use:
                    // MDB_MCP_API_CLIENT_ID: ATLAS_CLIENT_ID,
                    // MDB_MCP_API_CLIENT_SECRET: ATLAS_CLIENT_SECRET,
                },
            },
        }),
    ],
});

export { rootAgent };
package main

import (
    "context"
    "log"
    "os"
    "os/exec"

    "github.com/modelcontextprotocol/go-sdk/mcp"
    "google.golang.org/genai"

    "google.golang.org/adk/v2/agent"
    "google.golang.org/adk/v2/agent/llmagent"
    "google.golang.org/adk/v2/cmd/launcher"
    "google.golang.org/adk/v2/cmd/launcher/full"
    "google.golang.org/adk/v2/model/gemini"
    "google.golang.org/adk/v2/tool"
    "google.golang.org/adk/v2/tool/mcptoolset"
)

// For database access, use a connection string:
const connectionString = "mongodb://localhost:27017/myDatabase"

// For Atlas management, use API credentials:
// const atlasClientID = "YOUR_ATLAS_CLIENT_ID"
// const atlasClientSecret = "YOUR_ATLAS_CLIENT_SECRET"

func main() {
    ctx := context.Background()

    model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{
        APIKey: os.Getenv("GOOGLE_API_KEY"),
    })
    if err != nil {
        log.Fatalf("Failed to create the model: %v", err)
    }

    args := []string{
        "-y", "mongodb-mcp-server",
        "--readOnly", // Remove for write operations
    }

    server := exec.CommandContext(ctx, "npx", args...)
    // Forward only what npx needs, plus the MongoDB credentials. The parent
    // environment may hold unrelated secrets, such as the GOOGLE_API_KEY above.
    server.Env = []string{
        // For database access, use:
        "MDB_MCP_CONNECTION_STRING=" + connectionString,
        // For Atlas management, use:
        // "MDB_MCP_API_CLIENT_ID=" + atlasClientID,
        // "MDB_MCP_API_CLIENT_SECRET=" + atlasClientSecret,
    }
    for _, k := range []string{
        "PATH", "HOME", // POSIX
        "APPDATA", "LOCALAPPDATA", "TEMP", "USERPROFILE", // Windows
    } {
        if v, ok := os.LookupEnv(k); ok {
            server.Env = append(server.Env, k+"="+v)
        }
    }

    mongodb, err := mcptoolset.New(mcptoolset.Config{
        Transport: &mcp.CommandTransport{Command: server},
    })
    if err != nil {
        log.Fatalf("Failed to create the MongoDB tool set: %v", err)
    }

    rootAgent, err := llmagent.New(llmagent.Config{
        Model:       model,
        Name:        "mongodb_agent",
        Instruction: "Help users query and manage MongoDB databases",
        Toolsets:    []tool.Toolset{mongodb},
    })
    if err != nil {
        log.Fatalf("Failed to create the agent: %v", err)
    }

    l := full.NewLauncher()
    cfg := &launcher.Config{AgentLoader: agent.NewSingleLoader(rootAgent)}
    if err := l.Execute(ctx, cfg, os.Args[1:]); err != nil {
        log.Fatalf("Run failed: %v\n\n%s", err, l.CommandLineSyntax())
    }
}

可用的工具

MongoDB数据库工具

工具 描述
find 对 MongoDB 集合执行查找查询(find query)。
aggregate 对 MongoDB 集合执行聚合操作(即对集合中的数据进行处理,以生成新的数据结构或结果)。
count 获取集合中文档的数量
list-databases 列出与 MongoDB 连接相关的所有数据库。
list-collections 列出给定数据库中的所有集合。
collection-schema 描述一个集合(collection)的架构(schema)。
collection-indexes 描述某个集合中的索引(indexes)。
insert-many 将文档插入到集合中。
update-many 更新符合特定过滤条件的文档。
delete-many 删除符合特定过滤条件的文档。
create-collection 创建一个新的集合。
drop-collection 从数据库中删除一个集合(collection)。
drop-database 删除一个数据库
create-index 为某个集合创建一个索引。
drop-index 从集合中删除一个索引。
rename-collection 重命名一个集合(collection)。
db-stats 获取数据库的统计信息
explain 获取查询执行统计信息
export 将查询结果以 EJSON 格式导出

MongoDB Atlas 工具

注意:

Atlas 工具需要 API 凭据。请进行相应的设置。 MDB_MCP_API_CLIENT_ID 和 MDB_MCP_API_CLIENT_SECRET 需要启用这些功能的环境变量。

工具 描述
atlas-list-orgs 列出 MongoDB Atlas 组织(Organizations)
atlas-list-projects 列出 MongoDB Atlas 项目
atlas-list-clusters 列出 MongoDB Atlas 集群
atlas-inspect-cluster 检查集群的元数据
atlas-list-db-users 列出数据库用户
atlas-create-free-cluster 创建一个免费的 Atlas 集群。
atlas-create-project 创建一个 Atlas 项目。
atlas-create-db-user 创建一个数据库用户
atlas-create-access-list 配置 IP 访问列表
atlas-inspect-access-list 查看 IP 访问列表条目
atlas-list-alerts 列出 Atlas 警报信息
atlas-get-performance-advisor 获取性能优化建议

配置

环境变量

变量 描述
MDB_MCP_CONNECTION_STRING 用于访问数据库的 MongoDB 连接字符串
MDB_MCP_API_CLIENT_ID 用于 Atlas 工具的 Atlas API 客户端 ID
MDB_MCP_API_CLIENT_SECRET 用于 Atlas 工具的 Atlas API 客户端密钥
MDB_MCP_READ_ONLY 启用只读模式(Enable read-only mode)true 或者 false)
MDB_MCP_DISABLED_TOOLS 用于禁用的工具的列表(工具之间用逗号分隔)。
MDB_MCP_LOG_PATH 日志文件的存储目录

只读模式

The --readOnly 该标志(flag)限制服务器仅执行读取、连接以及元数据操作。这有效地防止了任何创建(create)、更新(update)或删除(delete)操作的发生,从而确保数据探索过程的安全性,避免了数据被意外修改的风险。

禁用这些工具

您可以使用相应的方法来禁用特定的工具或功能类别。 MDB_MCP_DISABLED_TOOLS:

  • 工具名称: find, aggregate, insert-many等等。
  • 类别: atlas (所有 Atlas 工具) mongodb (所有数据库工具)
  • 操作类型: create, update, delete, read, metadata

其他资源