跳到主要内容

从应用程序连接到 MCP 服务器

本教程展示了如何使用 Langflow 的 MCP Tools 组件将 MCP 工具连接到你的应用程序。

模型上下文协议 (MCP) 通过 MCP 客户端MCP 服务器 帮助智能体与 LLM 集成。 具体来说,MCP 服务器托管工具,智能体(MCP 客户端)使用这些工具来完成专门的任务。 MCP 服务器连接到 MCP 客户端,如 Cursor。 然后,你与客户端交互,客户端根据需要使用连接服务器的工具来完成你的请求。

你可以将 Langflow 作为 MCP 客户端和 MCP 服务器运行:

  • 将 Langflow 用作 MCP 客户端:当作为 MCP 客户端运行时,Langflow 流程中的 Agent 组件可以使用连接的组件作为工具来处理请求。 你可以使用现有组件作为工具,也可以将任何 MCP 服务器连接到你的流程,使该服务器的工具可用于智能体。

  • 将 Langflow 用作 MCP 服务器:当作为 MCP 服务器运行时,你的流程变成可以被 MCP 客户端使用的工具,该客户端可以是外部客户端或另一个 Langflow 流程。

在本教程中,你将使用 Langflow MCP Tools 组件将多个 MCP 服务器连接到你的流程,然后使用 Python 应用程序运行你的流程并以编程方式与智能体聊天。

前提条件

本教程使用 OpenAI LLM。如果你想使用不同的提供商,你需要该提供商的有效凭据。

创建智能体流程

  1. 在 Langflow 中,点击 New Flow,然后选择 Simple agent 模板。

  2. Agent 组件中,输入你的 OpenAI API 密钥。

    如果你想使用不同的提供商或模型,请相应地编辑 Model ProviderModel NameAPI Key 字段。

  3. 要测试流程,请点击 Playground,然后询问 LLM 今天在阿迪朗达克地区徒步旅行安全吗?

    这个查询展示了 LLM 本身可能无法访问专门设计用于处理特殊查询的信息或功能。在这个例子中,默认的 OpenAI 模型提供了一个模糊的响应,尽管智能体通过使用其内部的 get_current_date 功能知道当前日期。


    _10
    Today is July 11, 2025.
    _10
    To determine if it's safe to go hiking in the Adirondacks today, you should check the current weather conditions, trail advisories, and any local alerts (such as bear activity or flooding).
    _10
    Would you like a detailed weather forecast or information on trail conditions for the Adirondacks today?

    要改善响应,你可以将 MCP 服务器连接到你的流程,为智能体提供在生成响应时使用的专用工具。在本教程的下一部分中,你将连接一个为智能体提供实时天气信息的 MCP 服务器,以便它能够生成更具体的响应。

添加 MCP Tools 组件

网上有许多 MCP 服务器可用,为不同的任务提供不同的工具。 要将 MCP 服务器与 MCP 客户端一起使用,你必须使服务器对客户端可用。 对于所有 MCP 客户端,有以下几种方法:

  • 在本地安装服务器。
  • 使用 uvxnpx 获取并运行服务器包。
  • 调用远程运行的服务器,如 Smithery 上可用的服务器。

本教程演示了如何使用 uv pip install 在本地安装天气服务器,以及如何使用 npx 运行地理位置服务器包。 你特定的 MCP 服务器的要求可能有所不同。

