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

概述

MCP 工具箱 for Databases 是一个用于数据库的开源 MCP 服务器。它旨在满足企业级和生产质量的要求。通过处理连接池、身份验证等复杂性,它使您能够更轻松、更快、更安全地开发工具。 工具箱工具可以与 LangChain 应用程序无缝集成。有关入门配置 MCP 工具箱的更多信息,请参阅文档 架构

设置

本指南假设您已完成以下操作:
  1. 安装 Python 3.9+pip
  2. 安装 PostgreSQL 16+ 和 psql 命令行客户端

1. 设置您的数据库

首先,让我们设置一个 PostgreSQL 数据库。我们将创建一个新数据库、一个专用于 MCP 工具箱的用户,以及一个包含一些示例数据的 hotels 表。 使用 psql 命令连接到 PostgreSQL。您可能需要根据您的 PostgreSQL 设置调整命令(例如,如果需要指定主机或其他超级用户)。
psql -U postgres
现在,运行以下 SQL 命令来创建用户、数据库并授予必要的权限:
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;
使用新用户连接到您新创建的数据库:
\c toolbox_db toolbox_user
最后,创建 hotels 表并插入一些数据:
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
brew install mcp-toolbox
对于其他平台,下载适用于您的操作系统和架构的最新 MCP 工具箱二进制文件。 创建一个 tools.yaml 文件。此文件定义了 MCP 工具箱可以连接的数据源以及它可以向您的代理公开的工具。对于生产用途,请始终使用环境变量来存储机密信息。
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
toolbox --tools-file "tools.yaml"
MCP 工具箱默认在 http://127.0.0.1:5000 上启动,并且如果您对 tools.yaml 文件进行更改,它将热重载。

实例化

!pip install toolbox-langchain
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")

调用

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)
[{"id":1,"location":"Basel","name":"Hilton Basel","price_tier":"Luxury"},{"id":3,"location":"Basel","name":"Hyatt Regency Basel","price_tier":"Upper Upscale"}]

在代理中使用

现在是有趣的部分!我们将安装所需的 LangChain 包,并创建一个可以使用我们在 MCP 工具箱中定义的工具的代理。
pip install -qU toolbox-langchain langgraph langchain-google-vertexai
安装包后,我们可以定义我们的代理。我们将使用 ChatVertexAI 作为模型,并使用 ToolboxClient 来加载我们的工具。来自 langchain.agentscreate_agent 创建了一个强大的代理,可以推理要调用哪个工具。 注意: 在执行下面的代码之前,请确保您的 MCP 工具箱服务器在单独的终端中运行。
from langchain.agents import create_agent
from langchain_google_vertexai import ChatVertexAI
from langgraph.checkpoint.memory import MemorySaver
from toolbox_langchain import ToolboxClient


prompt = """
You're a helpful hotel assistant. You handle hotel searching and booking.
When the user searches for a hotel, list the full details for each hotel found: id, name, location, and price tier.
Always use the hotel ID for booking operations.
For any bookings, provide a clear confirmation message.
Don't ask for clarification or confirmation from the user; perform the requested action directly.
"""


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

    # --- Query 1: Search for hotels ---
    query1 = "I need to find a hotel in Basel."
    print(f'\n--- USER: "{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"--- AGENT: ---\n{event['data']['output'].content}")

    # --- Query 2: Book a hotel ---
    query2 = "Great, please book the Hyatt Regency Basel for me."
    print(f'\n--- USER: "{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"--- AGENT: ---\n{event['data']['output'].content}")

运行代理

async def main():
    await run_hotel_agent()


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

    # Load the tools from the running MCP Toolbox server
    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 有关更多信息,请参阅以下资源: MCP 工具箱具有多种功能,可使为数据库开发 Gen AI 工具变得无缝:
  • 认证参数:自动将工具输入绑定到来自 OIDC 令牌的值,从而轻松运行敏感查询而不会泄露数据。
  • 授权调用:根据用户的 Auth 令牌限制对使用工具的访问。
  • OpenTelemetry:使用 OpenTelemetry 从 MCP 工具箱获取指标和跟踪。

社区与支持

我们鼓励您参与社区: