|
1 | 1 | using Microsoft.Extensions.DependencyInjection; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using Microsoft.Extensions.Logging.Abstractions; |
2 | 4 | using Microsoft.Extensions.Options; |
3 | 5 | using ModelContextProtocol; |
4 | 6 | using ModelContextProtocol.Protocol; |
@@ -30,13 +32,18 @@ public static IMcpServerBuilder WithTasks(this IMcpServerBuilder builder, IMcpTa |
30 | 32 | if (store is null) throw new ArgumentNullException(nameof(store)); |
31 | 33 | #endif |
32 | 34 |
|
33 | | - builder.Services.AddSingleton<IPostConfigureOptions<McpServerOptions>>(new McpTasksPostConfigureOptions(store)); |
| 35 | + // Resolve ILoggerFactory from the provider (rather than requiring the caller to pass one) so the |
| 36 | + // background task body has somewhere to report failures. It is optional: if no logging is |
| 37 | + // registered, the options fall back to NullLoggerFactory. |
| 38 | + builder.Services.AddSingleton<IPostConfigureOptions<McpServerOptions>>( |
| 39 | + sp => new McpTasksPostConfigureOptions(store, sp.GetService<ILoggerFactory>())); |
34 | 40 | return builder; |
35 | 41 | } |
36 | 42 |
|
37 | | - private sealed class McpTasksPostConfigureOptions(IMcpTaskStore store) : IPostConfigureOptions<McpServerOptions> |
| 43 | + private sealed class McpTasksPostConfigureOptions(IMcpTaskStore store, ILoggerFactory? loggerFactory) : IPostConfigureOptions<McpServerOptions> |
38 | 44 | { |
39 | 45 | private readonly IMcpTaskStore _store = store; |
| 46 | + private readonly ILogger _logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger<McpTasksPostConfigureOptions>(); |
40 | 47 | private readonly ConcurrentDictionary<string, CancellationTokenSource> _cancellationSources = new(StringComparer.Ordinal); |
41 | 48 |
|
42 | 49 | public void PostConfigure(string? name, McpServerOptions options) |
@@ -74,71 +81,98 @@ public void PostConfigure(string? name, McpServerOptions options) |
74 | 81 |
|
75 | 82 | _ = Task.Run(async () => |
76 | 83 | { |
77 | | - using (McpTasksServerExtensions.CreateMcpTaskScope(request.Server, taskId, _store)) |
| 84 | + try |
78 | 85 | { |
79 | | - try |
| 86 | + using (McpTasksServerExtensions.CreateMcpTaskScope(request.Server, taskId, _store)) |
80 | 87 | { |
81 | | - var augmented = await next(request, taskCancellationToken).ConfigureAwait(false); |
| 88 | + try |
| 89 | + { |
| 90 | + var augmented = await next(request, taskCancellationToken).ConfigureAwait(false); |
82 | 91 |
|
83 | | - if (augmented.IsAlternate) |
| 92 | + if (augmented.IsAlternate) |
| 93 | + { |
| 94 | + var error = new JsonRpcErrorDetail |
| 95 | + { |
| 96 | + Code = (int)McpErrorCode.InternalError, |
| 97 | + Message = $"{nameof(IMcpTaskStore)} is configured and the {nameof(McpServerHandlers.CallToolWithAlternateHandler)} returned IsAlternate = true. Use only one mechanism.", |
| 98 | + }; |
| 99 | + var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>()); |
| 100 | + await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false); |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + var resultJson = JsonSerializer.SerializeToElement(augmented.Result!, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>()); |
| 105 | + await _store.SetCompletedAsync(taskId, resultJson).ConfigureAwait(false); |
| 106 | + } |
| 107 | + catch (OperationCanceledException) when (taskCancellationToken.IsCancellationRequested) |
| 108 | + { |
| 109 | + await _store.SetCancelledAsync(taskId, CancellationToken.None).ConfigureAwait(false); |
| 110 | + } |
| 111 | + catch (InputRequiredException) |
84 | 112 | { |
85 | 113 | var error = new JsonRpcErrorDetail |
86 | 114 | { |
87 | | - Code = (int)McpErrorCode.InternalError, |
88 | | - Message = $"{nameof(IMcpTaskStore)} is configured and the {nameof(McpServerHandlers.CallToolWithAlternateHandler)} returned IsAlternate = true. Use only one mechanism.", |
| 115 | + Code = (int)McpErrorCode.InvalidRequest, |
| 116 | + Message = "MRTR and tasks cannot be composed via [McpServerTool] yet.", |
89 | 117 | }; |
90 | 118 | var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>()); |
91 | 119 | await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false); |
92 | | - return; |
93 | 120 | } |
94 | | - |
95 | | - var resultJson = JsonSerializer.SerializeToElement(augmented.Result!, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>()); |
96 | | - await _store.SetCompletedAsync(taskId, resultJson).ConfigureAwait(false); |
97 | | - } |
98 | | - catch (OperationCanceledException) when (taskCancellationToken.IsCancellationRequested) |
99 | | - { |
100 | | - await _store.SetCancelledAsync(taskId, CancellationToken.None).ConfigureAwait(false); |
101 | | - } |
102 | | - catch (InputRequiredException) |
103 | | - { |
104 | | - var error = new JsonRpcErrorDetail |
| 121 | + catch (McpProtocolException mcpEx) |
105 | 122 | { |
106 | | - Code = (int)McpErrorCode.InvalidRequest, |
107 | | - Message = "MRTR and tasks cannot be composed via [McpServerTool] yet.", |
108 | | - }; |
109 | | - var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>()); |
110 | | - await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false); |
| 123 | + // SEP-2663 §186: protocol exceptions store as failed with JSON-RPC error shape. |
| 124 | + var error = new JsonRpcErrorDetail { Code = (int)mcpEx.ErrorCode, Message = mcpEx.Message }; |
| 125 | + var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>()); |
| 126 | + await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false); |
| 127 | + } |
| 128 | + catch (Exception ex) |
| 129 | + { |
| 130 | + // Non-protocol exceptions are wrapped as CallToolResult { IsError = true }, |
| 131 | + // matching Core's BuildInitialAlternateToolFilter behavior. |
| 132 | + var errorResult = new CallToolResult |
| 133 | + { |
| 134 | + IsError = true, |
| 135 | + Content = [new TextContentBlock |
| 136 | + { |
| 137 | + Text = ex is McpException |
| 138 | + ? $"An error occurred invoking '{request.Params?.Name}': {ex.Message}" |
| 139 | + : $"An error occurred invoking '{request.Params?.Name}'.", |
| 140 | + }], |
| 141 | + }; |
| 142 | + var resultJson = JsonSerializer.SerializeToElement(errorResult, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>()); |
| 143 | + await _store.SetCompletedAsync(taskId, resultJson).ConfigureAwait(false); |
| 144 | + } |
| 145 | + finally |
| 146 | + { |
| 147 | + if (_cancellationSources.TryRemove(taskId, out var registeredCts)) |
| 148 | + { |
| 149 | + registeredCts.Dispose(); |
| 150 | + } |
| 151 | + } |
111 | 152 | } |
112 | | - catch (McpProtocolException mcpEx) |
| 153 | + } |
| 154 | + catch (Exception outer) |
| 155 | + { |
| 156 | + // The inner handlers above record every expected outcome. Reaching here means a |
| 157 | + // store operation inside one of those handlers (or the task scope) threw, most |
| 158 | + // likely from a custom IMcpTaskStore. Record the failure best-effort and never let |
| 159 | + // it surface as an unobserved task exception. |
| 160 | + _logger.LogError(outer, "Background execution of task '{TaskId}' terminated unexpectedly while recording its result.", taskId); |
| 161 | + |
| 162 | + try |
113 | 163 | { |
114 | | - // SEP-2663 §186: protocol exceptions store as failed with JSON-RPC error shape. |
115 | | - var error = new JsonRpcErrorDetail { Code = (int)mcpEx.ErrorCode, Message = mcpEx.Message }; |
| 164 | + var error = new JsonRpcErrorDetail { Code = (int)McpErrorCode.InternalError, Message = outer.Message }; |
116 | 165 | var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>()); |
117 | 166 | await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false); |
118 | 167 | } |
119 | | - catch (Exception ex) |
| 168 | + catch (Exception storeEx) |
120 | 169 | { |
121 | | - // Non-protocol exceptions are wrapped as CallToolResult { IsError = true }, |
122 | | - // matching Core's BuildInitialAlternateToolFilter behavior. |
123 | | - var errorResult = new CallToolResult |
124 | | - { |
125 | | - IsError = true, |
126 | | - Content = [new TextContentBlock |
127 | | - { |
128 | | - Text = ex is McpException |
129 | | - ? $"An error occurred invoking '{request.Params?.Name}': {ex.Message}" |
130 | | - : $"An error occurred invoking '{request.Params?.Name}'.", |
131 | | - }], |
132 | | - }; |
133 | | - var resultJson = JsonSerializer.SerializeToElement(errorResult, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>()); |
134 | | - await _store.SetCompletedAsync(taskId, resultJson).ConfigureAwait(false); |
| 170 | + _logger.LogError(storeEx, "Failed to record the failure of background task '{TaskId}'.", taskId); |
135 | 171 | } |
136 | | - finally |
| 172 | + |
| 173 | + if (_cancellationSources.TryRemove(taskId, out var leftoverCts)) |
137 | 174 | { |
138 | | - if (_cancellationSources.TryRemove(taskId, out var registeredCts)) |
139 | | - { |
140 | | - registeredCts.Dispose(); |
141 | | - } |
| 175 | + leftoverCts.Dispose(); |
142 | 176 | } |
143 | 177 | } |
144 | 178 | }, CancellationToken.None); |
|
0 commit comments