进度上报功能允许你的服务器在某个 tool 运行期间向 Client 发送进度更新。Client 可以利用这些更新,在耗时操作过程中显示加载动画、进度条以及“仍在处理中”的界面。
注意:仅当 Client 为此请求提供了进度令牌时,ctx.report_progress(...) 才会发送通知。如果 Client 没有请求进度,这个调用不会执行任何操作。
## 基本用法
from dedalus_mcp import get_context, tool
@tool(description="Process files")
async def process_files(files: list[str]) -> str:
ctx = get_context()
for i, file in enumerate(files, start=1):
await ctx.report_progress(i, total=len(files), message=f"Processing {file}")
process_file(file) # 你的代码;如果此操作阻塞,请将其卸载或改为异步
return f"Processed {len(files)} files"
await ctx.report_progress(
progress=50, # 当前进度值
total=100, # 可选总数(用于计算百分比)
message="Halfway done...", # 可选状态消息
)
| 参数 | 类型 | 描述 |
|---|
progress | int | float | 当前进度值 |
total | int | float | None | 可选的总进度值;用于显示百分比 UI |
message | str | None | 可选的、便于阅读的状态文本 |
from dedalus_mcp import get_context, tool
@tool(description="Download files")
async def download_files(urls: list[str]) -> dict:
ctx = get_context()
downloaded: list[str] = []
for i, url in enumerate(urls, start=1):
await ctx.report_progress(i - 1, total=len(urls), message=f"Downloading {url}")
await ctx.info("Downloading", data={"url": url})
path = await download(url) # 你的代码
downloaded.append(path)
await ctx.report_progress(i, total=len(urls))
return {"files": downloaded}
from dedalus_mcp import get_context, tool
@tool(description="Process large dataset")
async def process_dataset(dataset_id: str) -> dict:
ctx = get_context()
await ctx.report_progress(0, total=100, message="Loading dataset")
data = load_dataset(dataset_id) # 你的代码
await ctx.report_progress(30, total=100, message="Transforming data")
total_items = len(data)
if total_items:
for i, item in enumerate(data, start=1):
# 将条目进度映射到 30..70 范围
progress = 30 + int((i / total_items) * 40)
await ctx.report_progress(progress, total=100)
transform(item) # 你的代码
await ctx.report_progress(70, total=100, message="Saving results")
save_results(data) # 你的代码
await ctx.report_progress(100, total=100, message="Done")
return {"processed": len(data)}
如果一开始不知道总量,可以省略 total,并定期发送进度更新:
from dedalus_mcp import get_context, tool
@tool(description="Search until found")
async def search(query: str) -> str:
ctx = get_context()
pages_searched = 0
while True:
pages_searched += 1
await ctx.report_progress(pages_searched, message=f"Searched {pages_searched} pages")
result = search_page(query, pages_searched) # 你的代码
if result:
return result
if pages_searched > 100:
return "Not found"
- 优先使用异步任务:当你的工具在执行 I/O(
async def)时,进度更新最有价值。如果是 CPU 密集型或阻塞型工作,考虑将其卸载到其他线程/进程或后台任务,这样进度通知仍然可以持续发送。
- 谨慎使用
message:像 “Downloading…”、“Transforming…”、“Saving…” 这样的短消息最方便 Client 展示。
- 不要频繁发送更新:在每个很小的步骤都发送进度会显得很嘈杂。对于非常大的循环,你可能只需要每处理 N 个条目再上报一次。
Last modified on April 11, 2026