context
TaskContext - Pure task state management.
This module provides TaskContext, which manages task state without any server/session dependencies. It can be used standalone for distributed workers or wrapped by ServerTaskContext for full server integration.
TaskContext
Pure task state management - no session dependencies.
This class handles: - Task state (status, result) - Cancellation tracking - Store interactions
For server-integrated features (elicit, create_message, notifications), use ServerTaskContext from mcp.server.experimental.
Example (distributed worker): async def worker_job(task_id: str): store = RedisTaskStore(redis_url) task = await store.get_task(task_id) ctx = TaskContext(task=task, store=store)
await ctx.update_status("Working...")
result = await do_work()
await ctx.complete(result)
Source code in src/mcp/shared/experimental/tasks/context.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
request_cancellation
request_cancellation() -> None
Request cancellation of this task.
This sets is_cancelled=True. Task work should check this periodically and exit gracefully if set.
Source code in src/mcp/shared/experimental/tasks/context.py
54 55 56 57 58 59 60 | |
update_status
async
update_status(message: str) -> None
Update the task's status message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The new status message |
required |
Source code in src/mcp/shared/experimental/tasks/context.py
62 63 64 65 66 67 68 69 70 71 | |
complete
async
complete(result: Result) -> None
Mark the task as completed with the given result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Result
|
The task result |
required |
Source code in src/mcp/shared/experimental/tasks/context.py
73 74 75 76 77 78 79 80 81 82 83 | |
fail
async
fail(error: str) -> None
Mark the task as failed with an error message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
str
|
The error message |
required |
Source code in src/mcp/shared/experimental/tasks/context.py
85 86 87 88 89 90 91 92 93 94 95 | |