For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
主要導覽

在即時互動中使用工具

讓即時語音智慧體呼叫函式工具與遠端 MCP 伺服器。

你可以在 Realtime 工作階段中加入工具,讓模型在即時對話期間查詢資料、執行動作或呼叫服務。無論你的用戶端使用的是 WebRTC 資料通道還是 WebSocket,工具組態都使用相同的事件介面。

如果需要由你的應用程式執行工具並傳回結果,請使用函式工具。如果需要由 Realtime API 代你連線至遠端工具伺服器,請使用 MCP 工具。

選擇工具類型

工具類型適用情境執行方
function你的應用程式負責商業邏輯、核准檢查或私有系統存取。你的用戶端或伺服器接收函式呼叫,並回傳 function_call_output
mcp 搭配 server_url你希望模型呼叫遠端 MCP 伺服器提供的工具。Realtime API 呼叫遠端 MCP 伺服器。
mcp 搭配 connector_id你使用既有模型搭配舊版內建連接器。Realtime API 使用你提供的授權呼叫連接器。

以下兩個位置擇一新增工具:

  • 如果希望工具在整個工作階段中都可用,請透過 session.update 中的 session.tools,在 工作階段層級 新增工具。
  • 如果只需要在單一回合中使用工具,請透過 response.create 中的 response.tools,在 回應層級 新增工具。

設定函式工具

當工具應在你的應用程式中執行時,函式工具是合適的預設選擇。模型會輸出函式呼叫引數,由你的程式碼執行動作,再透過 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" }));

如需依事件逐步說明函式呼叫的完整流程,請參閱管理對話

設定 MCP 工具

如果工具已由遠端 MCP 伺服器提供,或既有模型使用舊版內建連接器,就適合使用 MCP 工具。與函式工具不同,MCP 工具由 Realtime API 本身執行。

在 Realtime 中,MCP 工具的結構如下:

  • type: "mcp"
  • server_label
  • server_urlconnector_id,擇一使用
  • 選用的 authorizationheaders
  • 選用的 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));

舊版連接器

connector_id 在 2026 年 9 月 1 日之後發布的模型中已棄用。 請使用 server_url 連線至遠端 MCP 伺服器,或使用 tunnel_id 透過 安全 MCP 通道連線至本機 MCP 伺服器。既有模型 仍支援連接器。以下範例使用 gpt-realtime-1.5,此模型於上述截止日期之前發布。

內建連接器使用相同的 MCP 工具結構,但傳入的是 connector_id, 而非 server_url。例如,Google Calendar 使用 connector_googlecalendar。在 Realtime 中,請使用這些內建連接器執行讀取 動作,例如搜尋或讀取活動或電子郵件。將使用者的 OAuth 存取 Token 傳入 authorization,並盡可能透過 allowed_tools 限縮可用工具範圍:

設定 Google Calendar 連接器
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.updateresponse.create,其中包含一個 typemcptools 項目。
  2. 伺服器開始匯入工具,並發出 mcp_list_tools.in_progress
  3. 在工具清單仍在載入時,模型無法呼叫尚未載入的工具。如果你希望等工具就緒後,再開始需要使用這些工具的回合,請監聽 mcp_list_tools.completeditem.typemcp_list_toolsconversation.item.done 事件會顯示實際匯入的工具名稱。如果匯入失敗,你會收到 mcp_list_tools.failed
  4. 使用者說話或傳送文字後,由你的用戶端建立回應,或根據工作階段組態自動建立回應。
  5. 如果模型選擇 MCP 工具,你會看到 response.mcp_call_arguments.deltaresponse.mcp_call_arguments.done
  6. 如果需要核准,伺服器會新增一個 item.typemcp_approval_request 的對話項目。你的用戶端必須以 mcp_approval_response 項目回覆。
  7. 工具開始執行後,你會看到 response.mcp_call.in_progress。若執行成功,稍後會收到 item.typemcp_callresponse.output_item.done 事件;若失敗,則會收到 response.mcp_call.failed
  8. 回應的 response.done 可能會在其 MCP 呼叫完成前抵達。當回應結束且其所有 MCP 呼叫都完成後,請再傳送一個 response.create 事件,讓模型使用結果並繼續對話。如果模型再次發出 MCP 呼叫,請重複此步驟。Realtime API 不會自動建立這些後續回應。

此事件處理常式會記錄主要的 MCP 生命週期事件,但不會管理後續回應:

在 Realtime 工作階段中監聽 MCP 事件
function parseRealtimeEvent(rawMessage) {
  if (typeof rawMessage === "string") {
    return JSON.parse(rawMessage);
  }

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

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

function getOutputText(item) {
  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_urlconnector_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 工具定義在開始匯入前未通過驗證:常見原因包括同一個 tools 陣列中有重複的 server_label、同時設定 server_urlconnector_id、在首次建立工作階段的請求中省略這兩個欄位、使用無效的 connector_id,或同時傳送 authorizationheaders.Authorization。使用連接器時,請勿傳送 headers.Authorization

核准或拒絕 MCP 工具呼叫

如果工具需要核准,Realtime API 會在對話中插入一個 mcp_approval_request 項目。 若要繼續,請傳送新的 conversation.item.create 事件,並將其中的 item.type 設為 mcp_approval_response

核准 MCP 請求
function approveMcpRequest(approvalRequestId) {
  const event = {
    type: "conversation.item.create",
    item: {
      id: `mcp_approval_${approvalRequestId}`,
      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"],
    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_urlconnector_id 定義過伺服器或連接器,後續的 session.updateresponse.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 定義,讓伺服器能夠匯入其工具清單。