> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP 数据库工具箱集成

> 使用 LangChain Python 集成 MCP 数据库工具箱。

使用 MCP 工具箱将您的数据库与 LangChain 代理集成。

## 概述

[MCP 数据库工具箱](https://github.com/googleapis/genai-toolbox) 是一个开源的数据库 MCP 服务器。它在设计时考虑了企业级和生产质量。它通过处理连接池、身份验证等复杂性，使您能够更轻松、更快速、更安全地开发工具。

工具箱工具可以无缝集成到 LangChain 应用程序中。有关[入门](https://googleapis.github.io/genai-toolbox/getting-started/local_quickstart/)或[配置](https://googleapis.github.io/genai-toolbox/getting-started/configure/) MCP 工具箱的更多信息，请参阅[文档](https://googleapis.github.io/genai-toolbox/getting-started/introduction/)。

![架构](https://raw.githubusercontent.com/googleapis/genai-toolbox/refs/heads/main/docs/en/getting-started/introduction/architecture.png)

## 设置

本指南假设您已完成以下操作：

1. 已安装 [Python 3.9+](https://wiki.python.org/moin/BeginnersGuide/Download) 和 [pip](https://pip.pypa.io/en/stable/installation/)。
2. 已安装 [PostgreSQL 16+ 和 `psql` 命令行客户端](https://www.postgresql.org/download/)。

### 1. 设置您的数据库

首先，让我们设置一个 PostgreSQL 数据库。我们将创建一个新数据库、一个用于 MCP 工具箱的专用用户，以及一个包含一些示例数据的 `hotels` 表。

使用 `psql` 命令连接到 PostgreSQL。您可能需要根据您的 PostgreSQL 设置调整命令（例如，如果需要指定主机或不同的超级用户）。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
psql -U postgres
```

现在，运行以下 SQL 命令来创建用户、数据库并授予权限：

```sql theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
CREATE USER toolbox_user WITH PASSWORD 'my-password';
CREATE DATABASE toolbox_db;
GRANT ALL PRIVILEGES ON DATABASE toolbox_db TO toolbox_user;
ALTER DATABASE toolbox_db OWNER TO toolbox_user;
```

使用新用户连接到新创建的数据库：

```sql theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
\c toolbox_db toolbox_user
```

最后，创建 `hotels` 表并插入一些数据：

```sql theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
CREATE TABLE hotels(
  id            INTEGER NOT NULL PRIMARY KEY,
  name          VARCHAR NOT NULL,
  location      VARCHAR NOT NULL,
  price_tier    VARCHAR NOT NULL,
  booked        BIT     NOT NULL
);

INSERT INTO hotels(id, name, location, price_tier, booked)
VALUES
  (1, 'Hilton Basel', 'Basel', 'Luxury', B'0'),
  (2, 'Marriott Zurich', 'Zurich', 'Upscale', B'0'),
  (3, 'Hyatt Regency Basel', 'Basel', 'Upper Upscale', B'0');
```

现在，您可以通过输入 `\q` 退出 `psql`。

### 2. 安装 MCP 工具箱

接下来，我们将安装 MCP 工具箱，在 `tools.yaml` 配置文件中定义我们的工具，并运行 MCP 工具箱服务器。

对于 **macOS** 用户，最简单的安装方式是使用 [Homebrew](https://formulae.brew.sh/formula/mcp-toolbox)：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
brew install mcp-toolbox
```

对于其他平台，[下载适用于您的操作系统和架构的最新 MCP 工具箱二进制文件。](https://github.com/googleapis/genai-toolbox/releases)

创建一个 `tools.yaml` 文件。此文件定义了 MCP 工具箱可以连接的数据源以及它可以向您的代理公开的工具。对于生产用途，请始终使用环境变量来存储密钥。

```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
sources:
  my-pg-source:
    kind: postgres
    host: 127.0.0.1
    port: 5432
    database: toolbox_db
    user: toolbox_user
    password: my-password

tools:
  search-hotels-by-location:
    kind: postgres-sql
    source: my-pg-source
    description: 根据位置搜索酒店。
    parameters:
      - name: location
        type: string
        description: 酒店的位置。
    statement: SELECT id, name, location, price_tier FROM hotels WHERE location ILIKE '%' || $1 || '%';
  book-hotel:
    kind: postgres-sql
    source: my-pg-source
    description: >-
        通过 ID 预订酒店。如果酒店预订成功，返回确认消息。
    parameters:
      - name: hotel_id
        type: integer
        description: 要预订的酒店 ID。
    statement: UPDATE hotels SET booked = B'1' WHERE id = $1;

toolsets:
  hotel_toolset:
    - search-hotels-by-location
    - book-hotel
```

现在，在一个单独的终端窗口中，启动 MCP 工具箱服务器。如果您是通过 Homebrew 安装的，只需运行 `toolbox`。如果您是手动下载的二进制文件，则需要从保存它的目录运行 `./toolbox`：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
toolbox --tools-file "tools.yaml"
```

MCP 工具箱默认将在 `http://127.0.0.1:5000` 上启动，如果您对 `tools.yaml` 文件进行更改，它将热重载。

## 实例化

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
!pip install toolbox-langchain
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from toolbox_langchain import ToolboxClient

with ToolboxClient("http://127.0.0.1:5000") as client:
    search_tool = await client.aload_tool("search-hotels-by-location")
```

## 调用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from toolbox_langchain import ToolboxClient

with ToolboxClient("http://127.0.0.1:5000") as client:
    search_tool = await client.aload_tool("search-hotels-by-location")
    results = search_tool.invoke({"location": "Basel"})
    print(results)
```

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{"id":1,"location":"Basel","name":"Hilton Basel","price_tier":"Luxury"},{"id":3,"location":"Basel","name":"Hyatt Regency Basel","price_tier":"Upper Upscale"}]
```

## 在代理中使用

现在进入有趣的部分！我们将安装所需的 LangChain 包，并创建一个可以使用我们在 MCP 工具箱中定义的工具的代理。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU toolbox-langchain langgraph langchain-google-vertexai
```

安装好包后，我们可以定义我们的代理。我们将使用 `ChatVertexAI` 作为模型，并使用 `ToolboxClient` 来加载我们的工具。来自 `langchain.agents` 的 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 创建了一个健壮的代理，可以推理应该调用哪些工具。

**注意：** 在执行下面的代码之前，请确保您的 MCP 工具箱服务器正在单独的终端中运行。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent
from langchain_google_vertexai import ChatVertexAI
from langgraph.checkpoint.memory import MemorySaver
from toolbox_langchain import ToolboxClient


prompt = """
你是一个有用的酒店助手。你处理酒店搜索和预订。
当用户搜索酒店时，列出找到的每个酒店的完整详细信息：id、name、location 和 price_tier。
始终使用酒店 ID 进行预订操作。
对于任何预订，请提供清晰的确认消息。
不要向用户请求澄清或确认；直接执行请求的操作。
"""


async def run_queries(agent_executor):
    config = {"configurable": {"thread_id": "hotel-thread-1"}}

    # --- 查询 1：搜索酒店 ---
    query1 = "我需要在巴塞尔找一家酒店。"
    print(f'\n--- 用户: "{query1}" ---')
    inputs1 = {"messages": [("user", prompt + query1)]}
    async for event in agent_executor.astream_events(
        inputs1, config=config, version="v2"
    ):
        if event["event"] == "on_chat_model_end" and event["data"]["output"].content:
            print(f"--- 代理: ---\n{event['data']['output'].content}")

    # --- 查询 2：预订酒店 ---
    query2 = "好的，请为我预订巴塞尔凯悦酒店。"
    print(f'\n--- 用户: "{query2}" ---')
    inputs2 = {"messages": [("user", query2)]}
    async for event in agent_executor.astream_events(
        inputs2, config=config, version="v2"
    ):
        if event["event"] == "on_chat_model_end" and event["data"]["output"].content:
            print(f"--- 代理: ---\n{event['data']['output'].content}")
```

## 运行代理

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
async def main():
    await run_hotel_agent()


async def run_hotel_agent():
    model = ChatVertexAI(model_name="gemini-2.5-flash")

    # 从运行的 MCP 工具箱服务器加载工具
    async with ToolboxClient("http://127.0.0.1:5000") as client:
        tools = await client.aload_toolset("hotel_toolset")

        agent = create_agent(model, tools, checkpointer=MemorySaver())

        await run_queries(agent)


await main()
```

您已成功使用 MCP 工具箱将 LangChain 代理连接到本地数据库！🥳

***

## API 参考

此集成的主要类是 `ToolboxClient`。

更多信息，请参阅以下资源：

* [工具箱官方文档](https://googleapis.github.io/genai-toolbox/)
* [工具箱 GitHub 仓库](https://github.com/googleapis/genai-toolbox)
* [工具箱 LangChain SDK](https://github.com/googleapis/mcp-toolbox-python-sdk/tree/main/packages/toolbox-langchain)

MCP 工具箱具有多种功能，可使数据库 Gen AI 工具的开发变得无缝：

* [认证参数](https://googleapis.github.io/genai-toolbox/resources/tools/#authenticated-parameters)：自动将工具输入绑定到 OIDC 令牌中的值，从而轻松运行敏感查询而不会泄露数据
* [授权调用](https://googleapis.github.io/genai-toolbox/resources/tools/#authorized-invocations)：根据用户的 Auth 令牌限制对工具的访问
* [OpenTelemetry](https://googleapis.github.io/genai-toolbox/how-to/export_telemetry/)：通过 [OpenTelemetry](https://opentelemetry.io/docs/) 从 MCP 工具箱获取指标和跟踪

# 社区与支持

我们鼓励您参与社区：

* ⭐️ 前往 [GitHub 仓库](https://github.com/googleapis/genai-toolbox) 开始使用并关注更新。
* 📚 深入了解[官方文档](https://googleapis.github.io/genai-toolbox/getting-started/introduction/)，获取更多高级功能和配置。
* 💬 加入我们的 [Discord 服务器](https://discord.com/invite/a4XjGqtmnG)，与社区联系并提问。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/tools/mcp_toolbox.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
