( timeoutMs: number = MCP_ACTIVE_WORK_TIMEOUT_MS, )
| 61 | }; |
| 62 | |
| 63 | export const makeActiveWorkDeadline = ( |
| 64 | timeoutMs: number = MCP_ACTIVE_WORK_TIMEOUT_MS, |
| 65 | ): ActiveWorkDeadline => { |
| 66 | const controller = new AbortController(); |
| 67 | let remainingMs = timeoutMs; |
| 68 | let pendingElicitations = 0; |
| 69 | let startedAt: number | undefined; |
| 70 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 71 | |
| 72 | const stopTimer = (): void => { |
| 73 | if (timer === undefined || startedAt === undefined) return; |
| 74 | clearTimeout(timer); |
| 75 | timer = undefined; |
| 76 | remainingMs = Math.max(0, remainingMs - (Date.now() - startedAt)); |
| 77 | startedAt = undefined; |
| 78 | }; |
| 79 | |
| 80 | const abortForTimeout = (): void => { |
| 81 | timer = undefined; |
| 82 | startedAt = undefined; |
| 83 | // oxlint-disable-next-line executor/no-error-constructor -- boundary: AbortSignal consumers need a stable timeout reason |
| 84 | controller.abort(new Error("MCP tool invocation exceeded its active-work deadline")); |
| 85 | }; |
| 86 | |
| 87 | const startTimer = (): void => { |
| 88 | if (controller.signal.aborted || pendingElicitations > 0) return; |
| 89 | if (remainingMs <= 0) { |
| 90 | abortForTimeout(); |
| 91 | return; |
| 92 | } |
| 93 | startedAt = Date.now(); |
| 94 | timer = setTimeout(() => { |
| 95 | remainingMs = 0; |
| 96 | abortForTimeout(); |
| 97 | }, remainingMs); |
| 98 | }; |
| 99 | |
| 100 | startTimer(); |
| 101 | |
| 102 | return { |
| 103 | signal: controller.signal, |
| 104 | pause: () => { |
| 105 | pendingElicitations += 1; |
| 106 | if (pendingElicitations === 1) stopTimer(); |
| 107 | }, |
| 108 | resume: () => { |
| 109 | if (pendingElicitations === 0) return; |
| 110 | pendingElicitations -= 1; |
| 111 | if (pendingElicitations === 0) startTimer(); |
| 112 | }, |
| 113 | dispose: () => { |
| 114 | stopTimer(); |
| 115 | // oxlint-disable-next-line executor/no-error-constructor -- boundary: disposing the scoped signal must interrupt SDK work |
| 116 | controller.abort(new Error("MCP tool invocation was disposed")); |
| 117 | }, |
| 118 | }; |
| 119 | }; |
| 120 |
no test coverage detected