|
| 1 | +""" |
| 2 | +TaskContext - Context for task work to interact with state and notifications. |
| 3 | +""" |
| 4 | + |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from mcp.shared.experimental.tasks.store import TaskStore |
| 8 | +from mcp.types import ( |
| 9 | + Result, |
| 10 | + ServerNotification, |
| 11 | + Task, |
| 12 | + TaskStatusNotification, |
| 13 | + TaskStatusNotificationParams, |
| 14 | +) |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from mcp.server.session import ServerSession |
| 18 | + |
| 19 | + |
| 20 | +class TaskContext: |
| 21 | + """ |
| 22 | + Context provided to task work for state management and notifications. |
| 23 | +
|
| 24 | + This wraps a TaskStore and optional session, providing a clean API |
| 25 | + for task work to update status, complete, fail, and send notifications. |
| 26 | +
|
| 27 | + Example: |
| 28 | + async def my_task_work(ctx: TaskContext) -> CallToolResult: |
| 29 | + await ctx.update_status("Starting processing...") |
| 30 | +
|
| 31 | + for i, item in enumerate(items): |
| 32 | + await ctx.update_status(f"Processing item {i+1}/{len(items)}") |
| 33 | + if ctx.is_cancelled: |
| 34 | + return CallToolResult(content=[TextContent(type="text", text="Cancelled")]) |
| 35 | + process(item) |
| 36 | +
|
| 37 | + return CallToolResult(content=[TextContent(type="text", text="Done!")]) |
| 38 | + """ |
| 39 | + |
| 40 | + def __init__( |
| 41 | + self, |
| 42 | + task: Task, |
| 43 | + store: TaskStore, |
| 44 | + session: "ServerSession | None" = None, |
| 45 | + ): |
| 46 | + self._task = task |
| 47 | + self._store = store |
| 48 | + self._session = session |
| 49 | + self._cancelled = False |
| 50 | + |
| 51 | + @property |
| 52 | + def task_id(self) -> str: |
| 53 | + """The task identifier.""" |
| 54 | + return self._task.taskId |
| 55 | + |
| 56 | + @property |
| 57 | + def task(self) -> Task: |
| 58 | + """The current task state.""" |
| 59 | + return self._task |
| 60 | + |
| 61 | + @property |
| 62 | + def is_cancelled(self) -> bool: |
| 63 | + """Whether cancellation has been requested.""" |
| 64 | + return self._cancelled |
| 65 | + |
| 66 | + def request_cancellation(self) -> None: |
| 67 | + """ |
| 68 | + Request cancellation of this task. |
| 69 | +
|
| 70 | + This sets is_cancelled=True. Task work should check this |
| 71 | + periodically and exit gracefully if set. |
| 72 | + """ |
| 73 | + self._cancelled = True |
| 74 | + |
| 75 | + async def update_status(self, message: str, *, notify: bool = True) -> None: |
| 76 | + """ |
| 77 | + Update the task's status message. |
| 78 | +
|
| 79 | + Args: |
| 80 | + message: The new status message |
| 81 | + notify: Whether to send a notification to the client |
| 82 | + """ |
| 83 | + self._task = await self._store.update_task( |
| 84 | + self.task_id, |
| 85 | + status_message=message, |
| 86 | + ) |
| 87 | + if notify: |
| 88 | + await self._send_notification() |
| 89 | + |
| 90 | + async def complete(self, result: Result, *, notify: bool = True) -> None: |
| 91 | + """ |
| 92 | + Mark the task as completed with the given result. |
| 93 | +
|
| 94 | + Args: |
| 95 | + result: The task result |
| 96 | + notify: Whether to send a notification to the client |
| 97 | + """ |
| 98 | + await self._store.store_result(self.task_id, result) |
| 99 | + self._task = await self._store.update_task( |
| 100 | + self.task_id, |
| 101 | + status="completed", |
| 102 | + ) |
| 103 | + if notify: |
| 104 | + await self._send_notification() |
| 105 | + |
| 106 | + async def fail(self, error: str, *, notify: bool = True) -> None: |
| 107 | + """ |
| 108 | + Mark the task as failed with an error message. |
| 109 | +
|
| 110 | + Args: |
| 111 | + error: The error message |
| 112 | + notify: Whether to send a notification to the client |
| 113 | + """ |
| 114 | + self._task = await self._store.update_task( |
| 115 | + self.task_id, |
| 116 | + status="failed", |
| 117 | + status_message=error, |
| 118 | + ) |
| 119 | + if notify: |
| 120 | + await self._send_notification() |
| 121 | + |
| 122 | + async def _send_notification(self) -> None: |
| 123 | + """Send a task status notification to the client.""" |
| 124 | + if self._session is None: |
| 125 | + return |
| 126 | + |
| 127 | + await self._session.send_notification( |
| 128 | + ServerNotification( |
| 129 | + TaskStatusNotification( |
| 130 | + params=TaskStatusNotificationParams( |
| 131 | + taskId=self._task.taskId, |
| 132 | + status=self._task.status, |
| 133 | + statusMessage=self._task.statusMessage, |
| 134 | + createdAt=self._task.createdAt, |
| 135 | + ttl=self._task.ttl, |
| 136 | + pollInterval=self._task.pollInterval, |
| 137 | + ) |
| 138 | + ) |
| 139 | + ) |
| 140 | + ) |
0 commit comments