如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題
總覽 智慧體存取權 ChatGPT 與 Codex 使用者文件 使用案例

技術參考

ChatGPT 專屬 UI 擴充功能與中繼資料參考。

優先採用開放標準。請依照

MCP Apps 規格

使用共用的 UI 欄位和橋接方法。 OpenAI 擴充功能可視需要使用。需要 ChatGPT 專屬功能時,可透過 window.openai 存取。

window.openai 元件橋接介面

ChatGPT 透過 window.openai 提供相容性別名和選用的 ChatGPT 擴充功能。開發新的 UI 時,只要共用規格提供對應功能,就應使用 MCP Apps 橋接介面。只有需要 ChatGPT 專屬功能時,才使用 window.openai。

實作步驟請參閱建構 ChatGPT UI。

如果工具需要使用者確認,初始階段沒有 toolInput 屬於預期行為。核准前,ChatGPT 不會將需要核准的引數載入小工具。使用者核准工具呼叫後,主機才會透過 ui/notifications/tool-input 傳送這些引數。

功能

功能類別 介面 常見用途
狀態與資料 window.openai.toolInput 呼叫工具時提供的引數。若工具需要核准,這個值可能會維持 null,直到主機在核准後傳送 ui/notifications/tool-input。
狀態與資料 window.openai.toolOutput 工具傳回的 structuredContent。模型會逐字讀取欄位內容,請保持精簡。
狀態與資料 window.openai.toolResponseMetadata 僅供小工具使用的標準工具結果中繼資料。在 ChatGPT 中,這些資料包含 status、call_tool_result 和 mcp_tool_result,保留了完整的 MCP 結果封裝,包括隱藏的 _meta。
狀態與資料 window.openai.widgetState 在多次轉譯之間保留的 UI 狀態快照。
狀態與資料 window.openai.setWidgetState(state) 同步儲存新的快照。每次發生有意義的 UI 互動後,都應呼叫此方法。
小工具執行階段 API window.openai.callTool(name, args) 從小工具呼叫另一個 MCP 工具,呼叫方式與模型發起的呼叫相同。
小工具執行階段 API window.openai.sendFollowUpMessage({ prompt, scrollToBottom }) 要求 ChatGPT 發布由元件撰寫的訊息。scrollToBottom 為選用參數,預設為 true。設為 false 即可停用自動捲動。
小工具執行階段 API window.openai.uploadFile(file, { library?: boolean }) 上傳使用者選取的檔案並取得 fileId。傳入 { library: true } 後,如果使用者可以使用 ChatGPT 檔案庫,上傳的檔案也會儲存到該檔案庫。
小工具執行階段 API window.openai.selectFiles() 開啟 ChatGPT 檔案庫選擇器,並以 { fileId, fileName, mimeType }[] 傳回外掛程式已獲授權存取的檔案。部分使用者可能無法使用檔案庫,因此請先檢查是否支援此輔助函式。
小工具執行階段 API window.openai.getFileDownloadUrl({ fileId }) 取得檔案的暫時下載 URL。適用於小工具上傳、從檔案庫選取、透過檔案參數傳入,或由工具以檔案參照傳回的檔案。
小工具執行階段 API window.openai.requestDisplayMode(...) 要求切換至子母畫面或全螢幕模式。
小工具執行階段 API window.openai.requestModal({ params, template }) 開啟由 ChatGPT 管理的強制回應視窗。省略 template 即可使用目前的範本,也可傳入已註冊的範本 URI 來切換視窗內容。
小工具執行階段 API window.openai.requestClose() 要求 ChatGPT 關閉目前的小工具。
小工具執行階段 API window.openai.notifyIntrinsicHeight(...) 在小工具高度變動時回報高度,避免捲動內容遭到裁切。
小工具執行階段 API window.openai.openExternal({ href, redirectUrl }) 在使用者的瀏覽器中開啟經審核的外部連結。對於已核准的重新導向目標,ChatGPT 預設會附加 ?redirectUrl=...。設定 redirectUrl: false 即可略過此步驟。
小工具執行階段 API window.openai.setOpenInAppUrl({ href }) 可視需要覆寫全螢幕模式下顯示的外部連結目標。若未設定,ChatGPT 會依預設行為開啟元件目前的 iframe 路徑。
上下文 window.openai.theme、window.openai.displayMode、window.openai.maxHeight、window.openai.safeArea、window.openai.view、window.openai.userAgent、window.openai.locale 可透過 useOpenAiGlobal 讀取或訂閱這些環境資訊,以調整視覺呈現和文案。

useOpenAiGlobal 輔助函式

許多 ChatGPT UI 專案會將存取 window.openai 的邏輯封裝在小型輔助函式中,以便測試檢視元件。下列輔助函式會監聽主機的 openai:set_globals 事件,讓 React 元件可以訂閱單一全域值:

import { useSyncExternalStore } from "react";

type WebplusGlobals = {
  widgetState: { selectedId?: string | null; [key: string]: unknown } | null;
  toolInput: Record<string, unknown>;
  toolOutput: Record<string, unknown> | null;
  theme: "light" | "dark";
};
const SET_GLOBALS_EVENT_TYPE = "openai:set_globals";

export function useOpenAiGlobal<K extends keyof WebplusGlobals>(
  key: K
): WebplusGlobals[K] {
  return useSyncExternalStore(
    (onChange) => {
      const handleSetGlobal = (event: Event) => {
        if (!(event instanceof CustomEvent)) return;
        const value = event.detail?.globals?.[key];
        if (value === undefined) {
          return;
        }

        onChange();
      };

      window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleSetGlobal, {
        passive: true,
      });

      return () => {
        window.removeEventListener(SET_GLOBALS_EVENT_TYPE, handleSetGlobal);
      };
    },
    () => {
      const globals = (window as Window & { openai?: WebplusGlobals }).openai;
      if (!globals) throw new Error("This hook requires a ChatGPT app host.");
      return globals[key];
    }
  );
}

關閉 UI

呼叫 window.openai.requestClose(),要求 ChatGPT 關閉目前的 UI。

要求切換顯示模式

使用 window.openai.requestDisplayMode 要求以行內、子母畫面或全螢幕模式顯示:

await window.openai?.requestDisplayMode({ mode: "fullscreen" });
// On mobile, picture-in-picture may be presented as fullscreen.

開啟強制回應視窗

使用 window.openai.requestModal 開啟由主機控制的強制回應視窗。可提供同一個 MCP 伺服器註冊的另一個 UI 範本的 URI,或省略 template 以開啟目前的範本:

await window.openai.requestModal({
  template: "ui://widget/details.html",
});

檔案 API

ChatGPT 透過選用的 window.openai 擴充功能提供檔案上傳和下載輔助函式。

API 用途 說明
window.openai.uploadFile(file, { library?: boolean }) 上傳使用者選取的檔案並取得 fileId。 傳入 { library: true } 後,如果目前的使用者可以使用 ChatGPT 檔案庫,上傳的檔案也會儲存到該檔案庫。
window.openai.selectFiles() 開啟檔案庫選擇器,以選取現有檔案。 傳回 [{ fileId, fileName, mimeType }]。部分使用者可能無法使用檔案庫,因此請先檢查是否支援此輔助函式。
window.openai.getFileDownloadUrl({ fileId }) 要求取得檔案的暫時下載 URL。 適用於小工具上傳、從檔案庫選取、透過檔案參數傳入,或由工具以檔案參照傳回的檔案。

ChatGPT 檔案庫是選用功能,部分使用者可能無法使用。若 window.openai.selectFiles() 可用,目前的外掛程式已獲授權存取此函式傳回的檔案。可將傳回的 fileId 傳給 window.openai.getFileDownloadUrl({ fileId }),或用於採用檔案參數的工具輸入。

上傳使用者選取的檔案:

const { fileId } = await window.openai.uploadFile(file, {
  library: true,
});

選取使用者已上傳至 ChatGPT 的檔案:

if (window.openai?.selectFiles) {
  const files = await window.openai.selectFiles();
  // [{ fileId, fileName, mimeType }]
}

請先檢查是否支援 window.openai.selectFiles,若檔案庫無法使用,則改用 window.openai.uploadFile。

要求取得暫時下載 URL:

const { downloadUrl } = await window.openai.getFileDownloadUrl({ fileId });

定義檔案輸入

若要讓 ChatGPT 將檔案傳給工具,請在 _meta["openai/fileParams"] 中列出每個頂層檔案輸入欄位。每個列出的欄位都必須解析為檔案物件或檔案物件陣列。

每個檔案物件的結構描述都必須宣告以下四個支援的屬性:

屬性 型別 在 properties 中宣告 列入 required
download_url string 是 是
file_id string 是 是
mime_type string 是 否
file_name string 是 否

mime_type 和 file_name 的值可以省略,但仍須在結構描述中宣告這兩個屬性。掃描工具步驟和外掛程式提交程序都會拒絕下列檔案結構描述:漏列四個屬性中的任何一個、未將 download_url 和 file_id 兩者都設為必填、將任一選用屬性設為必填,或要求提供 download_url 或 file_id 以外的屬性。可以另外宣告選用屬性。

以下是完整的工具描述項,接受一個必填的檔案輸入:

{
  "name": "analyze_file",
  "title": "Analyze file",
  "description": "Analyzes a user-provided file without modifying it.",
  "inputSchema": {
    "type": "object",
    "$defs": {
      "OpenAIFile": {
        "type": "object",
        "properties": {
          "download_url": { "type": "string" },
          "file_id": { "type": "string" },
          "mime_type": { "type": "string" },
          "file_name": { "type": "string" }
        },
        "required": ["download_url", "file_id"],
        "additionalProperties": false
      }
    },
    "properties": {
      "file": { "$ref": "#/$defs/OpenAIFile" }
    },
    "required": ["file"]
  },
  "annotations": {
    "readOnlyHint": true,
    "openWorldHint": false,
    "destructiveHint": false
  },
  "_meta": {
    "openai/fileParams": ["file"]
  }
}

若要接受多個檔案,請將頂層欄位定義為陣列,並在 items 中使用相同的檔案物件結構描述。工具可以分別設定頂層檔案欄位是否必填,以及各檔案物件內有哪些必填屬性。

執行時,ChatGPT 會傳入檔案值,欄位名稱採用小寫字母與底線:

{
  "download_url": "https://...",
  "file_id": "file_...",
  "mime_type": "image/png",
  "file_name": "input.png"
}

ChatGPT 一律會提供 download_url 和 file_id,但可能省略 mime_type 和 file_name。當小工具需要新的暫時下載 URL 時,請使用 file_id 作為 fileId 的值,並呼叫 window.openai.getFileDownloadUrl({ fileId })。

儲存小工具狀態時,如果希望模型在後續對話回合中能看到圖片 ID,請使用包含 modelContent、privateContent、imageIds 的結構化格式。

由主機支援的導覽

沙盒執行環境會將 iframe 的導覽記錄同步到 ChatGPT UI。使用 React Router 等標準路由 API,主機就會讓導覽控制項與你的 UI 保持同步。

使用 React Router 的 BrowserRouter 設定路由器:

import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  useParams,
} from "react-router-dom";
function PizzaListPlugin() {
  const { placeId } = useParams();
  return (
    <main>
      <Link to="/place/pizzeria">Example Pizzeria</Link>
      <p>{placeId ?? "Choose a place"}</p>
    </main>
  );
}