在 Langflow 中,你使用 MCP Tools 组件将特定的 MCP 服务器连接到流程。 你需要为你想要流程使用的每个 MCP 服务器提供一个 MCP Tools 组件。

  1. 对于本教程,请使用 uv 和 Python 在你的本地机器上安装 天气 MCP 服务器


    _10
    uv pip install mcp_weather_server

    确保在 Langflow 运行的同一 Python 环境中安装服务器:

    • 虚拟环境中的 Langflow:在安装服务器之前激活环境。
    • Langflow Docker 镜像:在 Docker 容器内安装服务器。
    • Langflow Desktop 或系统级 Langflow OSS:全局安装服务器或在你运行 Langflow 的同一用户环境中安装。
  2. 在你的 Simple agent 流程中,移除 URLCalculator 工具,然后将 MCP Tools 组件添加到你的工作区。

  3. 点击 MCP Tools 组件,然后点击 Add MCP Server

  4. Add MCP Server 面板中,提供服务器启动命令和参数以将天气 MCP 服务器连接到你的流程。对于本教程,使用 JSONSTDIO 选项中的任一个。

    当智能体确定它需要使用该服务器提供的工具时,Langflow 运行该命令来启动服务器。

    注意,两种配置提供相同的信息,但格式不同。 这意味着如果你的 MCP 服务器仓库只为服务器提供 JSON 文件,你仍然可以在 STDIO 选项中使用这些值。

    要将 MCP 服务器配置作为 JSON 对象提供,请选择 JSON,然后将服务器配置粘贴到 JSON 字段中:


    _13
    {
    _13
    "mcpServers": {
    _13
    "weather": {
    _13
    "command": "python",
    _13
    "args": [
    _13
    "-m",
    _13
    "mcp_weather_server"
    _13
    ],
    _13
    "disabled": false,
    _13
    "autoApprove": []
    _13
    }
    _13
    }
    _13
    }

  5. 点击 Add Server,然后等待 Actions 列表填充。这意味着 MCP 服务器成功连接。

    对于这个天气服务器,MCP Tools 组件还添加了一个可选的 City 字段。 对于本教程,不要在此字段中输入任何内容。 相反,你将在下一步中添加一个地理位置 MCP 服务器,智能体将使用它来检测你的位置。

  6. 点击 MCP Tools 组件,在组件的标题菜单中启用 Tool Mode,然后将组件的 Toolset 端口连接到 Agent 组件的 Tools 端口。

    此时你的流程有四个连接的组件:

    • Chat Input 组件连接到 Agent 组件的 Input 端口。这允许流程被来自用户或应用程序的入入提示触发。
    • 带有天气 MCP 服务器的 MCP Tools 组件连接到 Agent 组件的 Tools 端口。智能体可能不会在每个请求中都使用这个服务器;智能体只有在认为服务器可以帮助回应提示时才使用这个连接。
    • Agent 组件的 Output 端口连接到 Chat Output 组件,该组件将最终响应返回给用户或应用程序。

    An agent component connected to an MCP weather server

  7. To test the weather MCP server, click Playground, and then ask the LLM Is it safe to go hiking in the Adirondacks today?

    The Playground shows you the agent's logic as it analyzes the request and select tools to use.

    Ideally, the agent's response will be more specific than the previous response because of the additional context provided by the weather MCP server. For example:


    _10
    The current weather in Lake Placid, a central location in the Adirondacks,
    _10
    is foggy with a temperature of 17.2°C (about 63°F).
    _10
    If you plan to go hiking today, be cautious as fog can reduce visibility
    _10
    on trails and make navigation more difficult.

    This is a better response, but what makes this MCP server more valuable than just calling a weather API?

    First, MCP servers are often customized for specific tasks, such as highly specialized actions or chained tools for complex, multi-step problem solving. Typically, you would have to write a custom script for a specific task, possibly including multiple API calls in a single script, and then you would have to either execute this script outside the context of the agent or provide it to your agent in some way.

    Instead, the MCP ensures that all MCP servers are added to agents in the same way, without having to know each server's specific endpoint structures or write custom integrations. The MCP is a standardized way to integrate many diverse tools into agentic applications. You don't have to learn a new API or write custom code every time you want to use a new MCP server.

    Additionally, you can attach many MCP servers to one agent, depending on the problems you want your application to solve. The more servers you add, the more specialized context the agent can use in its responses. In this tutorial, adding the weather MCP server already improved the quality of the LLM's response. In the next section of the tutorial, you will add a ip_geolocation MCP server so the agent can detect the user's location if they don't specify a location in their prompt.

Add a geolocation server

The Toolkit MCP server includes multiple MCP tools for network monitoring, including IP geolocation. It isn't extremely precise, but it doesn't require an API key.

Note that this tool returns the IP geolocation of your Langflow server, so if your server is deployed remotely, consider alternative approaches for getting user-specific location data, such as browser geolocation APIs.

This MCP server can be started with one npx command, which downloads and runs the Toolkit MCP server Node registry package without installing the package locally.

To add the Toolkip MCP server to your flow, do the following:

  1. Add another MCP Tools component to your flow, click the component, and then click Add MCP Server.

  2. Select STDIO.

  3. For Name, enter ip_geolocation.

    提示

    The tool name and description help the agent select tools. If your agent is struggling to select tools, make sure the names and descriptions are clear and human-readable.

  4. For Command, enter npx @cyanheads/toolkit-mcp-server.

  5. Click Add Server, and then wait for the Actions list to populate. This means that the MCP server successfully connected.

  6. Click the MCP Tools component, enable Tool Mode in the component's header menu, and then connect the component's Toolset port to the Agent component's Tools port.

    Your flow now has an additional MCP Tools component for a total of five components.

    An agent component connected to MCP weather and geolocation servers

Create a Python application that connects to Langflow

At this point, you can open the Playground and ask about the weather in your current location to test the IP geolocation tool. However, geolocation tools are most useful in applications where you or your users want to ask about the weather from different places around the world.

In the last part of this tutorial, you'll learn how to use the Langflow API to run a flow in a script. This could be part of a larger application, such as a mobile app where users want to know if the weather is good for a particular sport.

When you use the Langflow API to run a flow, you can change some aspects of the flow without changing the code. For example, you can add more MCP servers to your flow in Langflow, and then use the same script to run the flow. You can use the same input or a new input that prompts the agent to use other tools.

  1. For this tutorial's Python script, gather the following information:

    • LANGFLOW_SERVER_ADDRESS: Your Langflow server's domain. The default value is 127.0.0.1:7860. You can get this value from the code snippets on your flow's API access pane.
    • FLOW_ID: Your flow's UUID or custom endpoint name. You can get this value from the code snippets on your flow's API access pane.
    • LANGFLOW_API_KEY: A valid Langflow API key. To create an API key, see API keys.
  2. Copy the following script into a Python file, and then replace the placeholders with the information you gathered in the previous step:


    _34
    import requests
    _34
    import os
    _34
    _34
    url = "LANGFLOW_SERVER_ADDRESS/api/v1/run/FLOW_ID" # The complete API endpoint URL for this flow
    _34
    _34
    # Request payload configuration
    _34
    payload = {
    _34
    "output_type": "chat",
    _34
    "input_type": "chat",
    _34
    "input_value": "What's the weather like where I am right now?"
    _34
    }
    _34
    _34
    # Request headers
    _34
    headers = {
    _34
    "Content-Type": "application/json",
    _34
    "x-api-key": "LANGFLOW_API_KEY"
    _34
    }
    _34
    _34
    try:
    _34
    # Send API request
    _34
    response = requests.request("POST", url, json=payload, headers=headers)
    _34
    response.raise_for_status() # Raise exception for bad status codes
    _34
    _34
    # Parse and print only the message text
    _34
    data = response.json()
    _34
    message = data["outputs"][0]["outputs"][0]["results"]["message"]["text"]
    _34
    print(message)
    _34
    _34
    except requests.exceptions.RequestException as e:
    _34
    print(f"Error making API request: {e}")
    _34
    except ValueError as e:
    _34
    print(f"Error parsing response: {e}")
    _34
    except (KeyError, IndexError) as e:
    _34
    print(f"Error extracting message from response: {e}")

    Notice that this script uses a different prompt than the previous Playground examples. In this script, the input_value asks about the weather in the user's current location without providing any hints about the user's location, such as a particular city.

    Additionally, this script includes parsing code to extract the LLM's reply from the entire Langflow API response. You will want to use similar extraction in your own applications because the Langflow API response includes metadata and other information that isn't relevant to the reply passed to the user.

  3. Save and run the script to send the request and test the flow.

    The agent uses the ip_geolocation tool to detect the requester's location, and then it uses the weather tool to retrieve weather information for that location. For example:


    _10
    The weather in Waynesboro, Pennsylvania, is currently overcast with a temperature of 23.0°C (about 73.4°F).
    _10
    If you need more details or have any other questions, feel free to ask!

    Remember, the ip_geolocation tool used in this tutorial uses your Langflow server's location, which can be different from your actual location.

后续步骤

要继续构建本教程中介绍的概念,请参阅以下内容:

Search