如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
主题

在 Realtime 会话中使用工具

让实时语音智能体调用函数工具和远程 MCP 服务器。

您可以向 Realtime 会话添加工具,让模型在实时对话中查询数据、执行操作或调用服务。无论客户端使用 WebRTC 数据通道还是 WebSocket,配置工具时使用的事件接口都相同。

如果需要由您的应用执行工具并返回结果,请使用函数工具。如果需要由 Realtime API 代您连接远程工具服务器,请使用 MCP 工具。

选择工具类型

工具类型 适用场景 由谁执行
function 您的应用负责处理业务逻辑、执行审批检查或访问私有系统。 您的客户端或服务器接收函数调用并返回 function_call_output。
mcp 搭配 server_url 您希望模型调用远程 MCP 服务器提供的工具。 Realtime API 调用远程 MCP 服务器。
mcp 搭配 connector_id 您在现有模型中使用旧版内置连接器。 Realtime API 使用您提供的授权信息调用连接器。

您可以在以下两个层级中任选其一添加工具:

  • 会话级别:如果希望工具在整个会话期间都可用,请在 session.tools 中添加工具,并通过 session.update 发送配置。
  • 响应级别:如果只在一轮对话中需要工具,请在 response.tools 中添加工具,并通过 response.create 发送配置。

配置函数工具

如果工具需要在您的应用中运行,建议优先使用函数工具。模型会生成函数调用参数,您的代码负责执行操作,再通过 function_call_output 项将结果发回。

使用 session.update 配置函数工具
const event = {
  type: "session.update",
  session: {
    type: "realtime",
    model: "gpt-realtime-2.1",
    tools: [
      {
        type: "function",
        name: "lookup_order",
        description: "Look up an order by its order number.",
        parameters: {
          type: "object",
          properties: {
            order_number: {
              type: "string",
              description: "The customer-facing order number.",
            },
          },
          required: ["order_number"],
        },
      },
    ],
    tool_choice: "auto",
  },
};

ws.send(JSON.stringify(event));

当模型调用函数时,请监听函数调用项,执行应用逻辑,然后发回输出:

发送函数调用结果
const event = {
  type: "conversation.item.create",
  item: {
    type: "function_call_output",
    call_id: functionCall.call_id,
    output: JSON.stringify({
      status: "shipped",
      delivery_date: "2026-05-09",
    }),
  },
};

ws.send(JSON.stringify(event));
ws.send(
  JSON.stringify({
    type: "response.create",
    response: { output_modalities: ["text"], tool_choice: "none" },
  })
);

有关函数调用中每个事件的完整说明,请参阅管理对话。

配置 MCP 工具

如果远程 MCP 服务器已经提供了所需工具,或者现有模型使用的是旧版内置连接器,可以使用 MCP 工具。函数工具由您的应用执行,而 MCP 工具由 Realtime API 自行执行。

在 Realtime 中,MCP 工具定义包含以下字段:

  • type: "mcp"
  • server_label
  • server_url 或 connector_id,二选一
  • 可选字段 authorization 和 headers
  • 可选字段 allowed_tools
  • 可选字段 require_approval
  • 可选字段 server_description

以下示例让提供文档的 MCP 服务器在整个会话期间都可用:

使用 session.update 配置 MCP 工具
const event = {
  type: "session.update",
  session: {
    type: "realtime",
    model: "gpt-realtime-2.1",
    output_modalities: ["text"],
    tools: [
      {
        type: "mcp",
        server_label: "openai_docs",
        server_url: "https://developers.openai.com/mcp",
        allowed_tools: ["search_openai_docs", "fetch_openai_doc"],
        require_approval: "never",
      },
    ],
  },
};

ws.send(JSON.stringify(event));

旧版连接器

对于 2026 年 9 月 1 日之后发布的模型,connector_id 已弃用。请使用 server_url 连接远程 MCP 服务器,或使用 tunnel_id 通过 安全 MCP 隧道连接本地 MCP 服务器。现有模型仍支持连接器。以下示例使用的 gpt-realtime-1.5 发布于上述日期之前。

内置连接器使用相同的 MCP 工具结构,但传入的是 connector_id,而非 server_url。例如,Google 日历使用 connector_googlecalendar。在 Realtime 中,请使用这些内置连接器执行只读操作,例如搜索或读取日历事件或电子邮件。请在 authorization 中传入用户的 OAuth 访问令牌,并尽可能使用 allowed_tools 限制可调用的工具范围:

