From 3b6f2fcdc30a653fe340f287789837b56fd12b0d Mon Sep 17 00:00:00 2001 From: Lior Shmueli <48066416+ShmueLior@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:18:46 +0200 Subject: [PATCH 1/2] Make CLI connection errors short and actionable --- CHANGELOG.md | 2 + src/McpProbe.Cli/CliApp.cs | 3 +- src/McpProbe.Cli/ConnectError.cs | 86 ++++++++++++++ src/McpProbe.Cli/ServerConnector.cs | 34 ++++-- src/McpProbe.Cli/ServerOptions.cs | 16 ++- tests/McpProbe.Tests/CliTests.cs | 138 +++++++++++++++++++++- tests/McpProbe.Tests/ConnectErrorTests.cs | 79 +++++++++++++ 7 files changed, 341 insertions(+), 17 deletions(-) create mode 100644 src/McpProbe.Cli/ConnectError.cs create mode 100644 tests/McpProbe.Tests/ConnectErrorTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 69ec247..8fd8d98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,8 @@ All notable changes to this project are documented here. The format is based on ### Fixed - MCPP005 and MCPP006 no longer report "most names are X" when two styles tie. With no majority they report nothing. +- `--timeout N` now stops after about N seconds for a stdio server that does not exit (the SDK waited 5 more seconds before killing it; the grace period is now 500 ms), and the error no longer ends with the runtime's "A task was canceled.". A stdio server that needs more than 500 ms to exit after its stdin closes is now killed instead of waited for. +- HTTP connection errors are short and say what to try. A pinned `--transport sse` or `streamable-http` that gets a 400, 404 or 405 says the URL did not answer as that transport and points at the other one. A 401 shows the server's `WWW-Authenticate` challenge and says to pass `--header 'Authorization: Bearer '`, or that the credentials in `--header` were rejected. Other response bodies are shown as one line of at most 200 characters with HTML tags removed, instead of a whole page. Exit codes are unchanged. ## [0.3.0-preview] - 2026-11-28 diff --git a/src/McpProbe.Cli/CliApp.cs b/src/McpProbe.Cli/CliApp.cs index 8f026f3..2c7f2cc 100644 --- a/src/McpProbe.Cli/CliApp.cs +++ b/src/McpProbe.Cli/CliApp.cs @@ -257,7 +257,8 @@ private static string DescribeWithCauses(Exception ex) var messages = new List { ex.Message }; for (var inner = ex.InnerException; inner is not null && messages.Count < 4; inner = inner.InnerException) { - if (!messages.Any(m => m.Contains(inner.Message, StringComparison.Ordinal))) + // The runtime's "A task was canceled." (localized) says nothing the message above doesn't. + if (inner is not OperationCanceledException && !messages.Any(m => m.Contains(inner.Message, StringComparison.Ordinal))) { messages.Add(inner.Message); } diff --git a/src/McpProbe.Cli/ConnectError.cs b/src/McpProbe.Cli/ConnectError.cs new file mode 100644 index 0000000..b7789a2 --- /dev/null +++ b/src/McpProbe.Cli/ConnectError.cs @@ -0,0 +1,86 @@ +using System.Net; +using System.Text.RegularExpressions; +using McpProbe.Internal; +using ModelContextProtocol.Client; + +namespace McpProbe.Cli; + +/// +/// Turns the SDK's HTTP failure (status plus up to 1 KB of the response body, which may be a whole HTML page or advice +/// for the server author) into one short line that tells the CLI user what to try next. +/// +internal static partial class ConnectError +{ + private const string BodyMarker = "Response body: "; + private const int PreviewLength = 200; + + public static string Describe(HttpRequestException ex, Uri endpoint, HttpTransportMode mode, bool sentAuthorization, string? wwwAuthenticate) + { + var status = ex.StatusCode ?? throw new ArgumentException("The exception has no status code.", nameof(ex)); + var code = (int)status; + var url = endpoint.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.SafeUnescaped); + + if (status == HttpStatusCode.Unauthorized) + { + var challenge = string.IsNullOrWhiteSpace(wwwAuthenticate) ? "" : $" (WWW-Authenticate: {Printable.Text(wwwAuthenticate)})"; + return sentAuthorization + ? $"401 Unauthorized from {url}. The credentials in --header were rejected{challenge}." + : $"401 Unauthorized from {url}. The server wants authentication{challenge}. Pass --header 'Authorization: Bearer '."; + } + + if (status is HttpStatusCode.BadRequest or HttpStatusCode.NotFound or HttpStatusCode.MethodNotAllowed) + { + if (mode == HttpTransportMode.Sse) + { + return $"The server did not answer as a legacy SSE endpoint at this URL (HTTP {code}). Legacy SSE usually lives at /sse; use --transport auto or streamable-http for Streamable HTTP."; + } + + if (mode == HttpTransportMode.StreamableHttp) + { + return $"The server did not answer as Streamable HTTP at this URL (HTTP {code}). Streamable HTTP is usually at /mcp; use --transport auto or sse for a legacy SSE endpoint."; + } + } + + var preview = Preview(ex.Message); + return preview.Length == 0 ? $"HTTP {code} from {url}." : $"HTTP {code} from {url}: \"{preview}\""; + } + + /// The response body from an SDK exception message as one line: tags stripped when it is HTML, whitespace collapsed, at most 200 characters. + internal static string Preview(string exceptionMessage) + { + var start = exceptionMessage.IndexOf(BodyMarker, StringComparison.Ordinal); + if (start < 0) + { + return ""; + } + + var body = exceptionMessage[(start + BodyMarker.Length)..]; + if (body.TrimStart().StartsWith('<')) + { + body = WebUtility.HtmlDecode(Tags().Replace(body, " ")); + } + + return Printable.Text(Whitespace().Replace(body, " ").Trim(), PreviewLength); + } + + [GeneratedRegex("<[^>]*>")] + private static partial Regex Tags(); + + [GeneratedRegex(@"\s+")] + private static partial Regex Whitespace(); +} + +/// Remembers the last WWW-Authenticate value the server sent. The body is left alone, the SDK reads it. +internal sealed class ChallengeCapture() : DelegatingHandler(new SocketsHttpHandler()) +{ + private volatile string? _challenge; + + public string? Challenge => _challenge; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + _challenge = response.Headers.WwwAuthenticate is { Count: > 0 } values ? string.Join(", ", values) : null; + return response; + } +} diff --git a/src/McpProbe.Cli/ServerConnector.cs b/src/McpProbe.Cli/ServerConnector.cs index cc22a10..5614403 100644 --- a/src/McpProbe.Cli/ServerConnector.cs +++ b/src/McpProbe.Cli/ServerConnector.cs @@ -11,11 +11,18 @@ internal sealed record ServerTarget( IReadOnlyDictionary Headers, IReadOnlyDictionary Environment, string? WorkingDirectory, - HttpTransportMode TransportMode); + HttpTransportMode TransportMode, + TimeSpan Timeout); internal static class ServerConnector { - public static async Task ConnectAsync(ServerTarget target, StderrBuffer serverStderr, CancellationToken cancellationToken) + /// + /// How long a stdio server gets to exit by itself after its stdin is closed, before its process tree is killed. + /// The SDK default is 5 seconds, which would add that much to a --timeout. + /// + private static readonly TimeSpan s_shutdownTimeout = TimeSpan.FromMilliseconds(500); + + public static async Task ConnectAsync(ServerTarget target, StderrBuffer serverStderr, ChallengeCapture challenge, CancellationToken cancellationToken) { IClientTransport transport; if (target.StdioCommand is not null) @@ -34,17 +41,28 @@ public static async Task ConnectAsync(ServerTarget target, StderrBuff WorkingDirectory = target.WorkingDirectory, EnvironmentVariables = target.Environment.Count == 0 ? null : new Dictionary(target.Environment), StandardErrorLines = serverStderr.Add, + ShutdownTimeout = s_shutdownTimeout, }); } else if (target.HttpEndpoint is not null) { - transport = new HttpClientTransport(new HttpClientTransportOptions + // --timeout is the only time limit, so the HttpClient has none of its own. + var http = new HttpClient(challenge, disposeHandler: true) { - Name = "mcpprobe-target", - Endpoint = target.HttpEndpoint, - AdditionalHeaders = target.Headers.Count == 0 ? null : new Dictionary(target.Headers), - TransportMode = target.TransportMode, - }); + Timeout = Timeout.InfiniteTimeSpan, + }; + transport = new HttpClientTransport( + new HttpClientTransportOptions + { + Name = "mcpprobe-target", + Endpoint = target.HttpEndpoint, + AdditionalHeaders = target.Headers.Count == 0 ? null : new Dictionary(target.Headers), + TransportMode = target.TransportMode, + ConnectionTimeout = target.Timeout, + }, + http, + loggerFactory: null, + ownsHttpClient: true); } else { diff --git a/src/McpProbe.Cli/ServerOptions.cs b/src/McpProbe.Cli/ServerOptions.cs index 4ed72d2..5327741 100644 --- a/src/McpProbe.Cli/ServerOptions.cs +++ b/src/McpProbe.Cli/ServerOptions.cs @@ -130,15 +130,17 @@ public async Task CaptureAsync(ParseResult parse, TextWriter stderr ParsePairs(parse.GetValue(_headers), ':', "--header", "Name: value"), ParsePairs(parse.GetValue(_env), '=', "--env", "NAME=value").ToDictionary(p => p.Key, p => (string?)p.Value, StringComparer.Ordinal), parse.GetValue(_cwd), - ParseTransportMode(parse.GetValue(_transport)) ?? HttpTransportMode.AutoDetect); + ParseTransportMode(parse.GetValue(_transport)) ?? HttpTransportMode.AutoDetect, + TimeSpan.FromSeconds(timeoutSeconds)); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds)); var serverStderr = new StderrBuffer(); + var challenge = new ChallengeCapture(); try { - var client = await ServerConnector.ConnectAsync(target, serverStderr, timeout.Token).ConfigureAwait(false); + var client = await ServerConnector.ConnectAsync(target, serverStderr, challenge, timeout.Token).ConfigureAwait(false); await using (client.ConfigureAwait(false)) { return await ToolSurface.CaptureAsync(client, timeout.Token).ConfigureAwait(false); @@ -160,7 +162,15 @@ public async Task CaptureAsync(ParseResult parse, TextWriter stderr if (ex is OperationCanceledException && timeout.IsCancellationRequested && !cancellationToken.IsCancellationRequested) { - throw new TimeoutException($"The server didn't respond within {timeoutSeconds} seconds.", ex); + // No inner exception: its message is the runtime's localized "A task was canceled.". + throw new TimeoutException($"The server didn't respond within {timeoutSeconds} seconds."); + } + + if (ex is HttpRequestException { StatusCode: not null } http && target.HttpEndpoint is { } endpoint) + { + // The SDK's message carries the response body. Say what to try instead, with no inner exception to bring the body back. + var sentAuthorization = target.Headers.Keys.Any(k => string.Equals(k, "Authorization", StringComparison.OrdinalIgnoreCase)); + throw new HttpRequestException(ConnectError.Describe(http, endpoint, target.TransportMode, sentAuthorization, challenge.Challenge), inner: null, http.StatusCode); } throw; diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index 971c2e7..880031d 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -449,14 +449,19 @@ public async Task StderrBuffer_StopsWaitingWhenNothingArrives_OrWhenLinesKeepCom Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10), watch.Elapsed.ToString()); } - [Fact] - public async Task Stdio_TimeoutIsReported() + [Theory] + [InlineData("sleep 30")] + [InlineData("sh -c \"trap '' TERM; sleep 30\"")] + public async Task Stdio_TimeoutIsReported(string command) { SkipWithoutPosixShell(); - var (exit, _, error) = await RunAsync("lint", "--stdio", "sleep 30", "--timeout", "1"); + var watch = System.Diagnostics.Stopwatch.StartNew(); + var (exit, _, error) = await RunAsync("lint", "--stdio", command, "--timeout", "2"); Assert.Equal(ExitCodes.Error, exit); - Assert.Contains("didn't respond within 1 seconds", error, StringComparison.Ordinal); + Assert.Equal("error: The server didn't respond within 2 seconds.", error.TrimEnd()); + // The SDK waits 5 seconds for a graceful exit by default; the limit is only loose enough for a busy CI machine. + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(4), watch.Elapsed.ToString()); } [Fact] @@ -534,10 +539,108 @@ public async Task Http_TransportSseAgainstStreamableHttpEndpoint_IsAnError() "lint", "--http", baseUrl + "/mcp", "--transport", "sse", "--header", "X-Api-Key: secret", "--timeout", "10"); Assert.Equal(ExitCodes.Error, exit); - Assert.StartsWith("error:", error, StringComparison.Ordinal); + Assert.StartsWith("error: The server did not answer as a legacy SSE endpoint at this URL (HTTP ", error, StringComparison.Ordinal); + Assert.DoesNotContain("SessionMode", error, StringComparison.Ordinal); Assert.True(watch.Elapsed < TimeSpan.FromSeconds(15), watch.Elapsed.ToString()); } + [Fact] + public async Task Http_TransportStreamableHttpAgainstLegacySseEndpoint_IsAnError() + { + var (app, baseUrl) = await StartHttpServerAsync(enableLegacySse: true); + await using var server = app; + + var (exit, _, error) = await RunAsync( + "lint", "--http", baseUrl + "/mcp/sse", "--transport", "streamable-http", "--header", "X-Api-Key: secret", "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.StartsWith("error: The server did not answer as Streamable HTTP at this URL (HTTP ", error, StringComparison.Ordinal); + } + + [Theory] + [InlineData("sse", "legacy SSE endpoint")] + [InlineData("streamable-http", "as Streamable HTTP")] + public async Task Http_PinnedTransportAgainstHtmlPage_GetsTheTransportHint(string transport, string expected) + { + await using var stub = await StartStubAsync(context => Respond(context, 405, "

