Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <token>'`, 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

Expand Down
3 changes: 2 additions & 1 deletion src/McpProbe.Cli/CliApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@ private static string DescribeWithCauses(Exception ex)
var messages = new List<string> { 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);
}
Expand Down
99 changes: 99 additions & 0 deletions src/McpProbe.Cli/ConnectError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using System.Net;
using System.Text.RegularExpressions;
using McpProbe.Internal;
using ModelContextProtocol.Client;

namespace McpProbe.Cli;

/// <summary>
/// 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.
/// </summary>
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 <token>'.";
}

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);
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}\"";
}

/// <summary>The response body from an SDK exception message as one line: tags stripped when it is HTML, whitespace collapsed, at most 200 characters.</summary>
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();
}

/// <summary>Remembers the last <c>WWW-Authenticate</c> value the server sent. The body is left alone, the SDK reads it.</summary>
internal sealed class ChallengeCapture() : DelegatingHandler(new SocketsHttpHandler())
{
private volatile string? _challenge;

public string? Challenge => _challenge;

protected override async Task<HttpResponseMessage> 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;
}
}
34 changes: 26 additions & 8 deletions src/McpProbe.Cli/ServerConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,18 @@ internal sealed record ServerTarget(
IReadOnlyDictionary<string, string> Headers,
IReadOnlyDictionary<string, string?> Environment,
string? WorkingDirectory,
HttpTransportMode TransportMode);
HttpTransportMode TransportMode,
TimeSpan Timeout);

internal static class ServerConnector
{
public static async Task<McpClient> ConnectAsync(ServerTarget target, StderrBuffer serverStderr, CancellationToken cancellationToken)
/// <summary>
/// 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.
/// </summary>
private static readonly TimeSpan s_shutdownTimeout = TimeSpan.FromMilliseconds(500);

public static async Task<McpClient> ConnectAsync(ServerTarget target, StderrBuffer serverStderr, ChallengeCapture challenge, CancellationToken cancellationToken)
{
IClientTransport transport;
if (target.StdioCommand is not null)
Expand All @@ -34,17 +41,28 @@ public static async Task<McpClient> ConnectAsync(ServerTarget target, StderrBuff
WorkingDirectory = target.WorkingDirectory,
EnvironmentVariables = target.Environment.Count == 0 ? null : new Dictionary<string, string?>(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<string, string>(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<string, string>(target.Headers),
TransportMode = target.TransportMode,
ConnectionTimeout = target.Timeout,
},
http,
loggerFactory: null,
ownsHttpClient: true);
}
else
{
Expand Down
16 changes: 13 additions & 3 deletions src/McpProbe.Cli/ServerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,17 @@ public async Task<ToolSurface> 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);
Expand All @@ -160,7 +162,15 @@ public async Task<ToolSurface> 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;
Expand Down
149 changes: 144 additions & 5 deletions tests/McpProbe.Tests/CliTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -534,10 +539,119 @@ 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, "<html><body><h1>405</h1><p>Not here</p></body></html>"));

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 = "<!DOCTYPE html><html><head><title>Nope</title></head><body><h1>Not &amp; here</h1>\n<p>" + new string('x', 500) + "</p></body></html>";
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_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()
{
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 <token>'.",
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()
{
Expand Down Expand Up @@ -576,6 +690,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);
}

/// <summary>A plain HTTP server that answers every request with <paramref name="handler"/>, no MCP.</summary>
private static async Task<Stub> StartStubAsync(Func<HttpContext, Task> 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<IServer>().Features.Get<IServerAddressesFeature>()!.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();
Expand Down
Loading
Loading