配置 Google 日历连接器
const event = {
  type: "session.update",
  session: {
    type: "realtime",
    model: "gpt-realtime-1.5",
    output_modalities: ["text"],
    tools: [
      {
        type: "mcp",
        server_label: "google_calendar",
        connector_id: "connector_googlecalendar",
        authorization: "<google-oauth-access-token>",
        allowed_tools: ["search_events", "read_event"],
        require_approval: "never",
      },
    ],
  },
};

ws.send(JSON.stringify(event));

远程 MCP 服务器 不会自动收到完整的对话上下文,但可以看到模型在工具调用中发送的所有数据。要限制可调用的工具范围,请使用 allowed_tools。对于您不会自动执行的操作,请要求审批。

Realtime 中的 MCP 调用流程

与 Realtime 的 function 工具不同,远程 MCP 工具由 Realtime API 自行执行。您的客户端不会运行远程工具,也无需返回 function_call_output。客户端负责配置访问权限、监听 MCP 生命周期事件,并可在服务器请求审批时发送审批响应。

典型流程如下:

  1. 您发送 session.update 或 response.create 事件,其中 tools 数组包含一个 type 为 mcp 的条目。
  2. 服务器开始导入工具,并发出 mcp_list_tools.in_progress 事件。
  3. 获取工具列表期间,模型无法调用尚未加载的工具。如果您希望等工具加载完毕后再开始依赖这些工具的对话轮次,请监听 mcp_list_tools.completed。收到 conversation.item.done 事件时,如果其中的 item.type 为 mcp_list_tools,您就可以从该事件中查看实际导入的工具名称。如果导入失败,您会收到 mcp_list_tools.failed。
  4. 用户说话或发送文本后,响应由您的客户端创建,也可根据会话配置自动创建。
  5. 如果模型选择了 MCP 工具,您会看到 response.mcp_call_arguments.delta 和 response.mcp_call_arguments.done 事件。
  6. 如果需要审批,服务器会添加一个 item.type 为 mcp_approval_request 的对话项。您的客户端必须发送一个 mcp_approval_response 项来答复该请求。
  7. 工具开始运行后,您会看到 response.mcp_call.in_progress。如果调用成功,您随后会收到一个 response.output_item.done 事件,其中 item.type 为 mcp_call。如果调用失败,您会收到 response.mcp_call.failed。
  8. 您可能会在某个响应的 MCP 调用完成之前收到该响应的 response.done 事件。等响应结束且其所有 MCP 调用都完成后,再发送一个 response.create 事件,让模型使用调用结果继续对话。如果模型再次发起 MCP 调用,请重复此步骤。Realtime API 不会自动创建这些后续响应。

以下事件处理程序会记录主要的 MCP 生命周期事件,但不负责管理后续响应:

在 Realtime 会话中监听 MCP 事件
import type WebSocket from "ws";
import type {
  ConversationItem,
  RealtimeServerEvent,
} from "openai/resources/realtime/realtime";

function parseRealtimeEvent(
  rawMessage: string | WebSocket.RawData | MessageEvent<string>
): RealtimeServerEvent {
  if (typeof rawMessage === "string") {
    return JSON.parse(rawMessage);
  }

  if ("data" in rawMessage && typeof rawMessage.data === "string") {
    return JSON.parse(rawMessage.data);
  }

  return JSON.parse(rawMessage.toString());
}

function getOutputText(item: ConversationItem) {
  if (item.type !== "message") return "";

  return (item.content ?? [])
    .filter((part) => part.type === "output_text")
    .map((part) => part.text)
    .join("");
}

ws.on("message", (rawMessage) => {
  const event = parseRealtimeEvent(rawMessage);

  switch (event.type) {
    case "mcp_list_tools.in_progress":
      console.log("Listing MCP tools for item:", event.item_id);
      break;

    case "mcp_list_tools.completed":
      console.log("MCP tool listing complete for item:", event.item_id);
      break;

    case "mcp_list_tools.failed":
      console.error("MCP tool listing failed for item:", event.item_id);
      break;

    case "conversation.item.done":
      if (event.item.type === "mcp_list_tools") {
        const names = event.item.tools.map((tool) => tool.name).join(", ");
        console.log(`MCP tools ready on ${event.item.server_label}: ${names}`);
      }

      if (event.item.type === "mcp_approval_request") {
        console.log(
          "Approval required for:",
          event.item.name,
          event.item.arguments
        );
      }
      break;

    case "response.mcp_call_arguments.done":
      console.log("Final MCP call arguments:", event.arguments);
      break;

    case "response.mcp_call.in_progress":
      console.log("Running MCP tool for item:", event.item_id);
      break;

    case "response.mcp_call.failed":
      console.error("MCP tool call failed for item:", event.item_id);
      break;

    case "response.output_item.done":
      if (event.item.type === "mcp_call") {
        console.log(
          `MCP output from ${event.item.server_label}.${event.item.name}:`,
          event.item.output
        );
      }

      if (event.item.type === "message") {
        console.log("Assistant:", getOutputText(event.item));
      }
      break;

    case "response.done":
      console.log("Realtime turn complete.");
      break;
  }
});

