Google Workspace Model Context Protocol (MCP) 伺服器會使用伺服器驅動的人工介入迴路核准機制,在 AI 代理執行動作 (例如傳送電子郵件、修改日曆活動、更新或刪除檔案,或讀取資料和中繼資料) 之前,保護使用者資料。這些動作也受到使用者和管理員政策的規範。伺服器會使用 MCP 表單模式引導要求這些核准。
舉例來說,傳送 Gmail 郵件的核准對話方塊可能如下所示:
本指南說明如何連線至 /mcp/v1 端點、設計核准對話方塊以提供最佳使用者體驗,以及在 MCP 主機、MCP 用戶端或代理工具中實作無狀態表單引導通訊協定。
事前準備
實作或設定 MCP 表單誘導功能前,請先完成必要條件、判斷 MCP 主機或用戶端是否需要自訂誘導支援,並查看伺服器端點。
必要條件
在自訂 MCP 主機或用戶端中導入表單引導功能之前,請先完成下列設定:
- 在同一個 Google Cloud 專案中啟用 API 和 MCP 伺服器:在啟用目標 Google Workspace API 和 MCP 伺服器端點的 Google Cloud 專案中,建立 OAuth 2.0 用戶端 ID。建立 OAuth 用戶端時,請選取「讓 AI 輔助代理使用這個用戶端」。如需完整操作說明,請參閱「設定 Google Workspace MCP 伺服器」。
- 要求目標工具所需的 OAuth 2.0 範圍:使用
tools/call呼叫工具時,需要 OAuth 2.0Bearer存取權杖,其中包含該工具所需的範圍,即使tools/list傳回的可用工具與權杖範圍無關。請查看伺服器的 MCP 參考總覽頁面,瞭解各項工具所需的 OAuth 範圍。
確認是否需要導入表單誘導
建議您使用 MCP 表單引導功能連線至 /mcp/v1 端點,讓代理存取完整的 Google Workspace 工具和結果。是否需要編寫程式碼,取決於 MCP 主機和 MCP 用戶端的建構方式:
- 設定預先建構的 MCP 代管應用程式:如果您連結的是預先建構的 MCP 代管應用程式 (例如支援 MCP 表單引導的 Google Antigravity 或 Claude Desktop),就不需要編寫表單引導程式碼:
- 連線至
/mcp/v1端點。如需設定步驟,請參閱「設定 Google Workspace MCP 伺服器」。 - 將主機內建的本機工具確認設定設為「一律允許」,以便在
/mcp/v1上使用 Google Workspace MCP 伺服器,這樣使用者就不會重複收到相同動作的提示。 - 如果預先建構的 MCP 主機尚未支援表單提示,您可以連線至受限的
/mcp/v1self備用端點,該端點會公開不需表單提示即可使用的工具,但特定呼叫可能仍需核准。
- 連線至
- 將 MCP 用戶端 SDK 或代理框架整合至 MCP 主機:如果您使用的 MCP 用戶端程式庫或代理框架 (例如 Agent Development Kit (ADK)) 已在通訊協定層處理表單引導,您仍需將其引導處理常式連結至 MCP 主機的 UI 或 CLI 介面。請按照本指南中的核准 UI 建議操作,在
/mcp/v1上提供最佳使用者體驗。 - 建構自訂 MCP 用戶端和主機:如果您要建構自己的 MCP 用戶端和主機整合,請實作無狀態表單引導通訊協定,以及本指南中的核准 UI 建議,以便連線至
/mcp/v1。
伺服器端點
正式發布的 Google Workspace MCP 伺服器和 Universal Search MCP 伺服器提供主要 /mcp/v1 端點,以及有限的 /mcp/v1self 備用端點:
| 端點 | 伺服器網址 | 表單引導要求 | 可用的工具 |
|---|---|---|---|
/mcp/v1 |
|
建議的主要端點。與 mode: "form" 誘導搭配使用。 |
公開伺服器的所有工具和完整結果集,包括預設政策下一律需要使用者核准的工具。 |
/mcp/v1self |
|
備用端點。視政策和目標資源而定,特定呼叫可能仍需要表單引導。 |
省略預設政策下一律需要核准的工具,只顯示不需表單引導即可使用的工具,例如 update_doc。list_threads 等清單和搜尋方法只會傳回不需核准即可存取的結果子集,而不會提示要求完整存取權。 |
請盡可能搭配表單誘導使用 /mcp/v1,並將 /mcp/v1self 保留給無法新增表單誘導支援的 MCP 主機。如果用戶端呼叫工具的方式需要使用者在任一端點核准,但未宣告支援表單資訊收集,伺服器會封鎖呼叫並傳回 MissingRequiredClientCapability 錯誤。
如要查看各項服務在 /mcp/v1 和 /mcp/v1self 上可用的工具,請參閱伺服器的工具參考資料總覽頁面:
- Gmail MCP 參考資料
- 雲端硬碟 MCP 參考資料
- Docs MCP 參考資料
- Google 試算表 MCP 參考資料
- Google 簡報 MCP 參考資料
- Calendar MCP 參考資料
- Chat MCP 參考資料
- Universal Search MCP 參考資料
表單誘導的運作方式
Google Workspace MCP 伺服器會根據 2026-07-28 MCP Elicitation 規格,使用無狀態、單一連線要求和重試流程。
表單誘導生命週期包含下列步驟:
- 使用者提示:使用者要求代理執行動作,例如建立日曆活動。
- 初始
tools/call要求:MCP 用戶端會向/mcp/v1端點傳送tools/call要求,要求create_event等工具,並在params._meta中宣告elicitation功能。 InputRequiredResult敬請採取行動:如果要求的動作需要使用者核准,伺服器會先暫停執行,再執行工具。伺服器會傳回result物件,其中包含resultType: "input_required"、以"approval_choice"為索引鍵的inputRequests對應 (包含elicitation/create要求和mode: "form"),以及不透明的requestState字串。- 核准對話方塊:MCP 用戶端會顯示核准對話方塊,其中包含目標 Google Workspace 產品和工具、Markdown 確認訊息、決策問題,以及
enum和enumNames允許的選項。 - 使用者決定:使用者選取核准選項,例如「僅允許一次」或「不允許」。
- 使用
inputResponses和requestState重試tools/call:MCP 用戶端會傳送第二個tools/call要求,其中包含相同的工具name和arguments,以及頂層params.requestState和params.inputResponses欄位,其中包含使用者為"approval_choice"選取的選項。 - 工具執行結果:伺服器會驗證
requestState是否繫結至初始呼叫中的確切工具引數、評估使用者的決定、執行或結束工具呼叫,並傳回最終的result和resultType: "complete"。
有人要求核准時
工具呼叫是否會觸發 elicitation/create 驗證,是由 Google Workspace MCP 伺服器根據系統、使用者和管理員管理政策動態決定。政策評估可考量下列因素:
- 動作類型:根據預設,與目標對象共用資料或修改共用資源的寫入動作,需要使用者確認,除非使用者或管理員政策允許。而建立私人檔案等自我寫入動作,則預設不需確認即可執行。移至垃圾桶動作一律需要每次呼叫確認,不提供永久核准,而讀取或中繼資料動作也可能需要確認,具體取決於使用者或管理員政策。
- 內容擁有權和瀏覽權限:存取或修改其他使用者擁有的檔案,或與使用者所屬機構外部共用檔案,可能需要經過核准。
- 外部收件者:傳送郵件、共用檔案或邀請使用者網域以外的與會者時,通常需要明確確認。
- 使用者和管理員偏好設定:先前交易儲存的核准偏好設定,或全網域管理員規則,可能會要求或略過特定工具的確認。
由於每次呼叫都會在伺服器端進行政策評估,因此用戶端必須準備好在任何 tools/call 叫用時處理 InputRequiredResult 回應。請勿在用戶端硬式編碼工具敏感度規則,或快取核准決策。
核准選項參考資料
在 requestedSchema.properties.approval_choice 中,伺服器會傳回平行的 enum 和 enumNames 陣列,代表目前要求可用的選項。所有 Google Workspace MCP 伺服器都支援下列 enum 值:
enum值 |
預設英文 enumNames 標籤 |
允許執行 | 提供時機和行為 |
|---|---|---|---|
ALLOW_ONCE |
允許一次 | 是 | 每次出現核准提示時,都會提供這個選項。執行目前的工具呼叫一次,不記錄永久規則。 |
DENY_ONCE |
不允許 | 否 |
每次出現核准提示時,都會提供這個選項。以 UserDeniedAction 錯誤結束目前的工具呼叫,不記錄永久規則。 |
ALLOW_TOOL_ALWAYS |
一律允許這項工具 | 是 | 如果使用者和管理員政策允許工具層級的永久核准,系統就會提供這個選項。執行目前的呼叫,並預先核准同一個代理日後對相同工具的呼叫。 |
ALLOW_RESOURCE_ALWAYS |
一律允許對這個檔案/資料夾/雲端硬碟/電子郵件/活動/聊天室/ 即時通訊/群組通訊/工作/項目提出的要求 | 是 | 修改或存取最多 100 個相同類型的資源時,系統會提供這項功能。如果呼叫指定多項資源,請使用複數用詞,例如「一律允許對這些檔案提出的要求」。執行目前的呼叫,並預先核准相同代理對相同資源 ID 的後續呼叫。 |
ALLOW_AUDIENCE_ALWAYS |
一律允許對這位/這些收件者提出的要求 | 是 | 適用於傳送、分享和邀請動作,最多可指定 100 位收件者。執行目前的呼叫,並預先核准日後從相同代理程式到相同收件者組合的呼叫。 |
ALLOW_OWNER_ALWAYS |
一律允許對這位/這些擁有者提出的要求 | 是 | 讀取或基準提示涉及最多 3 位不同擁有者的項目時,可使用這項功能。執行目前的呼叫,並預先核准同一代理日後對這些使用者擁有的項目發出的呼叫。 |
任何個別 InputRequiredResult 只會包含適用於該特定工具呼叫的選項子集:
- 破壞性和垃圾桶動作:永久刪除或移至垃圾桶的動作,或由管理員政策控管、每次呼叫都需要確認的動作,僅提供
ALLOW_ONCE和DENY_ONCE。 - 範圍動作:如果允許永久核准,伺服器會傳回
ALLOW_ONCE、適用的窄範圍 (例如ALLOW_AUDIENCE_ALWAYS或ALLOW_RESOURCE_ALWAYS)、ALLOW_TOOL_ALWAYS和DENY_ONCE。
請一律顯示 enum 和 enumNames 為目前要求傳回的確切選項,而非硬式編碼按鈕值。
建議做法,提供最佳使用者體驗
支援表單資訊擷取的標準 MCP 用戶端可直接與 /mcp/v1 搭配使用。不過,一般表單轉譯器通常會將單選決策顯示為圓形按鈕群組或下拉式選單,並搭配獨立的「提交」按鈕,這需要額外點擊,且會隱藏目標 Google Workspace 應用程式內容。
為提供最佳的表單誘導使用者體驗,請在 MCP 用戶端中實作下列五項建議。建議 1 到 3 對應下列核准對話方塊插圖中的編號標註:
1. 顯示產品名稱、圖示和工具
使用者應能立即看出代理要呼叫的 Google Workspace 產品和工具:
- 將 MCP 伺服器的
serverInfo中繼資料 (來自初始化或server/discover),或要求主機名稱 (例如calendarmcp.googleapis.com),對應至 Google Workspace 產品名稱和圖示。 - 將
InputRequiredResult上的_meta呈現提示 (例如title、icons和isConfirmation) 視為選用強化功能。正式版 Google Workspace MCP 伺服器尚未發出這些_meta欄位,因此 UI 不應依賴這些欄位。 - 顯示
params.name的目標工具名稱,方便使用者區分create_draft和create_event等作業。
2. 顯示伺服器訊息和enumNames
請保持用戶端呈現層簡單,並直接轉譯伺服器提供的核准內容:
- 將
params.message轉譯為 Markdown 並顯示approval_choice.title: Google Workspace MCP 伺服器已將動作詳細資料格式化為inputRequests.approval_choice.params.message中的 Markdown,並在requestedSchema.properties.approval_choice.title中提供本地化的確認問題。直接使用安全的 Markdown 轉譯器轉譯message,而不是顯示原始 Markdown 符號或編寫自訂的工具引數格式邏輯,並在動作按鈕上方清楚顯示title。 - 將
enum值與enumNames標籤配對:動態檢查requestedSchema.properties.approval_choice。將enum中的每個 ID 與enumNames中相同索引的人類可讀標籤配對,如果與使用oneOf的其他 MCP 伺服器互動,則會改用 JSON 結構定義oneOf項目。
3. 一鍵簡化決策
當 requestedSchema 包含單一列舉屬性時,請避免顯示需要另外點選「提交」的圓形按鈕清單或下拉式選單:
- 兩個選項,例如
Allow once和Don't allow:並排顯示兩個按鈕。點選任一按鈕後,系統會立即提交重試要求。 - 多個允許選項:當伺服器傳回
ALLOW_ONCE、一或多個永久允許範圍 (例如ALLOW_AUDIENCE_ALWAYS或ALLOW_TOOL_ALWAYS) 和DENY_ONCE時,系統會顯示主要分割按鈕,預設為「僅允許一次」,並提供插入點選單,用於顯示其他允許選項,以及獨立的「不允許」按鈕。
在模式 A 中,破壞性雲端硬碟動作只會傳回 ALLOW_ONCE 和 DENY_ONCE,用戶端會將其轉譯為兩個並排按鈕,分別是「不允許」和「僅允許一次」。在模式 B 中,Gmail 動作會傳回 ALLOW_ONCE、ALLOW_AUDIENCE_ALWAYS、ALLOW_TOOL_ALWAYS 和 DENY_ONCE,用戶端會將其轉譯為「不允許」按鈕,以及「僅允許一次」分割按鈕,其選單會顯示永久允許選項。
4. 避免在/mcp/v1上重複顯示提示
許多 MCP 主機在執行任何外部工具前,都會顯示內建的本機確認提示。呼叫 Google Workspace MCP 伺服器時,如果啟用表單提示,本機預先執行提示會建立多餘的雙重提示體驗,因為伺服器會強制執行自己的政策感知提示驗證。
- 如果您要設定預先建構的 MCP 主機,並使用表單提示:請將
/mcp/v1上 Google Workspace MCP 伺服器的主機本機工具確認設定設為「一律允許」,並依賴伺服器啟動的提示對話方塊。如果主機不支援表單引導,且連線至/mcp/v1self,請保持啟用本機工具確認功能,以便在呼叫未觸發伺服器端核准時,顯示用戶端提示。 - 如果您正在建構 MCP 主機:當
*mcp.googleapis.com和people.googleapis.com啟用表單誘導功能時,請隱藏主機的一般預先呼叫確認對話方塊,例如gmailmcp.googleapis.com、calendarmcp.googleapis.com、drivemcp.googleapis.com和workspacemcp.googleapis.com。只有在伺服器傳回含有resultType: "input_required"的InputRequiredResult時,才提示使用者。
5. 引導代理行為,決定是否使用工具和拒絕要求
推論模型可能會以兩種方式誤解人工介入迴路核准流程:
- 預先避免寫入工具:如果模型假設呼叫寫入工具 (例如
send_message) 會立即執行,而不需要使用者審查,則即使使用者要求傳送電子郵件,模型也可能會改用草稿工具 (例如create_draft)。 - 拒絕後改用其他寫入工具重試:如果使用者在核准對話方塊中點選「不允許」,且伺服器傳回
UserDeniedAction錯誤結果,模型可能會將拒絕視為暫時性工具失敗,並嘗試使用其他寫入工具達成相同目標,進而觸發不必要的第二次核准提示。
為避免這兩種問題,請在代理的系統提示中加入下列指示:
提示詞
When calling Google Workspace MCP tools:
1. Select the tool that directly matches the user's intent (for example,
use send_message when asked to send an email). Sensitive tools
automatically pause for user confirmation through MCP form elicitation
before executing.
2. If a tool call fails because the user denied, declined, or canceled the
approval request, stop immediately and acknowledge the user's decision.
Do not retry the same action or call an alternative write tool unless
the user explicitly asks you to do so in a new message.
傳輸和無狀態通訊協定規定
Google Workspace MCP 伺服器透過無狀態 Streamable HTTP 運作。建構自訂 MCP 用戶端時,請在每項要求中遵循下列傳輸規定:
- HTTP 標頭:在傳送至
/mcp/v1的所有POST要求中,加入下列標頭:Authorization: Bearer ACCESS_TOKENContent-Type: application/jsonAccept: application/json, text/event-streamMCP-Protocol-Version: 2026-07-28Accept-Language: BCP_47_LANGUAGE_TAG,將確認訊息、問題和enumNames標籤本地化為使用者偏好的語言,例如es-419, es;q=0.9, en;q=0.8。如省略,文字預設為en-US。
- 回應內容類型:視伺服器和要求類型而定,HTTP 回應主體可以格式化為標準 JSON (
Content-Type: application/json),或伺服器傳送事件 (SSE) (Content-Type: text/event-stream),其中 JSON-RPC 酬載會顯示在data: {...}行。HTTP 傳輸剖析器必須接受這兩種格式。 - 無狀態探索:Google Workspace MCP 伺服器不會維護有狀態
initialize工作階段。如要在啟動時擷取伺服器中繼資料和功能,請傳送包含"method": "server/discover"和"params": {}的 JSON-RPC 要求,系統會在result._meta["io.modelcontextprotocol/serverInfo"]中傳回伺服器中繼資料。自訂確認_meta提示 (例如isConfirmation、title和icons) 尚未在正式版InputRequiredResult回應中發出,因此請一律將_meta顯示欄位視為選用,並改用serverInfo或伺服器主機名稱。 - 每個要求的
_meta功能:由於傳輸作業不具狀態,請在每個tools/list和tools/call要求的params內加入_meta,並使用下列鍵:"io.modelcontextprotocol/protocolVersion": "2026-07-28""io.modelcontextprotocol/clientInfo":{"name": "YOUR_APP_NAME","version": "VERSION"}"io.modelcontextprotocol/clientCapabilities":{"elicitation": {"form": {}}}
錯誤處理和參數繫結
如果工具呼叫遭到封鎖,或重試驗證失敗,伺服器會根據失敗類別,傳回工具層級錯誤結果或頂層 JSON-RPC 錯誤物件:
UserDeniedAction和AdminPolicyBlock:如果使用者拒絕核准提示,或管理員政策封鎖動作,伺服器會傳回 JSON-RPCresult,其中包含"resultType": "complete"、"isError": true,以及result.content中的本地化錯誤訊息。如果為服務和環境啟用這項功能,伺服器也會在result._meta["google.com/error"]中加入結構化錯誤中繼資料。由於result._meta["google.com/error"]是依服務和環境進行閘道控制,因此當result._meta["google.com/error"]不存在時,用戶端必須改為從result.content讀取錯誤訊息:UserDeniedAction:使用者選取「DENY_ONCE」、拒絕或取消核准表單時傳回。預設的英文訊息為"Action canceled. The user declined the confirmation request."AdminPolicyBlock:如果組織管理員政策禁止代理執行作業,就會傳回這個錯誤。預設的英文訊息為"Action could not be completed. Your administrator has blocked third-party agents from performing this action."
JSON
{ "jsonrpc": "2.0", "id": 3, "result": { "resultType": "complete", "isError": true, "content": [ { "type": "text", "text": "Action canceled. The user declined the confirmation request." } ], "_meta": { "google.com/error": { "code": 400, "message": "Action canceled. The user declined the confirmation request.", "status": "FAILED_PRECONDITION", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "UserDeniedAction", "domain": "mcp.googleapis.com" } ] } } } }MissingRequiredClientCapability:如果用戶端呼叫工具的方式需要使用者在/mcp/v1或/mcp/v1self上確認,但未在_meta["io.modelcontextprotocol/clientCapabilities"]中宣告表單引導支援,就會傳回這個錯誤。伺服器會將這項錯誤轉譯為頂層 JSON-RPCerror物件,其中包含代碼-32021和error.data.requiredCapabilities中的必要功能物件:JSON
{ "jsonrpc": "2.0", "id": 2, "error": { "code": -32021, "message": "Action could not be completed. This action requires user confirmation, which this client does not support. Use a client that supports form elicitation to perform this action.", "data": { "requiredCapabilities": { "elicitation": { "form": {} } } } } }強制執行參數繫結:
requestState內的requestBinding權杖會以加密方式,將初始核准驗證繫結至第一次呼叫時傳送的確切工具arguments。如果用戶端在重試呼叫時修改params.arguments中的任何欄位,或傳遞格式錯誤或未繫結的params.requestState,伺服器會忽略無效的核准並傳回新的InputRequiredResult驗證問題,或傳回無效參數或失敗的前提條件錯誤,指示用戶端在不使用inputResponses的情況下重試。
導入範例
下列端對端逐步操作說明示範 MCP 用戶端如何呼叫日曆 create_event 工具、在瀏覽器 UI 或終端機 CLI 中算繪伺服器的核准提示,並以 TypeScript 和 Python 提交使用者的決定,接著提供可重複使用的代理技能,用於編寫代理程式。
客戶核准介面
在瀏覽器型 MCP 用戶端中,TypeScript 實作會顯示視覺化核准資訊卡,其中包含日曆圖示、伺服器主機名稱、工具名稱、伺服器轉譯的 Markdown message 預覽畫面、確認問題、「不允許」按鈕,以及「允許一次」分割按鈕:
在終端機型 MCP 用戶端中,Python CLI 實作會將相同的 InputRequiredResult 酬載轉譯為互動式編號提示:
CLI
=== Google Calendar (create_event) ===
Architecture Review
Tue, Oct 20 · 10:00 - 10:30 AM PDT · 🟢 No calendar conflicts
You, dana@example.com, sam@example.com
Conferencing: Google Meet
Allow Cymbal Agent to use create_event for these recipients?
[1] Allow once (ALLOW_ONCE)
[2] Always allow for these recipients (ALLOW_AUDIENCE_ALWAYS)
[3] Always allow this tool (ALLOW_TOOL_ALWAYS)
[4] Don't allow (DENY_ONCE)
Enter choice (1-4, or c to cancel):
初始呼叫和引導回應
用戶端會先傳送 tools/call 要求,使用 create_event 工具建立日曆活動:
JSON
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "create_event",
"arguments": {
"calendarId": "primary",
"summary": "Architecture Review",
"startTime": "2026-10-20T10:00:00",
"endTime": "2026-10-20T10:30:00",
"timeZone": "America/Los_Angeles",
"attendees": [
{
"email": "dana@example.com"
},
{
"email": "sam@example.com"
}
],
"addGoogleMeetUrl": true
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "Cymbal Agent",
"version": "1.0.0"
},
"io.modelcontextprotocol/clientCapabilities": {
"elicitation": {
"form": {}
}
}
}
}
}
如果需要核准,伺服器會傳回 InputRequiredResult:
JSON
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "input_required",
"inputRequests": {
"approval_choice": {
"method": "elicitation/create",
"params": {
"mode": "form",
"message": "**Architecture Review** \nTue, Oct 20 · 10:00 - 10:30 AM PDT · 🟢 No calendar conflicts \nYou, dana@example.com, sam@example.com \n**Conferencing:** Google Meet",
"requestedSchema": {
"type": "object",
"required": ["approval_choice"],
"properties": {
"approval_choice": {
"type": "string",
"title": "Allow Cymbal Agent to use create_event for these recipients?",
"enum": [
"ALLOW_ONCE",
"ALLOW_AUDIENCE_ALWAYS",
"ALLOW_TOOL_ALWAYS",
"DENY_ONCE"
],
"enumNames": [
"Allow once",
"Always allow for these recipients",
"Always allow this tool",
"Don't allow"
]
}
}
}
}
}
},
"requestState": "{\"elicitationId\":\"...\",\"requestBinding\":\"...\"}"
}
}
InputRequiredResult 回應包含下列重要欄位:
result.resultType:伺服器暫停執行以等待使用者輸入時,設為"input_required";工具執行完畢時,設為"complete"。result.inputRequests:以要求 ID"approval_choice"為鍵的地圖。每個項目都有"method": "elicitation/create"和含有"mode": "form"的params物件。_meta顯示提示:isConfirmation、title和icons等選項欄位尚未在正式版InputRequiredResult回應中發出。請一律將_meta欄位視為選用,並從serverInfo或伺服器主機名稱 (如果沒有) 解析 產品名稱和圖示。inputRequests.approval_choice.params.message:伺服器產生的動作預覽畫面 (Markdown 格式),或確認問題 (如果工具未產生獨立的預覽資訊卡)。inputRequests.approval_choice.params.requestedSchema:JSON 結構定義物件,其properties.approval_choice定義包含下列欄位:title:本地化的確認問題,例如"Allow Cymbal Agent to use create_event for these recipients?"。當您在要求中提供_meta["io.modelcontextprotocol/clientInfo"].name時,伺服器會將應用程式名稱納入這個問題。enum:ApprovalChoiceID 的排序陣列,例如ALLOW_ONCE、ALLOW_AUDIENCE_ALWAYS、ALLOW_TOOL_ALWAYS和DENY_ONCE。enumNames:與enum中各項目對應的本地化人類可讀標籤平行陣列,例如Allow once、Always allow for these recipients、Always allow this tool和Don't allow。
result.requestState:不透明的 JSON 編碼字串,包含伺服器的elicitationId和加密requestBinding權杖。重試呼叫時,您必須在params.requestState中原封不動地回傳這個字串。
重試、拒絕和取消酬載
使用者選取允許選項後,請傳送第二個 tools/call 要求,其中包含完全相同的 name 和 arguments,並將 requestState 和 inputResponses 做為 params 內的頂層欄位傳遞:
JSON
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "create_event",
"arguments": {
"calendarId": "primary",
"summary": "Architecture Review",
"startTime": "2026-10-20T10:00:00",
"endTime": "2026-10-20T10:30:00",
"timeZone": "America/Los_Angeles",
"attendees": [
{
"email": "dana@example.com"
},
{
"email": "sam@example.com"
}
],
"addGoogleMeetUrl": true
},
"requestState": "{\"elicitationId\":\"...\",\"requestBinding\":\"...\"}",
"inputResponses": {
"approval_choice": {
"action": "accept",
"content": {
"approval_choice": "ALLOW_ONCE"
}
}
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "Cymbal Agent",
"version": "1.0.0"
},
"io.modelcontextprotocol/clientCapabilities": {
"elicitation": {
"form": {}
}
}
}
}
}
MCP 誘導規格會區分提交表單值和關閉對話方塊。您可以透過兩種方式,在 params.inputResponses 中表示使用者拒絕:
提交
DENY_ONCE選項:使用者點選與DENY_ONCE對應的「不允許」按鈕時,傳送"action": "accept"和"content": {"approval_choice": "DENY_ONCE"}:JSON
{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "create_event", "arguments": { "calendarId": "primary", "summary": "Architecture Review", "startTime": "2026-10-20T10:00:00", "endTime": "2026-10-20T10:30:00", "timeZone": "America/Los_Angeles", "attendees": [ { "email": "dana@example.com" }, { "email": "sam@example.com" } ], "addGoogleMeetUrl": true }, "requestState": "{\"elicitationId\":\"...\",\"requestBinding\":\"...\"}", "inputResponses": { "approval_choice": { "action": "accept", "content": { "approval_choice": "DENY_ONCE" } } }, "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": { "name": "Cymbal Agent", "version": "1.0.0" }, "io.modelcontextprotocol/clientCapabilities": { "elicitation": { "form": {} } } } } }拒絕或取消對話方塊:如果使用者關閉或取消對話方塊,但未選取允許選項,請傳送
"action": "decline"或"action": "cancel",並省略content欄位:JSON
"inputResponses": { "approval_choice": { "action": "cancel" } }
無論是哪種情況,伺服器都會將回應視為 DENY_ONCE,結束工具執行作業,並傳回工具錯誤結果。
TypeScript 網頁用戶端
以下 TypeScript 範例會直接從 InputRequiredResult 酬載中擷取 Markdown message、確認問題和允許的選項,並從選用的 _meta 提示或伺服器主機名稱解析產品名稱,然後根據使用者的決定重播 tools/call:
TypeScript
const PROTOCOL_VERSION = "2026-07-28";
const CLIENT_INFO = { name: "Cymbal Agent", version: "1.0.0" };
const MAX_ELICITATION_ROUNDS = 3;
const HOST_TITLES: Record<string, string> = {
"gmailmcp.googleapis.com": "Gmail",
"calendarmcp.googleapis.com": "Google Calendar",
"drivemcp.googleapis.com": "Google Drive",
"docsmcp.googleapis.com": "Google Docs",
"sheetsmcp.googleapis.com": "Google Sheets",
"slidesmcp.googleapis.com": "Google Slides",
"chatmcp.googleapis.com": "Google Chat",
"people.googleapis.com": "Google Contacts",
"tasksmcp.googleapis.com": "Google Tasks",
"workspacemcp.googleapis.com": "Google Workspace",
};
interface ElicitationOption {
value: string;
label: string;
}
export interface ElicitationCardModel {
requestKey: string;
serverTitle: string;
serverIconUrl?: string;
toolName: string;
markdownMessage: string;
questionTitle: string;
decisionFieldKey: string;
denyOption?: ElicitationOption;
primaryAllowOption?: ElicitationOption;
secondaryAllowOptions: ElicitationOption[];
}
function buildBaseMeta(): Record<string, unknown> {
return {
"io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
"io.modelcontextprotocol/clientInfo": CLIENT_INFO,
"io.modelcontextprotocol/clientCapabilities": {
elicitation: { form: {} },
},
};
}
/**
* Extracts a UI view model directly from an InputRequiredResult response.
* Render card.markdownMessage with a safe Markdown renderer in your UI.
*/
export function extractCardModel(
rpcResult: Record<string, any>,
toolName: string,
serverHost = "workspacemcp.googleapis.com",
): ElicitationCardModel | null {
const inputRequests: Record<string, any> = rpcResult.inputRequests ?? {};
const requestEntry = Object.entries(inputRequests).find(
([, req]: [string, any]) =>
req?.method === "elicitation/create" && req?.params?.mode === "form",
);
if (!requestEntry) {
return null;
}
const [requestKey, elicitationReq] = requestEntry;
const reqMeta = elicitationReq.params?._meta ?? {};
const resultMeta = rpcResult._meta ?? {};
const serverInfo = resultMeta["io.modelcontextprotocol/serverInfo"] ?? {};
const icons: Array<{ src: string; mimeType?: string }> =
reqMeta.icons ?? resultMeta.icons ?? serverInfo.icons ?? [];
const preferredIcon =
icons.find((icon) => icon.mimeType === "image/svg+xml") ?? icons[0];
const properties: Record<string, any> =
elicitationReq.params?.requestedSchema?.properties ?? {};
const firstProperty = Object.entries(properties)[0];
if (!firstProperty) {
return null;
}
const [decisionFieldKey, fieldSchema] = firstProperty as [
string,
Record<string, any>,
];
let options: ElicitationOption[] = [];
if (Array.isArray(fieldSchema.enum)) {
const enumNames: string[] = Array.isArray(fieldSchema.enumNames)
? fieldSchema.enumNames
: [];
options = fieldSchema.enum.map((val: string, idx: number) => ({
value: val,
label: enumNames[idx] ?? val,
}));
} else if (Array.isArray(fieldSchema.oneOf)) {
options = fieldSchema.oneOf.map((opt: any) => ({
value: opt.const,
label: opt.title ?? opt.const,
}));
}
const denyOption = options.find((opt) => opt.value.startsWith("DENY"));
const allowOptions = options.filter(
(opt) => !opt.value.startsWith("DENY"),
);
return {
requestKey,
serverTitle:
reqMeta.title ??
resultMeta.title ??
serverInfo.title ??
serverInfo.name ??
HOST_TITLES[serverHost] ??
"Google Workspace",
serverIconUrl: preferredIcon?.src,
toolName,
markdownMessage:
elicitationReq.params?.message ?? "Confirm this action.",
questionTitle: fieldSchema.title ?? "Confirm this action?",
decisionFieldKey,
denyOption,
primaryAllowOption: allowOptions[0],
secondaryAllowOptions: allowOptions.slice(1),
};
}
/**
* Executes tools/call and replays with requestState and inputResponses
* when the server returns an InputRequiredResult.
*/
export async function handleToolCallWithElicitation(
sendRpc: (payload: Record<string, unknown>) => Promise<Record<string, any>>,
promptUserInUi: (card: ElicitationCardModel) => Promise<string | null>,
toolName: string,
toolArgs: Record<string, unknown>,
serverHost = "calendarmcp.googleapis.com",
): Promise<Record<string, any>> {
let requestId = 1;
let response = await sendRpc({
jsonrpc: "2.0",
id: requestId,
method: "tools/call",
params: {
name: toolName,
arguments: structuredClone(toolArgs),
_meta: buildBaseMeta(),
},
});
for (let round = 0; round < MAX_ELICITATION_ROUNDS; round++) {
const result = response.result ?? {};
if (result.resultType !== "input_required") {
return response;
}
const card = extractCardModel(result, toolName, serverHost);
if (!card) {
return response;
}
const selectedValue = await promptUserInUi(card);
const userResponse = selectedValue
? {
action: "accept",
content: { [card.decisionFieldKey]: selectedValue },
}
: { action: "cancel" };
requestId += 1;
response = await sendRpc({
jsonrpc: "2.0",
id: requestId,
method: "tools/call",
params: {
name: toolName,
arguments: structuredClone(toolArgs),
...(result.requestState !== undefined
? { requestState: result.requestState }
: {}),
inputResponses: {
[card.requestKey]: userResponse,
},
_meta: buildBaseMeta(),
},
});
}
return response;
}
Python CLI 用戶端
Python
import copy
import re
from typing import Any
PROTOCOL_VERSION = "2026-07-28"
CLIENT_INFO = {"name": "Cymbal CLI Agent", "version": "1.0.0"}
MAX_ELICITATION_ROUNDS = 3
HOST_TITLES = {
"gmailmcp.googleapis.com": "Gmail",
"calendarmcp.googleapis.com": "Google Calendar",
"drivemcp.googleapis.com": "Google Drive",
"docsmcp.googleapis.com": "Google Docs",
"sheetsmcp.googleapis.com": "Google Sheets",
"slidesmcp.googleapis.com": "Google Slides",
"chatmcp.googleapis.com": "Google Chat",
"people.googleapis.com": "Google Contacts",
"tasksmcp.googleapis.com": "Google Tasks",
"workspacemcp.googleapis.com": "Google Workspace",
}
def build_base_meta() -> dict[str, Any]:
"""Returns the required per-request _meta block for /mcp/v1 calls."""
return {
"io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
"io.modelcontextprotocol/clientInfo": CLIENT_INFO,
"io.modelcontextprotocol/clientCapabilities": {
"elicitation": {"form": {}}
},
}
def strip_markdown(text: str) -> str:
"""Minimal example that strips basic Markdown for terminal display."""
text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", text)
text = re.sub(r"\*\*(.*?)\*\*", r"\1", text)
return re.sub(r"`([^`]+)`", r"\1", text)
def extract_decision_options(
requested_schema: dict[str, Any],
) -> tuple[str | None, str, list[dict[str, str]]]:
"""Extracts the property key, question title, and options from schema."""
properties = requested_schema.get("properties", {})
first_entry = next(iter(properties.items()), None)
if first_entry is None:
return None, "Confirm this action?", []
field_key, field_schema = first_entry
question_title = field_schema.get("title", "Confirm this action?")
if "enum" in field_schema:
enum_values = field_schema.get("enum", [])
enum_names = field_schema.get("enumNames", [])
options = [
{
"value": val,
"label": enum_names[idx] if idx < len(enum_names) else val,
}
for idx, val in enumerate(enum_values)
]
elif "oneOf" in field_schema:
options = [
{
"value": item["const"],
"label": item.get("title", item["const"]),
}
for item in field_schema["oneOf"]
]
else:
options = []
return field_key, question_title, options
def prompt_user_in_cli(
elicitation_req: dict[str, Any],
result_meta: dict[str, Any],
tool_name: str,
server_host: str = "calendarmcp.googleapis.com",
) -> dict[str, Any]:
"""Renders a CLI approval prompt and returns the inputResponses entry."""
params = elicitation_req.get("params", {})
req_meta = params.get("_meta", {})
server_info = result_meta.get(
"io.modelcontextprotocol/serverInfo", {}
)
server_title = (
req_meta.get("title")
or result_meta.get("title")
or server_info.get("title")
or server_info.get("name")
or HOST_TITLES.get(server_host, "Google Workspace MCP")
)
message = strip_markdown(params.get("message", "Confirm this action."))
field_key, question_title, options = extract_decision_options(
params.get("requestedSchema", {})
)
if not field_key or not options:
return {"action": "cancel"}
print(f"\n=== {server_title} ({tool_name}) ===")
print(message)
print(f"\n{strip_markdown(question_title)}")
for idx, opt in enumerate(options, start=1):
print(f" [{idx}] {opt['label']} ({opt['value']})")
choice = input(
f"Enter choice (1-{len(options)}, or c to cancel): "
).strip()
try:
selected_idx = int(choice) - 1
if 0 <= selected_idx < len(options):
selected_value = options[selected_idx]["value"]
return {
"action": "accept",
"content": {field_key: selected_value},
}
except ValueError:
pass
return {"action": "cancel"}
def handle_tool_call_with_elicitation(
send_rpc_fn: Any, tool_name: str, tool_args: dict[str, Any]
) -> dict[str, Any]:
"""Executes tools/call and retries with inputResponses when elicited."""
base_params = {
"name": tool_name,
"arguments": copy.deepcopy(tool_args),
"_meta": build_base_meta(),
}
request_id = 1
response = send_rpc_fn(
{
"jsonrpc": "2.0",
"id": request_id,
"method": "tools/call",
"params": copy.deepcopy(base_params),
}
)
for _ in range(MAX_ELICITATION_ROUNDS):
result = response.get("result", {})
if result.get("resultType") != "input_required":
return response
input_requests = result.get("inputRequests", {})
if not isinstance(input_requests, dict) or not input_requests:
return response
result_meta = result.get("_meta", {})
input_responses: dict[str, Any] = {}
for req_key, req in input_requests.items():
if (
isinstance(req, dict)
and req.get("method") == "elicitation/create"
and req.get("params", {}).get("mode") == "form"
):
input_responses[req_key] = prompt_user_in_cli(
req, result_meta, tool_name
)
if not input_responses:
return response
request_id += 1
retry_params = copy.deepcopy(base_params)
request_state = result.get("requestState")
if request_state is not None:
retry_params["requestState"] = request_state
retry_params["inputResponses"] = input_responses
response = send_rpc_fn(
{
"jsonrpc": "2.0",
"id": request_id,
"method": "tools/call",
"params": retry_params,
}
)
return response
代理技能
請將下列內容做為技能或提示詞,讓程式設計代理為代理駕馭系統實作表單資訊收集功能:
提示詞
---
name: google-workspace-mcp-elicitation
metadata:
version: "1.0.0"
category: GoogleWorkspace
description: >-
Implements Model Context Protocol (MCP) form elicitation
(`elicitation/create`) for Human-in-the-Loop (HITL) approvals with Google
Workspace MCP servers (Gmail, Calendar, Drive, Docs, Sheets, Slides, Chat,
Contacts). Use when adding HITL confirmation prompts to an agent, handling
Stateless HTTP (`2026-07-28`) Multi Round-Trip Requests
(`resultType: "input_required"`), mapping elicitation schemas or `_meta`
hints to UI controls, or troubleshooting Workspace MCP `401`/`403`/`405`
and capability errors. Don't use for general OAuth 2.0 app setup unrelated
to MCP or for authoring custom MCP servers.
---
# Implementing Google Workspace MCP Form Elicitation (HITL)
Use this guide to support **Model Context Protocol (MCP) Form Elicitation**
for Human-in-the-Loop (HITL) confirmations when integrating **Google
Workspace MCP servers** into an AI agent.
Rather than duplicating the MCP specification, this guide references the
canonical specs and focuses on **Google Workspace server nuances**, **mapping
protocol message fields to UI**, **upcoming Google Workspace `_meta`
extensions**, and **practical integration boundaries**:
- [MCP Elicitation Specification][mcp-elicitation]
- [MCP Multi Round-Trip Requests (MRTR) Specification][mcp-mrtr]
- [MCP Lifecycle & Initialization][mcp-life]
- [MCP Icons Utility Specification][mcp-icon]
---
## 1. Prerequisites, Nuances & Architectural Boundaries
### Prerequisites (Assumed Configured)
This skill focuses on **handling elicitation requests and mapping them to
UI**. It assumes the host application already has Google Workspace MCP
connectivity and OAuth 2.0 configured. If not yet set up, follow the
[Google Workspace MCP Server Configuration Guide][ws-mcp-setup] to configure:
1. **Google Cloud Project & Service Enablement**: A Google Cloud project with
the target Google Workspace APIs and MCP endpoints enabled.
2. **OAuth 2.0 Bearer Authentication**: An OAuth 2.0 flow issuing user access
tokens with the required service scopes, passed as
`Authorization: Bearer {access_token}` on MCP HTTP `POST` requests. When
using standard 3-legged OAuth 2.0, the OAuth client configuration must
have the **"Used by an agent"** checkbox enabled.
Canonical MCP server URLs and default OAuth 2.0 scopes by service:
- **Gmail** (`https://gmailmcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/gmail.modify`
- `https://www.googleapis.com/auth/gmail.settings.basic`
- **Google Calendar** (`https://calendarmcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/calendar.events`
- `https://www.googleapis.com/auth/calendar.readonly`
- **Google Drive** (`https://drivemcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/drive`
- **Google Docs** (`https://docsmcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/documents`
- **Google Sheets** (`https://sheetsmcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/spreadsheets`
- **Google Slides** (`https://slidesmcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/presentations`
- **Google Chat** (`https://chatmcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/chat.messages`
- **Google Contacts (preview)** (`https://people.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/contacts`
- **Google Tasks** (`https://tasksmcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/tasks`
- **Universal Search** (`https://workspacemcp.googleapis.com/mcp/v1`):
- `https://www.googleapis.com/auth/gmail.readonly`
- `https://www.googleapis.com/auth/drive.readonly`
- `https://www.googleapis.com/auth/calendar.readonly`
- `https://www.googleapis.com/auth/chat.messages.readonly`
- `https://www.googleapis.com/auth/chat.spaces.readonly`
- `https://www.googleapis.com/auth/chat.memberships.readonly`
### Key Nuances for Google Workspace MCP Servers
- **Markdown Messages**: Google Workspace MCP servers format `params.message`
as **GitHub-Flavored Markdown** (headings, bold labels, bulleted lists of
parameters, links). Render `params.message` with a Markdown renderer rather
than plain text.
- **Selective Server-Side Gate (Writes & Sensitive/Shared Reads)**: Workspace
form elicitation selectively gates sensitive operations on the server, such
as **high-impact write operations** (for example, sending an email,
scheduling a meeting with external attendees, modifying a shared document)
as well as **reads of sensitive or externally shared data**, rather than
triggering on every tool call or validating general agent intent. Because
these sensitive actions already trigger a server-side `elicitation/create`
prompt, enabling unconditional client-side pre-tool approvals (such as
`needsApproval: true` on all tools) can double-prompt the user. Factor this
server-side gate into your risk assessment when deciding whether to
auto-approve tool calls, gate specific tools, or require pre-execution
approval across the board.
### Architectural Boundaries: Do Not Fight the Framework
Pausing an in-flight tool call, presenting a prompt to a user, and resuming
execution cuts across the host application's language, agent framework, MCP
SDK, and UI surface. **Do not fight the host framework or re-implement MCP
from scratch**. Reuse what the framework and SDK already provide to the
fullest extent possible:
- **Reuse Built-In Framework & MCP SDK Elicitation Support First**: Before
writing protocol or transport code, inspect the host application's agent
framework and MCP client library for existing MCP tool adapters, capability
negotiation, elicitation callbacks, and HITL interrupt/checkpoint
mechanisms. Wire elicitation through those built-in extension points rather
than replacing the SDK with a hand-rolled JSON-RPC client or custom
tool-calling loop.
- **Stateless HTTP (`2026-07-28`) MRTR & Adapting Stateful Implementations**:
Google Workspace MCP servers use Stateless HTTP (`2026-07-28`)
[Multi Round-Trip Requests (MRTR)][mcp-mrtr] (`POST`-only, where `GET`
returns `405`) to deliver `elicitation/create` prompts inside `tools/call`
responses via `result.resultType === "input_required"`
(`result.requestState`, `result.inputRequests`) and resume when
`tools/call` is replayed with `params.requestState` and
`params.inputResponses`. Supporting older stateful transports is not
required for Google Workspace, but existing elicitation support in an SDK
or host application might assume stateful server-initiated streams
(`2025-11-25`). Verify how the existing client handles elicitation: if it
already implements Stateless HTTP MRTR, use it directly. If it only listens
for stateful server-to-client stream requests (or strips MRTR fields during
typed deserialization), adapt the transport layer so `input_required`
responses route through the SDK's registered elicitation handler and replay
`tools/call` with `requestState` and `inputResponses`.
- **Elicitation Rendering Is a Presentation-Layer Concern**: Keep protocol
and transport handling decoupled from UI rendering. Pass the structured
elicitation request (`message`, `requestedSchema`, and `_meta`) to the host
application's presentation layer rather than embedding UI markup inside
agent or transport code, and render it using the application's native UI
paradigm rather than assuming HTML.
- **Suspension & Resumption Principles**: Regardless of how the host
application is deployed, suspending and resuming an elicitation must
satisfy three behaviors:
1. *Yield Cleanly Waiting for User Input*: Pause the in-flight tool
execution while waiting for the user's decision, using the host
runtime's native mechanism (such as awaiting an async callback/channel
in-memory or yielding via the framework's checkpoint/interrupt
primitive).
2. *Preserve Correlation & Continuation Context*: Retain the correlation ID
(`requestId`), opaque server `requestState`, and original tool call
context (`name`, `arguments`, and any prior `inputResponses`) across the
pause, in memory if the session stays alive or in durable storage if the
process or turn can terminate before the user responds.
3. *Accumulate Multi-Round-Trip Responses*: When replaying `tools/call`
with `requestState` and `inputResponses`, keep accumulating responses
across rounds if the server returns subsequent `input_required` stages
until the tool returns a final `CallToolResult`.
---
## 2. Phase 1: Core Form Elicitation Support (Priority)
Start by supporting standard [MCP Form Elicitation][mcp-elicitation]
end-to-end using your framework's and MCP SDK's built-in primitives so any
schema renders and resolves cleanly on the host UI surface.
### Step 1: Enable Elicitation & Register Handler
1. Register an `elicitation/create` handler through your agent framework or
MCP client SDK, and ensure the client advertises the `elicitation`
capability during initialization (and in per-request capability metadata
when using Stateless HTTP discovery):
```json
{
"capabilities": {
"elicitation": {}
}
}
```
2. Verify that your client handles Stateless HTTP (`2026-07-28`)
[MRTR][mcp-mrtr] (`result.resultType === "input_required"`). If the SDK
does not yet handle `input_required` natively, adapt the transport so each
entry in `result.inputRequests` (preserving `_meta` hints) is passed to
your registered elicitation handler and `tools/call` is replayed with
`params.requestState` and `params.inputResponses`.
### Step 2: Render Prompt on the Host UI Surface & Collect User Input
1. **Map Protocol Fields to the Host UI Surface**:
- Render `params.message` using a **Markdown renderer appropriate for the
host surface** (for example, GFM component in a web UI, formatted text
widgets in a chat card, or terminal Markdown in a CLI/TUI).
- Present input controls for `params.requestedSchema.properties` covering
all [MCP Elicitation supported schema types][mcp-schema-types]
(`string`, `number`, `integer`, `boolean`, and `enum` / `oneOf`).
2. **Collect the User's Decision**: Format the user's response per the
[MCP Elicitation response specification][mcp-elicitation]:
- **Submit Form / Select Option**:
`{ "action": "accept", "content": { ... } }` *(Note: When the schema
presents explicit `ALLOW_*` and `DENY_*` enum options, selecting a
`DENY_*` option is still submitted with `action: "accept"` and the
selected enum value in `content`.)*
- **Decline**: `{ "action": "decline" }`
- **Cancel / Dismiss**: `{ "action": "cancel" }`
### Step 3: Return the Elicitation Result
Return the `{ action, content }` result from your elicitation handler (or
pass it to your framework's resume mechanism) so the MCP client completes the
tool call and returns the final `CallToolResult` to the agent.
---
## 3. Phase 2: Optional UX Enhancements & Custom `_meta` Extensions
Once generic form elicitation works, you can optionally enhance the UX for
single-enum prompts and Google Workspace `_meta` extensions on your target UI
surface. Always treat `_meta` fields as optional (`undefined`-safe) so the UI
degrades cleanly to the Phase 1 form.
> [!NOTE]
> Google Workspace MCP servers define custom `_meta` presentation attributes
> (`isConfirmation`, `title`, `icons`, `learn_more_url`), but do not yet emit
> them in production responses. **Enhancement A** works today for `<= 4` enum
options using standard schema fields, whereas **Enhancements B and C** rely
> on upcoming `_meta` attributes. **Only implement Enhancements B and C if
> explicitly directed to by the user.**
### Enhancement A: Single-Enum Auto-Submitting Action Buttons / Quick Choices
Most HITL confirmations ask a single multiple-choice question (where
`requestedSchema.properties` has **1 property** defining `enum` or `oneOf`).
- **When to Apply**: Present a single-enum schema as direct auto-submitting
action buttons (or single-step quick choices in a TUI/CLI) **if and only
if**:
1. The single enum has **`<= 4` options**, **or**
2. The prompt is explicitly flagged as a HITL confirmation
(`params._meta?.isConfirmation === true`). Otherwise (for example, a
generic single-enum prompt with `> 4` options), fall back to the
standard Phase 1 selection form/menu.
- **Option Labels, Hierarchy & Submission**: Use `enumNames[i]` or
`oneOf[i].title` (falling back to a human-readable format of the enum
value) as the option label, assign visual emphasis in enum order
(`1st option -> primary`, `2nd option -> secondary`,
`3rd+ option -> tertiary`), and immediately submit
`{ "action": "accept", "content": { "{field_name}": "{selected_value}" } }`
when chosen, even when the user selects a `DENY_*` option.
- **Hide or De-Emphasize Redundant Decline/Cancel Controls**: Because HITL
schemas already include explicit `DENY_*` enum options (which are
functionally equivalent to declining/canceling on the server), presenting
separate generic `Decline` and `Cancel` buttons alongside `Allow` and
`Deny` enum choices is redundant. In this single-enum action view, omit a
separate `Decline` control and map `{ "action": "cancel" }` only to a
de-emphasized dismiss affordance appropriate to the surface (such as a
corner close `x` icon / `Escape` key in a GUI, or a `[c] Cancel` key in a
TUI).
### Enhancement B: Dynamic Button Stacking (Only If Explicitly Requested)
- **When to Apply**: On surfaces that support grouped/split buttons (or
grouped action menus), stack related options **if and only if**
`params._meta?.isConfirmation === true`. Never stack options based on enum
names alone when `isConfirmation` is not `true`.
- **Do Not Assume a Fixed Enum Set (`ALLOW_*` / `DENY_*` Convention)**: The
exact approval enum values are not a fixed list and might change over time
(for example, `ALLOW_ONCE`, `ALLOW_SESSION`, `ALWAYS_ALLOW`, `DENY_ONCE`),
following the `ALLOW_*` and `DENY_*` convention.
1. **Group by Action Prefix (`ALLOW` vs. `DENY`)**: Group options
dynamically by their action token/prefix, normalizing leading modifiers
like `ALWAYS_` or `ONCE_` so all `ALLOW` variants (such as `ALLOW_ONCE`,
`ALLOW_SESSION`, `ALWAYS_ALLOW`) stack into one group and `DENY`
variants (such as `DENY_ONCE`) group into another.
2. **Intra-Group Order**: Within each group, use the **first option in the
schema's enum order** as the primary action, and place remaining options
in that group (if any) into its secondary/split menu in enum order
(rendering a standalone button/action when a group has only one option).
3. **Inter-Group Hierarchy**: Order groups by their first appearance in the
enum and assign visual emphasis accordingly (`1st group -> primary`,
`2nd group -> secondary`, `3rd+ group -> tertiary`).
### Enhancement C: Custom `_meta` & `serverInfo` Hints (Only If Requested)
When present in the elicitation request's `params._meta` or the MCP server's
`Implementation` metadata (`serverInfo` from [MCP initialization][mcp-life]
or discovery), map these optional presentation fields to the confirmation
prompt (adapting to what the host UI surface supports):
- **Title (`params._meta?.title`)**: Use `params._meta.title` if non-empty.
Otherwise fall back to `"{server_name} confirmation"`.
- **Service Icon (`params._meta?.icons` / `serverInfo?.icons`)**: Check
`params._meta?.icons?.[0]?.src` first, then fall back to
`serverInfo?.icons?.[0]?.src` (per the [MCP Icons specification][mcp-icon]).
On graphical/card surfaces, render the icon only when a URL is present and
hide it on load error.
- **Learn More Link (`params._meta?.learn_more_url`)**: If present, display a
subtle "Learn more" link or URL reference in the prompt footer pointing to
`learn_more_url`.
---
## 4. Verification & Troubleshooting
### Verification: Triggering Conditions & Expected Behavior
Because Google Workspace MCP servers apply **context-aware server-side
policies**, **not every tool call or write operation triggers an
elicitation**:
- **Absence of an Elicitation Is Often Expected**: Operations confined to the
user's own private resources (for example, creating a Calendar event with
no attendees, or editing a private unshared Google Doc) might execute
immediately without an elicitation prompt. Do **not** treat a tool call
succeeding without an elicitation as a bug in your client implementation.
- **Scenarios That Reliably Trigger Elicitation**: To test your elicitation
flow end-to-end, use prompts that cross external or shared-resource
boundaries, such as:
- **Google Calendar**: Creating or updating an event **with an external
participant** (such as `dana@example.com`), or deleting an event with
attendees.
- **Gmail**: Sending an email to a recipient, deleting a draft, or creating
a mail filter.
- **Google Docs / Drive**: Updating **a shared document** or reading
sensitive/externally shared content.
- **End-to-End Validation Checklist**: Run a test prompt against one of the
scenarios above, verify each item below, and if any step fails, diagnose
the failure using the troubleshooting list below, apply the fix, and re-run
the check until all items pass:
- [ ] `params.message` renders as formatted Markdown on the target UI
surface.
- [ ] Approving (`accept`) replays `tools/call` with `requestState` and
`inputResponses` and returns the completed tool output.
- [ ] Declining (`decline`) or canceling (`cancel`) resolves cleanly
without hanging the agent turn.
### Troubleshooting Definitive Errors (`40x` & Protocol Failures)
- **Server refuses to execute `tools/call` stating elicitation is not
supported**:
- *Root cause*: Definitive signal that the client did not advertise
`elicitation` capability correctly.
- *Resolution*: Ensure `capabilities: { elicitation: {} }` is sent during
initialization (and in per-request client capability metadata if using
Stateless HTTP discovery), and verify that your 3-legged OAuth 2.0 client
has **"Used by an agent"** enabled.
- **`tools/call` returns `resultType: "input_required"` as raw tool output
(no prompt shown)**:
- *Root cause*: Definitive signal that the server triggered an elicitation,
but the MCP client did not handle the Stateless HTTP (`2026-07-28`)
[MRTR][mcp-mrtr] response (or stripped MRTR fields during typed
deserialization).
- *Resolution*: Verify your MCP client library supports Stateless HTTP MRTR
(`2026-07-28`) and preserves `resultType`, `requestState`,
`inputRequests`, and `_meta`, or handle `input_required` and replay
`tools/call` with `requestState` and `inputResponses`.
- **`401 Unauthorized`**:
- *Root cause*: Missing, expired, or invalid OAuth 2.0 access token.
- *Resolution*: Verify `Authorization: Bearer {access_token}` is attached
to every MCP HTTP `POST` request and refresh expired tokens.
- **`403 Forbidden` (Standard JSON error body)**:
- *Root cause*: OAuth token is missing required Google Workspace scopes for
the target server/tool, or the user lacks resource permission.
- *Resolution*: Compare granted token scopes against the default OAuth 2.0
scopes in Section 1 and re-consent.
- **`403 Forbidden` (Response body contains `{"result":{"tools":[...]}}`
schema dump)**:
- *Root cause*: Google Cloud project has not enabled the target Workspace
MCP service (or is not allowlisted). Because unauthenticated `tools/list`
discovery is permitted on the endpoint, the server returns the full
`tools/list` schema payload in the HTTP `403` error body while keeping
the `403` status code.
- *Resolution*: Enable the corresponding MCP service on the OAuth client's
Google Cloud project per the [Workspace MCP setup guide][ws-mcp-setup].
Summarize this error in logs to avoid dumping 50KB+ of tool schemas.
- **`405 Method Not Allowed`**:
- *Root cause*: MCP client or SDK sent an HTTP `GET` request (probing for
legacy SSE) instead of `POST`.
- *Resolution*: Google Workspace MCP endpoints are Stateless HTTP
`POST`-only. Configure the transport for `POST`-only or short-circuit
`GET` probes locally with `405`.
[mcp-elicitation]:
https://modelcontextprotocol.io/specification/latest/client/elicitation
[mcp-mrtr]:
https://modelcontextprotocol.io/specification/latest/basic/patterns/mrtr
[mcp-life]:
https://modelcontextprotocol.io/specification/latest/basic/lifecycle
[mcp-icon]:
https://modelcontextprotocol.io/specification/latest/basic/utilities/icons
[mcp-schema-types]:
https://modelcontextprotocol.io/specification/latest/client/elicitation#supported-schema-types
[ws-mcp-setup]:
https://developers.google.com/workspace/guides/configure-mcp-servers