405

Not here

")); + + var (exit, _, error) = await RunAsync("lint", "--http", stub.Url, "--transport", transport, "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains(expected, error, StringComparison.Ordinal); + Assert.Contains("(HTTP 405)", error, StringComparison.Ordinal); + Assert.DoesNotContain("<", error, StringComparison.Ordinal); + } + + [Fact] + public async Task Http_AutoTransportAgainstHtmlPage_ShowsAShortPreviewWithoutTags() + { + var body = "Nope

Not & here

\n

" + new string('x', 500) + "

"; + await using var stub = await StartStubAsync(context => Respond(context, 405, body)); + + var (exit, _, error) = await RunAsync("lint", "--http", stub.Url, "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.StartsWith($"error: HTTP 405 from {stub.Url}: \"Nope Not & here xxx", error, StringComparison.Ordinal); + Assert.EndsWith("...\".", error.TrimEnd(), StringComparison.Ordinal); + Assert.Single(error.TrimEnd().Split('\n')); + Assert.DoesNotContain("<", error, StringComparison.Ordinal); + Assert.True(error.Length < 400, $"{error.Length}"); + } + + [Fact] + public async Task Http_ServerError_HasNoTransportHint() + { + await using var stub = await StartStubAsync(context => Respond(context, 500, "boom")); + + var (exit, _, error) = await RunAsync("lint", "--http", stub.Url, "--transport", "sse", "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Equal($"error: HTTP 500 from {stub.Url}: \"boom\".", error.TrimEnd()); + } + + [Fact] + public async Task Http_HostileBody_IsEscaped() + { + await using var stub = await StartStubAsync(context => Respond(context, 502, "bad \u001b[31mred\u001b[0m \u202E gateway")); + + var (exit, _, error) = await RunAsync("lint", "--http", stub.Url, "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.DoesNotContain('\u001b', error); + Assert.DoesNotContain('\u202E', error); + Assert.Contains("\\u001B[31mred", error, StringComparison.Ordinal); + } + + [Fact] + public async Task Http_Unauthorized_SaysWhatTheServerWantsAndWhatToPass() + { + await using var stub = await StartStubAsync(context => + { + context.Response.Headers.WWWAuthenticate = "Bearer resource_metadata=\"http://example.test/.well-known/x\""; + return Respond(context, 401, ""); + }); + + var (exit, _, error) = await RunAsync("lint", "--http", stub.Url + "?token=secret", "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Equal( + $"error: 401 Unauthorized from {stub.Url}. The server wants authentication (WWW-Authenticate: Bearer resource_metadata=\"http://example.test/.well-known/x\"). Pass --header 'Authorization: Bearer '.", + error.TrimEnd()); + } + + [Fact] + public async Task Http_UnauthorizedWithAuthorizationHeader_SaysTheCredentialsWereRejected() + { + await using var stub = await StartStubAsync(context => Respond(context, 401, "")); + + var (exit, _, error) = await RunAsync("lint", "--http", stub.Url, "--header", "authorization: Bearer nope", "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Equal($"error: 401 Unauthorized from {stub.Url}. The credentials in --header were rejected.", error.TrimEnd()); + Assert.DoesNotContain("nope", error, StringComparison.Ordinal); + } + [Fact] public async Task Http_TransportSse_WorksAgainstLegacySseEndpoint() { @@ -576,6 +679,31 @@ public async Task Help_ExitsZero() Assert.Contains("lint", output, StringComparison.Ordinal); } + private static Task Respond(HttpContext context, int status, string body) + { + context.Response.StatusCode = status; + return context.Response.WriteAsync(body); + } + + /// A plain HTTP server that answers every request with , no MCP. + private static async Task StartStubAsync(Func handler) + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + var app = builder.Build(); + app.MapFallback(new RequestDelegate(handler)); + await app.StartAsync(TestContext.Current.CancellationToken); + return new Stub(app, app.Services.GetRequiredService().Features.Get()!.Addresses.Single() + "/mcp"); + } + + private sealed class Stub(WebApplication app, string url) : IAsyncDisposable + { + public string Url { get; } = url; + + public ValueTask DisposeAsync() => app.DisposeAsync(); + } + private static async Task<(WebApplication App, string BaseUrl)> StartHttpServerAsync(bool enableLegacySse = false) { var builder = WebApplication.CreateSlimBuilder(); diff --git a/tests/McpProbe.Tests/ConnectErrorTests.cs b/tests/McpProbe.Tests/ConnectErrorTests.cs new file mode 100644 index 0000000..1036bbf --- /dev/null +++ b/tests/McpProbe.Tests/ConnectErrorTests.cs @@ -0,0 +1,79 @@ +using System.Net; +using McpProbe.Cli; +using ModelContextProtocol.Client; + +namespace McpProbe.Tests; + +public sealed class ConnectErrorTests +{ + private static readonly Uri s_endpoint = new("https://user:pw@example.test/mcp?token=secret#frag"); + + private static HttpRequestException Failure(HttpStatusCode status, string? body = null) => + new($"Response status code does not indicate success: {(int)status} ({status})." + (body is null ? "" : " Response body: " + body), null, status); + + [Theory] + [InlineData("", "")] + [InlineData("{\"error\": {\"code\": -32000}}", "{\"error\": {\"code\": -32000}}")] + [InlineData(" line one\n\n line two\t", "line one line two")] + [InlineData("\n

405: No

Use <POST> & wait

\n", "405: No Use & wait")] + [InlineData("not html but 1 < 2 and 3 > 2", "not html but 1 < 2 and 3 > 2")] + public void Preview_IsOneLineWithoutMarkup(string body, string expected) => + Assert.Equal(expected, ConnectError.Preview("Response status code does not indicate success: 405 (Method Not Allowed). Response body: " + body)); + + [Fact] + public void Preview_WithoutABody_IsEmpty() => + Assert.Equal("", ConnectError.Preview("Response status code does not indicate success: 405 (Method Not Allowed).")); + + [Fact] + public void Preview_IsCappedAndNeverSplitsAnEscapeOrSurrogatePair() + { + var preview = ConnectError.Preview("Response body: " + new string('\u0007', 150) + "\U0001F600\U0001F600"); + + Assert.True(preview.Length <= 200, $"{preview.Length}"); + Assert.EndsWith("...", preview, StringComparison.Ordinal); + Assert.DoesNotContain('\u0007', preview); + Assert.Matches(@"^(\\u0007)+\.\.\.$", preview); + } + + [Fact] + public void Describe_ShowsTheEndpointWithoutCredentialsOrQuery() => + Assert.Equal( + "HTTP 500 from https://example.test/mcp: \"boom\"", + ConnectError.Describe(Failure(HttpStatusCode.InternalServerError, "boom"), s_endpoint, HttpTransportMode.AutoDetect, false, null)); + + [Theory] + [InlineData(HttpStatusCode.BadRequest, 400)] + [InlineData(HttpStatusCode.NotFound, 404)] + [InlineData(HttpStatusCode.MethodNotAllowed, 405)] + public void Describe_PinnedTransportMismatch_NamesTheTransportAndCode(HttpStatusCode status, int code) + { + var sse = ConnectError.Describe(Failure(status, "advice for the server author"), s_endpoint, HttpTransportMode.Sse, false, null); + var streamable = ConnectError.Describe(Failure(status, "advice for the server author"), s_endpoint, HttpTransportMode.StreamableHttp, false, null); + + Assert.StartsWith($"The server did not answer as a legacy SSE endpoint at this URL (HTTP {code}).", sse, StringComparison.Ordinal); + Assert.StartsWith($"The server did not answer as Streamable HTTP at this URL (HTTP {code}).", streamable, StringComparison.Ordinal); + Assert.DoesNotContain("advice", sse + streamable, StringComparison.Ordinal); + } + + [Theory] + [InlineData(HttpStatusCode.Forbidden, HttpTransportMode.Sse)] + [InlineData(HttpStatusCode.InternalServerError, HttpTransportMode.StreamableHttp)] + [InlineData(HttpStatusCode.MethodNotAllowed, HttpTransportMode.AutoDetect)] + public void Describe_OtherCases_HaveNoTransportHint(HttpStatusCode status, HttpTransportMode mode) => + Assert.StartsWith($"HTTP {(int)status} from https://example.test/mcp", ConnectError.Describe(Failure(status), s_endpoint, mode, false, null), StringComparison.Ordinal); + + [Fact] + public void Describe_Unauthorized_EscapesTheServersChallenge() + { + var message = ConnectError.Describe(Failure(HttpStatusCode.Unauthorized), s_endpoint, HttpTransportMode.AutoDetect, false, "Bearer realm=\"x\u001b[31m\\\""); + + Assert.Contains("(WWW-Authenticate: Bearer realm=\"x\\u001B[31m\\\\\")", message, StringComparison.Ordinal); + Assert.DoesNotContain('\u001b', message); + } + + [Fact] + public void Describe_Unauthorized_WithoutAChallengeLeavesThatPartOut() => + Assert.Equal( + "401 Unauthorized from https://example.test/mcp. The server wants authentication. Pass --header 'Authorization: Bearer '.", + ConnectError.Describe(Failure(HttpStatusCode.Unauthorized), s_endpoint, HttpTransportMode.AutoDetect, false, " ")); +} From 5bd3e726307135bfdd0dae9b2802712bb11b6d18 Mon Sep 17 00:00:00 2001 From: Lior Shmueli <48066416+ShmueLior@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:25:26 +0200 Subject: [PATCH 2/2] Avoid a double period after a quoted HTTP error preview DescribeWithCauses always appends a period after the line. A body that already ended with a period was printing as "found.". Keep a truncation ellipsis and drop only a trailing sentence period so the message period sits after the closing quote. --- src/McpProbe.Cli/ConnectError.cs | 15 ++++++++++++++- tests/McpProbe.Tests/CliTests.cs | 11 +++++++++++ tests/McpProbe.Tests/ConnectErrorTests.cs | 6 ++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/McpProbe.Cli/ConnectError.cs b/src/McpProbe.Cli/ConnectError.cs index b7789a2..0b40b26 100644 --- a/src/McpProbe.Cli/ConnectError.cs +++ b/src/McpProbe.Cli/ConnectError.cs @@ -42,7 +42,20 @@ public static string Describe(HttpRequestException ex, Uri endpoint, HttpTranspo } var preview = Preview(ex.Message); - return preview.Length == 0 ? $"HTTP {code} from {url}." : $"HTTP {code} from {url}: \"{preview}\""; + if (preview.Length == 0) + { + return $"HTTP {code} from {url}."; + } + + // DescribeWithCauses puts a period after the whole line. A body that already ends with + // a period would then print as `"found.".` Keep a truncation ellipsis; drop only a + // trailing sentence period so the message period sits after the closing quote. + if (preview.EndsWith('.') && !preview.EndsWith("...", StringComparison.Ordinal)) + { + preview = preview[..^1]; + } + + return $"HTTP {code} from {url}: \"{preview}\""; } /// The response body from an SDK exception message as one line: tags stripped when it is HTML, whitespace collapsed, at most 200 characters. diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index 880031d..badc29d 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -599,6 +599,17 @@ public async Task Http_ServerError_HasNoTransportHint() Assert.Equal($"error: HTTP 500 from {stub.Url}: \"boom\".", error.TrimEnd()); } + [Fact] + public async Task Http_PreviewEndingWithAPeriod_DoesNotGetASecondPeriodAfterTheQuote() + { + await using var stub = await StartStubAsync(context => Respond(context, 404, "Profile 'nonexistent' not found.")); + + var (exit, _, error) = await RunAsync("lint", "--http", stub.Url, "--timeout", "10"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Equal($"error: HTTP 404 from {stub.Url}: \"Profile 'nonexistent' not found\".", error.TrimEnd()); + } + [Fact] public async Task Http_HostileBody_IsEscaped() { diff --git a/tests/McpProbe.Tests/ConnectErrorTests.cs b/tests/McpProbe.Tests/ConnectErrorTests.cs index 1036bbf..51be9ba 100644 --- a/tests/McpProbe.Tests/ConnectErrorTests.cs +++ b/tests/McpProbe.Tests/ConnectErrorTests.cs @@ -41,6 +41,12 @@ public void Describe_ShowsTheEndpointWithoutCredentialsOrQuery() => "HTTP 500 from https://example.test/mcp: \"boom\"", ConnectError.Describe(Failure(HttpStatusCode.InternalServerError, "boom"), s_endpoint, HttpTransportMode.AutoDetect, false, null)); + [Fact] + public void Describe_DropsATrailingSentencePeriodInsideThePreviewQuotes() => + Assert.Equal( + "HTTP 404 from https://example.test/mcp: \"Profile 'nonexistent' not found\"", + ConnectError.Describe(Failure(HttpStatusCode.NotFound, "Profile 'nonexistent' not found."), s_endpoint, HttpTransportMode.AutoDetect, false, null)); + [Theory] [InlineData(HttpStatusCode.BadRequest, 400)] [InlineData(HttpStatusCode.NotFound, 404)]