export default function PizzaListRouter() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<PizzaListPlugin />}>
          <Route path="place/:placeId" element={<PizzaListPlugin />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

以程式控制導覽:

import { createElement } from "react";
import { BrowserRouter, useNavigate } from "react-router-dom";
function NavigationExample() {
  const navigate = useNavigate();

  function openDetails(placeId: string) {
    navigate(`place/${placeId}`, { replace: false });
  }

  function closeDetails() {
    navigate("..", { replace: true });
  }

  return createElement(
    "div",
    null,
    createElement(
      "button",
      { onClick: () => openDetails("pizzeria") },
      "Open details"
    ),
    createElement("button", { onClick: closeDetails }, "Close details")
  );
}

工具描述項參數

依預設,工具描述應包含 MCP 規格列出的欄位。

請為工具宣告 outputSchema,凡是會傳回 structuredContent 的工具都必須宣告此欄位。結構描述應準確反映工具實際傳回的物件,讓用戶端能驗證結果,也讓模型能據此判斷後續如何呼叫工具。

工具描述項的 _meta 欄位

請在工具描述項中使用下列 _meta 欄位。若要將工具連結到 UI 範本,請優先使用 MCP Apps 的標準鍵 _meta.ui.resourceUri。ChatGPT 支援 OpenAI 專屬中繼資料,以維持相容性並提供選用的擴充功能。

鍵 位置 型別 限制 用途
_meta["securitySchemes"] 工具描述項 array 無 提供安全性配置的副本,以相容於只讀取 _meta 的舊版用戶端。
_meta.ui.resourceUri 工具描述項 string(URI) 無 UI 範本的標準資源 URI。
_meta.ui.visibility 工具描述項 string[] 預設為 ["model", "app"] 控制工具可供模型、UI 或兩者使用。app 是 MCP Apps 通訊協定中代表 UI 的識別碼。
_meta["openai/outputTemplate"] 工具描述項 string(URI) 無 ChatGPT 中 _meta.ui.resourceUri 的 OpenAI 專屬選用別名,可用於維持相容性。
_meta["openai/profile"] 工具描述項 boolean 選用。只有 true 表示這是個人資料工具 標示需要驗證身分且會傳回目前個人資料的唯讀工具。實作此工具可協助使用者辨識及管理多個已連結的帳戶。即使未實作,使用者仍可連結多個帳戶。請參閱支援多個帳戶。
_meta["openai/widgetAccessible"] 工具描述項 boolean 預設為 false 現有 UI 整合使用的 OpenAI 專屬相容性欄位。請優先搭配使用 _meta.ui.visibility 和 tools/call。
_meta["openai/visibility"] 工具描述項 string public(預設)或 private 現有 UI 整合使用的 OpenAI 專屬相容性欄位。請優先使用 _meta.ui.visibility。
_meta["openai/toolInvocation/invoking"] 工具描述項 string ≤ 64 個字元 工具執行期間顯示的簡短狀態文字。
_meta["openai/toolInvocation/invoked"] 工具描述項 string ≤ 64 個字元 工具執行完畢後顯示的簡短狀態文字。
_meta["openai/fileParams"] 工具描述項 string[] 無 列出代表檔案的頂層輸入欄位。每個欄位都會收到 { download_url, file_id, mime_type?, file_name? }。

範例:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
const server = new McpServer({ name: "docs-example", version: "1.0.0" });

// Local example data; replace this with your application data.
async function performSearch(query: string) {
  const documents = [
    {
      id: "intro",
      title: "Introduction to Acme",
      url: "https://example.com/intro",
    },
  ];
  return documents.filter((document) =>
    document.title.toLowerCase().includes(query.toLowerCase())
  );
}

import { registerAppTool } from "@modelcontextprotocol/ext-apps/server";
import { z } from "zod";

registerAppTool(
  server,
  "search",
  {
    title: "Public Search",
    description: "Search public documents.",
    inputSchema: { q: z.string() },
    outputSchema: {
      results: z.array(
        z.object({
          id: z.string(),
          title: z.string(),
          url: z.string(),
        })
      ),
    },
    _meta: {
      securitySchemes: [
        { type: "noauth" },
        { type: "oauth2", scopes: ["search.read"] },
      ],
      ui: { resourceUri: "ui://widget/story.html" },
      // Optional compatibility alias (ChatGPT only):
      // "openai/outputTemplate": "ui://widget/story.html",
      "openai/toolInvocation/invoking": "Searching…",
      "openai/toolInvocation/invoked": "Results ready",
    },
  },
  async ({ q }) => {
    const results = await performSearch(q);

    return {
      structuredContent: { results },
      content: [{ type: "text", text: `Found ${results.length} results.` }],
    };
  }
);

註釋

若要將工具標示為「唯讀」,請在工具描述項中使用下列 ToolAnnotations 欄位:

鍵 型別 是否必填 說明
readOnlyHint boolean 必填 表示工具只擷取資訊或進行運算,不會建立、更新或刪除資料,也不會將資料傳送到對話之外。
destructiveHint boolean 必填 表示工具可能會刪除或覆寫使用者資料,讓主機知道必須先要求使用者明確核准。
openWorldHint boolean 必填 表示工具會存取公開網際網路,或與範圍不固定的外部對象互動,包括執行網頁搜尋等唯讀操作。範圍明確的私人帳戶或工作區,即使託管於外部,也不會僅因此就被視為開放環境。
idempotentHint boolean 選用 表示以相同引數重複呼叫工具,不會對其環境造成額外影響。

這些提示只會影響 ChatGPT 或 Codex 向使用者說明工具呼叫的方式。伺服器仍須自行執行授權邏輯。

範例:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
const server = new McpServer({ name: "docs-example", version: "1.0.0" });

// Local example data; replace this with your application data.
async function fetchSavedRecipes() {
  return [{ id: "pasta", title: "Tomato pasta" }];
}

import { z } from "zod";

server.registerTool(
  "list_saved_recipes",
  {
    title: "List saved recipes",
    description: "Returns the user’s saved recipes without modifying them.",
    inputSchema: {},
    outputSchema: {
      recipes: z.array(
        z.object({
          id: z.string(),
          title: z.string(),
        })
      ),
    },
    annotations: { readOnlyHint: true },
  },
  async () => ({
    content: [],
    structuredContent: { recipes: await fetchSavedRecipes() },
  })
);

元件資源的 _meta 欄位

請在提供元件的資源範本(registerResource)中設定這些鍵。ChatGPT 可據此說明 iframe 的內容並設定其顯示方式,同時避免向其他用戶端洩漏中繼資料。

鍵 位置 型別 用途
_meta.ui.prefersBorder 資源內容 boolean 建議在支援的情況下,將元件顯示在有框線的卡片內。
_meta.ui.csp 資源內容 object 建議在此設定小工具的標準 CSP 欄位:connectDomains、resourceDomains 和選用的 frameDomains。
_meta.ui.domain 資源內容 string(來源) 託管元件的專屬來源。提交含有 UI 的外掛程式時必須設定,且各外掛程式的來源不得重複。預設為 https://web-sandbox.oaiusercontent.com。
_meta["openai/ui"].availableDisplayModes 資源內容 string[] 支援的顯示模式包括 inline、fullscreen 和 pip。ChatGPT 可在載入元件前據此選擇顯示模式。
_meta["openai/widgetDescription"] 資源內容 string 元件載入時提供給模型的易讀摘要,可減少助理重複說明。
_meta["openai/widgetPrefersBorder"] 資源內容 boolean ChatGPT 中 _meta.ui.prefersBorder 的 OpenAI 專屬相容性別名。
_meta["openai/widgetCSP"] 資源內容 object ChatGPT 舊版小工具 CSP 中繼資料的相容性鍵。標準 CSP 欄位已改用 _meta.ui.csp,但仍須設定 redirect_domains 來指定受信任的 openExternal 目的地。
_meta["openai/widgetDomain"] 資源內容 string(來源) ChatGPT 中 _meta.ui.domain 的 OpenAI 專屬相容性別名。

ChatGPT 支援舊版相容性鍵 _meta["openai/widgetCSP"],其欄位名稱採用 snake_case 格式:

  • connect_domains:string[]
  • resource_domains:string[]
  • frame_domains?:string[]
  • redirect_domains?:string[]。這是 ChatGPT 擴充功能,用來指定 window.openai.openExternal 的重新導向目標。

開發新的 UI 時,通常建議使用標準的 _meta.ui.csp 物件。支援的欄位如下:

  • connectDomains:string[]。小工具可透過 fetch/XHR 連線的網域。
  • resourceDomains:string[]。提供靜態資源(圖片、字型、指令碼、樣式)的網域。
  • frameDomains?:string[]。選用欄位,列出允許透過 iframe 嵌入的來源。依預設,小工具無法顯示子框架。外掛程式可依照 iframe 政策嵌入自有網域的內容,包括既有的編輯器和管理介面。提交時必須說明使用理由。使用 iframe 可能需要額外審查,也可能延長核准時間。

不過,_meta.ui.csp 不支援 redirect_domains,因此無法透過這個物件指定 window.openai.openExternal(...) 連結的重新導向目標。若要將重新導向目標加入允許清單,仍須設定 _meta["openai/widgetCSP"].redirect_domains。

在 UI 載入前宣告顯示模式

請在伺服器傳回的資源內容中設定 _meta["openai/ui"].availableDisplayModes。如果元件僅支援全螢幕,這項設定可讓 ChatGPT 立即以全螢幕開啟元件,省去先以行內模式顯示載入狀態的步驟。

請在資源的 contents 陣列中傳回以下物件,並將 html 設為元件的 HTML:

const resource = {
  uri: "ui://widget/viewer.html",
  mimeType: "text/html;profile=mcp-app",
  text: html,
  _meta: {
    "openai/ui": {
      availableDisplayModes: ["fullscreen"],
    },
  },
};

請列出元件支援的所有模式,例如 ["inline", "fullscreen"]。在 MCP Apps 初始化期間也應繼續宣告 availableDisplayModes。伺服器端的宣告是對初始化流程的補充,該流程也支援動態顯示模式。

工具結果

工具結果可以包含 MCP 規格列出的欄位。以下幾個欄位尤其值得留意:

鍵 型別 是否必填 說明
structuredContent object 選用 提供給模型和元件。若已宣告 outputSchema,內容必須符合該結構描述。
content string 或 Content[] 選用 提供給模型和元件。
_meta object 選用 僅傳送給元件,模型無法看到。

只有 structuredContent 和 content 會出現在對話記錄中。主機會將 _meta 轉送給元件,讓你可以用這些資料填入 UI,而不會向模型揭露資料。

主機提供的工具結果中繼資料:

鍵 位置 型別 用途
_meta["openai/widgetSessionId"] 工具結果的 _meta(由主機提供) string 目前已掛載的小工具執行個體的穩定 ID。在小工具卸載前,可用此 ID 關聯記錄與工具呼叫。

範例:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
const server = new McpServer({ name: "docs-example", version: "1.0.0" });

// Local example data; replace this with your application data.
function generateZooAnimals(count: number) {
  return Array.from({ length: count }, (_, index) => ({
    id: `animal-${index + 1}`,
    name: `Penguin ${index + 1}`,
    species: "Penguin",
  }));
}

import { registerAppTool } from "@modelcontextprotocol/ext-apps/server";
import { z } from "zod";

registerAppTool(
  server,
  "get_zoo_animals",
  {
    title: "get_zoo_animals",
    inputSchema: { count: z.number().int().min(1).max(20).optional() },
    outputSchema: {
      animals: z.array(
        z.object({
          id: z.string(),
          name: z.string(),
          species: z.string(),
        })
      ),
    },
    _meta: { ui: { resourceUri: "ui://widget/widget.html" } },
  },
  async ({ count = 10 }) => {
    const animals = generateZooAnimals(count);

    return {
      structuredContent: { animals },
      content: [{ type: "text", text: `Here are ${animals.length} animals.` }],
      _meta: {
        allAnimalsById: Object.fromEntries(
          animals.map((animal) => [animal.id, animal])
        ),
      },
    };
  }
);

工具錯誤結果

若要在工具結果中傳回錯誤,請使用下列 _meta 鍵:

鍵 用途 型別 說明
_meta["mcp/www_authenticate"] 錯誤結果 string 或 string[] 提供 RFC 7235 定義的 WWW-Authenticate 驗證要求,以觸發 OAuth 流程。

用戶端提供的 _meta 欄位

鍵 提供時機 型別 用途
_meta["openai/locale"] 初始化及工具呼叫時 string(BCP 47) 要求使用的語言地區設定(舊版用戶端可能會傳送 _meta["webplus/i18n"])。
_meta["openai/userAgent"] 工具呼叫時 string 選用的使用者代理程式資訊,用戶端會盡可能提供,可供分析或調整格式。
_meta["openai/userLocation"] 工具呼叫時 object 大略的位置資訊(city、region、country、timezone、longitude、latitude)。
_meta["openai/subject"] 工具呼叫時 string 傳送給 MCP 伺服器的匿名化使用者 ID,用於實施速率限制及識別使用者。
_meta["openai/session"] 工具呼叫時 string 匿名化的對話 ID,用於關聯同一個 ChatGPT 工作階段中的工具呼叫。
_meta["openai/organization"] 工具呼叫時 string 與目前 ChatGPT 組織相關聯的匿名化組織 ID,僅在可取得時提供。

操作階段的 _meta["openai/userAgent"] 和 _meta["openai/userLocation"] 僅供參考。伺服器絕不可依賴這些欄位做出授權決策,而且即使缺少這些欄位也必須能正常運作。_meta["openai/userAgent"] 是用戶端會盡可能提供的選用中繼資料,無法用來可靠地判斷是哪個主機介面正在呼叫伺服器。

範例:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
const server = new McpServer({ name: "docs-example", version: "1.0.0" });

// Local example data; replace this with your application data.
async function findNearbyCafes(city: unknown) {
  return city === "San Francisco"
    ? [{ name: "Example Cafe", address: "123 Example Street, San Francisco" }]
    : [];
}

function formatIntro(locale: unknown, city: unknown) {
  const location = typeof city === "string" ? city : "your area";
  return locale === "es" ? `Cafés en ${location}` : `Cafes in ${location}`;
}

import { z } from "zod";

server.registerTool(
  "recommend_cafe",
  {
    title: "Recommend a cafe",
    inputSchema: {},
    outputSchema: {
      cafes: z.array(
        z.object({
          name: z.string(),
          address: z.string(),
        })
      ),
    },
  },
  async (_args, { _meta }) => {
    const locale = _meta?.["openai/locale"] ?? "en";
    const userLocation = _meta?.["openai/userLocation"];
    const location =
      typeof userLocation === "object" &&
      userLocation !== null &&
      "city" in userLocation
        ? userLocation.city
        : undefined;
    const cafes = await findNearbyCafes(location);

    return {
      content: [{ type: "text", text: formatIntro(locale, location) }],
      structuredContent: { cafes },
    };
  }
);