Skip to content

Ending a subscriptions/listen request always logs "request handler failed" at Warning (OperationCanceledException from sending the response) #2045

Backlog

Description

@BrannonKing

Summary

A subscriptions/listen request only ends when the client cancels it: on Streamable HTTP by closing the request, which the spec says a server must treat as cancellation, or with notifications/cancelled. Every time that happens, the server logs:

Warning ModelContextProtocol.Server.McpServer[LogRequestHandlerException]:
Server (...), Client (...) method 'subscriptions/listen' request handler failed in 357313.2957ms.
System.OperationCanceledException: The operation was canceled.
   at System.Threading.CancellationToken.ThrowOperationCanceledException()
   at System.Threading.CancellationToken.ThrowIfCancellationRequested()
   at ModelContextProtocol.McpSessionHandler.SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken)
   at ModelContextProtocol.McpSessionHandler.HandleRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken)
   at ModelContextProtocol.McpSessionHandler.HandleMessageCoreAsync(JsonRpcMessage message, CancellationToken cancellationToken)

The handler did nothing wrong: it saw its token cancelled and returned. A long-running server logs one of these for every listening client that disconnects, which looks like a fault and drowns out real request failures.

It happens with the SDK's built-in subscriptions/listen handler as well as with a custom SubscriptionsListenHandler, so a handler can't avoid it.

Version

ModelContextProtocol / ModelContextProtocol.AspNetCore 2.4.0 (the latest release). main has the same code as of 2026-11-25. .NET 10.

Cause

McpSessionHandler.HandleRequestAsync sends the response with the request's token after the handler returns:

JsonNode? result = await handler(request, cancellationToken).ConfigureAwait(false);

await SendMessageAsync(new JsonRpcResponse
{
    Id = request.Id,
    Result = result,
    Context = request.Context,
}, cancellationToken).ConfigureAwait(false);   // token is already cancelled -> throws

A listen handler only returns once that token is cancelled, so SendMessageAsync always throws OperationCanceledException from ThrowIfCancellationRequested. HandleMessageCoreAsync then logs every exception from HandleRequestAsync, cancellation included, at Warning (LogRequestHandlerException) before rethrowing. The outer catch in ProcessMessagesCoreAsync already treats the cancellation as a user cancellation and sends no error, so the only visible effect is the warning.

Throwing OperationCanceledException from the handler instead of returning doesn't help: HandleMessageCoreAsync logs that the same way.

Repro

The program below runs two scenarios against stock 2.4.0 and prints every Warning-or-higher log entry:

  • A: Streamable HTTP, SessionMode = Stateless, a custom SubscriptionsListenHandler that acknowledges, waits for its token, and returns EmptyResult. A 2026-07-28 McpClient opens the listen, waits for the acknowledgement, and cancels it.
  • B: StreamServerTransport over pipes with the built-in listen handler. The client opens the listen, waits for the acknowledgement, and cancels it (notifications/cancelled).

Output:

A: negotiated 2026-07-28, session <none>
=== A: Streamable HTTP, stateless, custom SubscriptionsListenHandler, client cancels the listen
  Warning ModelContextProtocol.Server.McpServer[LogRequestHandlerException]: Server (ListenCancelRepro 1.0.0.0), Client (ListenCancelRepro 1.0.0.0) method 'subscriptions/listen' request handler failed in 8.993ms. -- OperationCanceledException: The operation was canceled. (at System.Threading.CancellationToken.ThrowOperationCanceledException() <- at System.Threading.CancellationToken.ThrowIfCancellationRequested() <- at ModelContextProtocol.McpSessionHandler.SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken))
B: negotiated 2026-07-28
=== B: stream transport, built-in subscriptions/listen handler, client cancels the listen
  Warning ModelContextProtocol.Server.McpServer[LogRequestHandlerException]: Server (ListenCancelRepro 1.0.0.0), Client (ListenCancelRepro 1.0.0.0) method 'subscriptions/listen' request handler failed in 5.6821ms. -- OperationCanceledException: The operation was canceled. (at System.Threading.CancellationToken.ThrowOperationCanceledException() <- at System.Threading.CancellationToken.ThrowIfCancellationRequested() <- at ModelContextProtocol.McpSessionHandler.SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken))

Expected

Ending a listen request the way the protocol defines produces no Warning. The spec also says the receiver of a cancellation should not send a response for the cancelled request, and on HTTP the stream the response would use is already closed.

Suggested fix

In HandleRequestAsync, skip sending the response when cancellationToken.IsCancellationRequested after the handler returns. In HandleMessageCoreAsync, log an OperationCanceledException thrown while that token is cancelled at Debug, as LogEndpointMessageProcessingCanceled already does for the read loop, not through LogRequestHandlerException. This would also quiet the same warning for any other request a client cancels, such as a long tools/call.

Related

Repro program (ListenCancelRepro: net10.0, FrameworkReference Microsoft.AspNetCore.App, PackageReference ModelContextProtocol.AspNetCore 2.4.0)
using System.Collections.Concurrent;
using System.IO.Pipelines;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ModelContextProtocol;
using ModelContextProtocol.AspNetCore;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;

// Repro: ending a subscriptions/listen request logs "request handler failed" at Warning with an
// OperationCanceledException, though cancellation is the only way a listen request ends.

var warnings = new ConcurrentQueue<string>();
var capture = new CaptureProvider(warnings);

await HttpStatelessCustomHandlerAsync();
Report("A: Streamable HTTP, stateless, custom SubscriptionsListenHandler, client cancels the listen");

await StreamBuiltInHandlerAsync();
Report("B: stream transport, built-in subscriptions/listen handler, client cancels the listen");

