載入中

日誌與進度通知實作起來很簡單,但在使用 MCP 伺服器時,卻能大幅改善使用者體驗。它們能幫助使用者了解長時間執行的操作期間發生了什麼事,而不必擔心是否出了問題。

當 Claude 呼叫一個需要花時間完成的工具時——例如研究某個主題或處理資料——使用者通常在操作完成之前什麼都看不到。這可能會令人感到沮喪,因為他們不知道工具是正在運作還是已經卡住了。

啟用日誌與進度通知後,使用者可以獲得即時回饋,準確顯示幕後正在發生的事情。他們可以在操作執行時看到進度條、狀態訊息以及詳細的日誌。

運作方式

在 Python MCP SDK 中,日誌與進度通知是透過自動提供給您的工具函式的 Context 引數來運作的。這個 context 物件提供您一些方法,讓您可以在執行期間與用戶端進行溝通。

python
@mcp.tool(
    name="research",
    description="Research a given topic"
)
async def research(
    topic: str = Field(description="Topic to research"),
    *,
    context: Context
):
    await context.info("About to do research...")
    await context.report_progress(20, 100)
    sources = await do_research(topic)

    await context.info("Writing report...")
    await context.report_progress(70, 100)
    results = await generate_report(sources)

    return results

您會用到的關鍵方法有:

  • context.info() - 向用戶端傳送日誌訊息
  • context.report_progress() - 以目前值與總值更新進度

用戶端實作

在用戶端,您需要設定回呼函式來處理這些通知。伺服器會發出這些訊息,但要如何將它們呈現給使用者,則取決於您的用戶端應用程式。

python
async def logging_callback(params: LoggingMessageNotificationParams):
    print(params.data)

async def print_progress_callback(
    progress: float, total: float | None, message: str | None
):
    if total is not None:
        percentage = (progress / total) * 100
        print(f"Progress: {progress}/{total} ({percentage:.1f}%)")
    else:
        print(f"Progress: {progress}")

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(
            read,
            write,
            logging_callback=logging_callback
        ) as session:
            await session.initialize()

            await session.call_tool(
                name="add",
                arguments={"a": 1, "b": 3},
                progress_callback=print_progress_callback,
            )

您需要在建立用戶端工作階段時提供日誌回呼函式,並在進行個別工具呼叫時提供進度回呼函式。這讓您能夠靈活地適當處理不同類型的通知。

呈現方式選項

您如何呈現這些通知,取決於您的應用程式類型:

  • CLI 應用程式 - 只需將訊息與進度印到終端機即可
  • 網頁應用程式 - 使用 WebSocket、伺服器傳送事件(server-sent events)或輪詢方式,將更新推送到瀏覽器
  • 桌面應用程式 - 在您的使用者介面中更新進度條與狀態顯示

請記住,實作這些通知完全是選擇性的。您可以選擇完全忽略它們、只顯示特定類型,或以任何對您的應用程式有意義的方式呈現它們。它們純粹是使用者體驗的強化功能,用來幫助使用者了解長時間執行的操作期間發生了什麼事。