Link Search Menu Expand Document Documentation Menu

连接到外部 MCP 服务器

3.0 版本引入

OpenSearch 支持使用智能体的智能体工作流。虽然 OpenSearch 提供了用于运行复杂查询的内置工具,但模型上下文协议 (MCP) 能够与外部工具和数据源集成。MCP 是一种开放的协议标准,它为 AI 模型连接外部数据源和工具提供了标准化方法,充当远程 MCP 服务器工具的“通用适配器”。

目前,OpenSearch 仅支持使用服务器发送事件 (Server-Sent Events, SSE) 协议的 MCP 服务器。不支持标准输入/输出 (stdio) 协议。

以下示例演示了在智能体工作流中使用 MCP 工具。

先决条件

在使用 MCP 工具之前,您必须完成以下先决条件。

启用 MCP 并配置可信连接器端点

  • 通过配置 plugins.ml_commons.mcp_feature_enabled 设置来启用 MCP 协议。
  • plugins.ml_commons.trusted_connector_endpoints_regex 设置中配置可信连接器端点。出于安全考虑,此设置使用正则表达式模式来定义允许哪些 MCP 服务器 URL。

要配置这两个设置,请发送以下请求

POST /_cluster/settings/
{
  "persistent": {
    "plugins.ml_commons.trusted_connector_endpoints_regex": [
      "<mcp server url>"
    ],
    "plugins.ml_commons.mcp_feature_enabled": "true"
  }
}

设置 MCP 服务器

确保您有一个正在运行的 MCP 服务器,并且可以从您的 OpenSearch 集群访问该服务器。

步骤 1:创建 MCP 连接器

MCP 连接器存储 MCP 服务器的连接详细信息和凭据。要创建 MCP 连接器,请发送以下请求

POST /_plugins/_ml/connectors/_create
{
  "name":        "My MCP Connector",
  "description": "Connects to the external MCP server for weather tools",
  "version":     1,
  "protocol":    "mcp_sse",
  "url":         "https://my-mcp-server.domain.com",
  "credential": {
    "mcp_server_key": "THE_MCP_SERVER_API_KEY"
  },
  "parameters":{
    "sse_endpoint": "/sse" 
  },
  "headers": {
    "Authorization": "Bearer ${credential.mcp_server_key}"
  }
}

下表描述了连接器参数。有关标准连接器参数的更多信息,请参阅配置参数