常见故障

  • mcp_list_tools.failed:Realtime API 无法从远程服务器或连接器导入工具。请检查 server_url 或 connector_id、身份验证信息、服务器连接以及您在 allowed_tools 中指定的工具名称。
  • response.mcp_call.failed:模型选择了工具,但工具调用未能完成。请查看事件载荷及后续的 mcp_call 项,检查是否存在 MCP 协议、执行或传输错误。
  • mcp_approval_request 没有对应的 mcp_approval_response:客户端必须明确批准或拒绝请求,工具调用才能继续。
  • 对话轮次在 mcp_list_tools.in_progress 状态下开始:该轮对话只能使用已经加载完毕的工具。
  • 响应使用了 tool_choice: "required",但当前没有可用工具:模型找不到可调用的工具。请等待 mcp_list_tools.completed 事件,确认至少已导入一个工具,或在无需调用工具的对话轮次中为 tool_choice 设置其他值。
  • MCP 工具定义在导入开始前未通过验证:常见原因包括 server_label 在同一 tools 数组中重复、同时设置了 server_url 和 connector_id、首次创建会话的请求中两者均未设置、使用了无效的 connector_id,或同时发送了 authorization 和 headers.Authorization。使用连接器时,请勿发送 headers.Authorization。

批准或拒绝 MCP 工具调用

如果工具需要审批,Realtime API 会在对话中插入一个 mcp_approval_request 项。要继续处理该调用,请发送一个新的 conversation.item.create 事件,并将其中的 item.type 设为 mcp_approval_response。

批准 MCP 请求
function approveMcpRequest(approvalRequestId: string) {
  const event = {
    type: "conversation.item.create",
    item: {
      type: "mcp_approval_response",
      approval_request_id: approvalRequestId,
      approve: true,
    },
  };

  ws.send(JSON.stringify(event));
}

如果您拒绝请求,请将 approve 设为 false,还可以在 reason 中说明原因。

仅在一次响应中使用 MCP

如果 MCP 只需在一轮对话中可用,请将同一个 MCP 工具对象添加到 response.tools,而非 session.tools:

为单次响应添加 MCP 工具
const event = {
  type: "response.create",
  response: {
    output_modalities: ["text"],
    tool_choice: "required",
    parallel_tool_calls: false,
    input: [
      {
        type: "message",
        role: "user",
        content: [
          {
            type: "input_text",
            text: "Which transport should I use for browser clients in the Realtime API?",
          },
        ],
      },
    ],
    tools: [
      {
        type: "mcp",
        server_label: "openai_docs",
        server_url: "https://developers.openai.com/mcp",
        allowed_tools: ["search_openai_docs", "fetch_openai_doc"],
        require_approval: "never",
      },
    ],
  },
};

ws.send(JSON.stringify(event));

如果只有一次响应需要外部上下文,或者不同对话轮次需要使用不同的 MCP 服务器,可以采用这种方式。

复用先前定义的服务器标签

server_label 是工具定义在当前 Realtime 会话中的固定标识。首次定义服务器或连接器时,请提供 server_label 以及 server_url 或 connector_id。之后发送 session.update 或 response.create 事件时,只需引用相同的 server_label,Realtime API 就会复用先前的定义,无需再次发送完整的工具对象。

复用先前定义的连接器
const event = {
  type: "response.create",
  response: {
    output_modalities: ["text"],
    input: [
      {
        type: "message",
        role: "user",
        content: [
          {
            type: "input_text",
            text: "Check my schedule for this afternoon.",
          },
        ],
      },
    ],
    // Reuses the google_calendar connector defined earlier in this session.
    tools: [
      {
        type: "mcp",
        server_label: "google_calendar",
      },
    ],
  },
};

ws.send(JSON.stringify(event));

工具定义只能在同一会话中复用。如果您启动了新的 Realtime 会话,请重新发送完整的 MCP 定义,以便服务器导入工具列表。