Add progress and logs to a slow tool
Your research server has an add_all tool that sums a list of numbers, working through them one at a time. Right now it stays silent, so the client can't tell how far along it is. You'll log a message when it starts, then report progress after each number so the client can render a smooth, advancing progress bar.
FastMCP and Context are imported and the server mcp is created. run_tool(numbers) runs your tool through a real MCP client–server session and collects what the connected client receives into the lists LOGS and PROGRESS.
This exercise is part of the course
Model Context Protocol: Advanced Topics
Exercise instructions
- Use
ctx.info()to log the message"Adding the numbers..."when the tool starts. - After adding each number, call
ctx.report_progress()inside the loop. - Report the count done so far (
i + 1) out of the total (len(numbers)).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
@mcp.tool()
async def add_all(numbers: list[int], ctx: Context) -> int:
# Log that the tool started
await ctx.____("Adding the numbers...")
total = 0
for i, number in enumerate(numbers):
total += number
# Report progress after each number
await ctx.____(____, ____)
return total
# Run the tool through a real MCP client-server session
result = run_tool([5, 3, 2])
print(result, LOGS, PROGRESS)