参数 数据类型 必需 描述
protocol 字符串 指定 mcp_sse 以使用 SSE 协议(MCP 唯一支持的协议类型)。
url 字符串 MCP 服务器的完整基础 URL,包括协议、主机名和端口(如果未使用默认端口)(例如,https://my-mcp-server.com:8443)。
credential 对象 包含敏感的身份验证信息,例如 API 密钥或令牌。此对象中存储的值可以使用 ${credential.*} 语法在 headers 部分安全引用。
parameters 对象 包含 MCP 连接器的配置参数。
parameters.sse_endpoint 字符串 MCP 服务器的 SSE 端点路径。默认值为 /sse
headers 对象 要包含在对 MCP 服务器请求中的 HTTP 标头。对于身份验证标头,使用 ${credential.*} 语法引用 credential 对象中的值(例如,"Authorization": "Bearer ${credential.mcp_server_key}")。

响应包含连接器 ID:

{
  "connector_id": "NZ2W2ZUBZ_3SyqdOvh2n",
}

步骤 2:注册模型

使用连接器注册任何外部托管的大型语言模型 (LLM)。有关支持模型的列表,请参阅支持的连接器

例如,要注册 OpenAI 聊天模型,请发送以下请求

POST /_plugins/_ml/models/_register
{
  "name": "My OpenAI model: gpt-4",
  "function_name": "remote",
  "description": "Test model registration (this example uses OpenAI, but you can register any model)",
  "connector": {
    "name": "My OpenAI Connector: gpt-4",
    "description": "Connector for the OpenAI chat model",
    "version": 1,
    "protocol": "http",
    "parameters": {
      "model": "gpt-4o"
    },
    "credential": {
      "openAI_key": "<YOUR_API_KEY>"
    },
    "actions": [
      {
        "action_type": "predict",
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "headers": {
          "Authorization": "Bearer ${credential.openAI_key}"
        },
        "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_instruction}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}], \"tools\": [${parameters._tools:-}],\"parallel_tool_calls\":${parameters.parallel_tool_calls},\"tool_choice\": \"${parameters.tool_choice}\" }"
      }
    ]
  }
}

响应包含模型 ID

{
  "task_id": "K_iQfpYBjoQOEoSHN3wU",
  "status": "CREATED",
  "model_id": "LPiQfpYBjoQOEoSHN3zH"
}

要检查操作状态,请将任务 ID 提供给任务 API。注册完成后,任务的 state 将变为 COMPLETED

步骤 3:注册用于访问 MCP 工具的智能体

目前,MCP 工具只能与会话式计划-执行-反思智能体类型一起使用。

要启用外部 MCP 工具,请在智能体配置中包含一个或多个 MCP 连接器。

每个连接器都必须在 parameters.mcp_connectors 数组中指定以下参数。

参数 数据类型 必需 描述
mcp_connector_id 字符串 MCP 连接器的连接器 ID。
tool_filters 数组 一个 Java 风格正则表达式数组,用于指定 MCP 服务器中的哪些工具可供智能体使用。如果某个工具与数组中的至少一个正则表达式匹配,则该工具将被包含。如果省略或设置为空数组,则连接器公开的所有工具都将可用。使用 ^$ 锚点或字面字符串来精确匹配工具名称。例如,^get_forecast 匹配任何以“get_forecast”开头的工具,而 search_indices 只匹配“search_indices”。

在此示例中,您将使用步骤 1 中创建的连接器 ID 注册一个会话式智能体。MCP 服务器有两个可用工具(get_alertsget_forecasts),但只有 get_alerts 工具将包含在智能体的配置中,因为它匹配指定的正则表达式模式 ^get_alerts$

POST /_plugins/_ml/agents/_register
{
  "name":        "Weather & Search Bot",
  "type":        "conversational",
  "description": "Uses MCP to fetch forecasts and OpenSearch indices",
  "llm": {
    "model_id": "<MODEL_ID_FROM_STEP_2>",
    "parameters": {
      "max_iteration": 5,
      "system_instruction": "You are a helpful assistant.",
      "prompt": "${parameters.question}"
    }
  },
  "memory": {
    "type": "conversation_index"
  },
  "parameters": {
    "_llm_interface": "openai/v1/chat/completions",
    "mcp_connectors": [
      {
        "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>",
        "tool_filters": [
          "^get_alerts$"
        ]
      }
    ]
  },
  "tools": [
    { "type": "ListIndexTool" },
    { "type": "SearchIndexTool" }
  ],
  "app_type": "os_chat"
}

响应包含智能体 ID

{
  "agent_id": "LfiXfpYBjoQOEoSH93w7"
}

步骤 4:运行代理

通过调用 Execute Agent API 并提供用户问题来调用注册的智能体

POST /_plugins/_ml/agents/<Agent_ID>/_execute
{
  "parameters": {
    "question": "Any weather alerts in Washington",
    "verbose": true
  }
}

智能体同时使用 tools 数组中指定的 OpenSearch 工具和从 MCP 服务器选择的工具(根据您的工具过滤器)来返回答案

{
    "inference_results": [
        {
            "output": [
                {
                    "name": "memory_id",
                    "result": "MfiZfpYBjoQOEoSH13wj"
                },
                {
                    "name": "parent_interaction_id",
                    "result": "MviZfpYBjoQOEoSH13xC"
                },
                {
                    "name": "response",
                    "result": "{\"id\":\"chatcmpl-BRRcdxVjkrKG7HjkVWZVwueJSEjgd\",\"object\":\"chat.completion\",\"created\":1.745880735E9,\"model\":\"gpt-4o-2024-08-06\",\"choices\":[{\"index\":0.0,\"message\":{\"role\":\"assistant\",\"tool_calls\":[{\"id\":\"call_yWg0wk4mfE2v8ARebupfbJ87\",\"type\":\"function\",\"function\":{\"name\":\"get_alerts\",\"arguments\":\"{\\\"state\\\":\\\"WA\\\"}\"}}],\"annotations\":[]},\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":201.0,\"completion_tokens\":16.0,\"total_tokens\":217.0,\"prompt_tokens_details\":{\"cached_tokens\":0.0,\"audio_tokens\":0.0},\"completion_tokens_details\":{\"reasoning_tokens\":0.0,\"audio_tokens\":0.0,\"accepted_prediction_tokens\":0.0,\"rejected_prediction_tokens\":0.0}},\"service_tier\":\"default\",\"system_fingerprint\":\"fp_f5bdcc3276\"}"
                },
                {
                    "name": "response",
                    "result": "[{\"text\":\"\\nEvent: Wind Advisory\\nArea: Kittitas Valley\\nSeverity: Moderate\\nDescription: * WHAT...Northwest winds 25 to 35 mph with gusts up to 45 mph\\nexpected.\\n\\n* WHERE...Kittitas Valley.\\n\\n* WHEN...From 2 PM to 8 PM PDT Tuesday.\\n\\n* IMPACTS...Gusty winds will blow around unsecured objects. Tree\\nlimbs could be blown down and a few power outages may result.\\nInstructions: Winds this strong can make driving difficult, especially for high\\nprofile vehicles. Use extra caution.\\n\"}]"
                },
                {
                    "name": "response",
                    "result": "There is a Wind Advisory for the Kittitas Valley in Washington. Here are the details:\n\n- **Event:** Wind Advisory\n- **Area:** Kittitas Valley\n- **Severity:** Moderate\n- **Description:** Northwest winds 25 to 35 mph with gusts up to 45 mph expected.\n- **When:** From 2 PM to 8 PM PDT Tuesday.\n- **Impacts:** Gusty winds may blow around unsecured objects, potentially causing tree limbs to fall, and resulting in a few power outages.\n\n**Instructions:** These strong winds can make driving difficult, especially for high-profile vehicles. Use extra caution if you are traveling in the area."
                }
            ]
        }
    ]
}

更多资源