void Report(string scenario)
{
	Console.WriteLine($"=== {scenario}");
	if (warnings.IsEmpty)
		Console.WriteLine("  (no warnings)");
	while (warnings.TryDequeue(out var line))
		Console.WriteLine($"  {line}");
}

JsonRpcRequest ListenRequest() => new()
{
	Method = RequestMethods.SubscriptionsListen,
	Params = JsonSerializer.SerializeToNode
	(
		new SubscriptionsListenRequestParams { Notifications = new SubscriptionsListenNotifications { ToolsListChanged = true } },
		McpJsonUtilities.DefaultOptions
	)
};

async Task CancelListenAsync(McpClient client, TaskCompletionSource acknowledged)
{
	using var listening = new CancellationTokenSource();
	var listen = client.SendRequestAsync(ListenRequest(), listening.Token);

	await acknowledged.Task.WaitAsync(TimeSpan.FromSeconds(5));
	await listening.CancelAsync();
	try { await listen; } catch (OperationCanceledException) { }

	// Give the server time to finish the request and log.
	await Task.Delay(1000);
}

McpClientHandlers AckHandlers(TaskCompletionSource acknowledged) => new()
{
	NotificationHandlers =
	[
		new(NotificationMethods.SubscriptionsAcknowledgedNotification, (_, _) =>
		{
			acknowledged.TrySetResult();
			return ValueTask.CompletedTask;
		})
	]
};

async Task HttpStatelessCustomHandlerAsync()
{
	var builder = WebApplication.CreateSlimBuilder();
	builder.Logging.ClearProviders();
	builder.Logging.AddProvider(capture);
	builder.WebHost.UseUrls("http://127.0.0.1:0");
	builder.Services.AddMcpServer(options => options.Capabilities = new ServerCapabilities { Tools = new ToolsCapability { ListChanged = true } })
		.WithHttpTransport(options => options.SessionMode = HttpServerSessionMode.Stateless)
		.WithSubscriptionsListenHandler(async (request, cancellationToken) =>
		{
			var ack = new SubscriptionsAcknowledgedNotificationParams { Notifications = new SubscriptionsListenNotifications { ToolsListChanged = true } };
			var parameters = JsonSerializer.SerializeToNode(ack, McpJsonUtilities.DefaultOptions)!.AsObject();
			parameters["_meta"] = new System.Text.Json.Nodes.JsonObject
			{
				[MetaKeys.SubscriptionId] = JsonSerializer.SerializeToNode(request.JsonRpcRequest.Id, McpJsonUtilities.DefaultOptions)
			};
			await request.Server.SendMessageAsync(new JsonRpcNotification { Method = NotificationMethods.SubscriptionsAcknowledgedNotification, Params = parameters }, cancellationToken);

			// A listen request has nothing to do but wait; it ends when the client cancels it.
			try
			{
				await Task.Delay(Timeout.Infinite, cancellationToken);
			}
			catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
			{
			}

			return new EmptyResult();
		});

	await using var app = builder.Build();
	app.MapMcp("/mcp");
	await app.StartAsync();

	var acknowledged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
	var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri(new Uri(app.Urls.Single()), "mcp") });
	await using (var client = await McpClient.CreateAsync(transport, new McpClientOptions { Handlers = AckHandlers(acknowledged) }))
	{
		Console.WriteLine($"A: negotiated {client.NegotiatedProtocolVersion}, session {client.SessionId ?? "<none>"}");
		await CancelListenAsync(client, acknowledged);
	}

	await app.StopAsync();
}

async Task StreamBuiltInHandlerAsync()
{
	using var loggerFactory = LoggerFactory.Create(logging => logging.AddProvider(capture));
	var clientToServer = new Pipe();
	var serverToClient = new Pipe();

	var serverTransport = new StreamServerTransport(clientToServer.Reader.AsStream(), serverToClient.Writer.AsStream(), "repro", loggerFactory);
	var server = McpServer.Create
	(
		serverTransport,
		new McpServerOptions { Capabilities = new ServerCapabilities { Tools = new ToolsCapability { ListChanged = true } } },
		loggerFactory
	);
	using var serverStop = new CancellationTokenSource();
	var serverRun = server.RunAsync(serverStop.Token);

	var acknowledged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
	var clientTransport = new StreamClientTransport(clientToServer.Writer.AsStream(), serverToClient.Reader.AsStream());
	await using (var client = await McpClient.CreateAsync(clientTransport, new McpClientOptions { Handlers = AckHandlers(acknowledged) }))
	{
		Console.WriteLine($"B: negotiated {client.NegotiatedProtocolVersion}");
		await CancelListenAsync(client, acknowledged);
	}

	await serverStop.CancelAsync();
	try { await serverRun; } catch (OperationCanceledException) { }
	await server.DisposeAsync();
}

sealed class CaptureProvider(ConcurrentQueue<string> sink) : ILoggerProvider
{
	public ILogger CreateLogger(string categoryName) => new Capture(categoryName, sink);
	public void Dispose() { }

	private sealed class Capture(string category, ConcurrentQueue<string> sink) : ILogger
	{
		public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
		public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
			if (!IsEnabled(logLevel))
				return;
			var origin = string.Join(" <- ", (exception?.StackTrace ?? "").Split('\n').Select(line => line.Trim()).Where(line => line.Length > 0).Take(3));
			sink.Enqueue($"{logLevel} {category}[{eventId.Name}]: {formatter(state, exception)}{(exception is null ? "" : $" -- {exception.GetType().Name}: {exception.Message} ({origin})")}");
		}
	}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions