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 @@ -7,11 +7,13 @@ All notable changes to this project are documented here. The format is based on

### Added

- `--bearer-env <VAR>` and `--header-env 'Name: VAR'` on the CLI: HTTP authentication read from environment variables, so tokens are not on the command line. Later sources win for the same header name (`--header`, then `--header-env`, then `--bearer-env`). A missing or empty variable is exit 2 and names the variable, not the value. GitHub Action inputs `bearer-env` and `header-env`, and Azure Pipelines parameters `bearerEnv` and `headerEnv`, pass the variable names through. They need a CLI that has these flags.
- `McpProbeHostOptions.IncludeServerExceptions` (default `true`): in the in-memory host, when a tool throws an exception that is not an `McpException`, the tool error result shows the exception type and message (for example `An error occurred invoking 'update_todo_item': FormatException: ...`) instead of the SDK's generic message, `An error occurred invoking 'update_todo_item'.` Prompts and resources that throw are reported the same way. Set it to `false` for the generic text a remote client would see.
- `ToolSurfaceChange.Before` and `After` hold the previous and current title or description when that is what changed. Other change kinds leave them unset.

### Changed

- A 401 now says `The credentials were rejected.` (it used to say `The credentials in --header were rejected.`), and the hint for a missing token also mentions `--bearer-env`.
- Title and description changes in a tool-surface diff now include a short before and after (truncated and escaped), in the CLI, the HTML report, and snapshot check messages.
- Package tags now include `mcp-server`, `dotnet` and `csharp`. The README opening line describes McpProbe as a .NET test kit for C# MCP server testing.
- The README GitHub Action section now has an inputs and outputs table, a warning not to log `header` or `env`, and pinning guidance (exact tags only; no `@main` or floating major tag until 1.0).
Expand Down
24 changes: 20 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,12 @@ dotnet tool install --global McpProbe.Cli --version 0.5.0-preview

mcpprobe snapshot --stdio "dotnet run --project src/MyServer" --out mcp-tools.json
mcpprobe diff --stdio "dotnet run --project src/MyServer" --baseline mcp-tools.json
mcpprobe lint --http https://localhost:5001/mcp --header "Authorization: Bearer $TOKEN"
mcpprobe lint --http http://localhost:5000/sse --transport sse --header "Authorization: Bearer $TOKEN"
mcpprobe lint --http https://localhost:5001/mcp --bearer-env MCP_TOKEN
mcpprobe lint --http http://localhost:5000/sse --transport sse --bearer-env MCP_TOKEN
```

For authenticated HTTP servers, `--bearer-env <VAR>` sends `Authorization: Bearer <value>` with the value read from the environment variable `VAR`, and `--header-env 'Name: VAR'` does the same for any header. Unlike `--header "Authorization: Bearer $TOKEN"`, the token is not on the command line, so it doesn't end up in shell history or in a log that prints the command. If the same header comes from more than one of these, the order is `--header`, then `--header-env`, then `--bearer-env`, and the last one wins. A missing or empty variable is a usage error (exit `2`) that names the variable, never its value. The variable name is matched the way the operating system does (case-insensitive on Windows).

The `mcpprobe` tool is packed for net8.0 and net10.0 (`RollForward=Major`), so a .NET 8 or .NET 10 runtime must be installed. An SDK is also needed if the `--stdio` command is `dotnet run`. If the apphost errors with "You must install .NET to run this application" even though `dotnet` works, set `DOTNET_ROOT` to that install's root (the directory that contains `dotnet` and the `shared` folder).

`--http` already tries Streamable HTTP and falls back to legacy SSE. Use `--transport streamable-http` or `--transport sse` to pin a mode (`auto` is the default). Legacy SSE servers usually listen at `/sse` (and `/message`), not at the Streamable HTTP path. If the server maps MCP at a prefix such as `/mcp` and enables legacy SSE, the C# SDK places those endpoints under the prefix (`/mcp/sse` and `/mcp/message`). There is no WebSocket transport.
Expand Down Expand Up @@ -282,7 +284,17 @@ jobs:

Pass exactly one of `stdio`, `http`, or `from-file`. Both `diff` and `lint` are on by default. The Action fails the step on a breaking change or a lint finding at or above `--fail-on` (default `warning`, or `failOn` from [`mcpprobe.json`](#config-file-and-ignore-rules) when `fail-on` is empty).

`header` and `env` often carry tokens. Do not log these values.
`header` and `env` often carry tokens. Do not log these values. To authenticate an HTTP server, pass the **name** of an environment variable in `bearer-env` or `header-env`, and set that variable from a secret. The token never appears in the Action's inputs or in the `mcpprobe` command line:

```yaml
- name: Check MCP tool surface
uses: ShmueLior/mcpprobe@v0.5.0-preview
with:
http: https://example.test/mcp
bearer-env: MCP_TOKEN
env:
MCP_TOKEN: ${{ secrets.MCP_TOKEN }}
```

#### Inputs

Expand All @@ -293,6 +305,8 @@ Pass exactly one of `stdio`, `http`, or `from-file`. Both `diff` and `lint` are
| `from-file` | empty | Read the current tool surface from a snapshot file instead of a server. |
| `baseline` | `mcp-tools.json` | The committed snapshot to compare against (diff only). |
| `header` | empty | HTTP headers as 'Name: value', one per line. Only used with http. Do not log these values; they often carry tokens. |
| `bearer-env` | empty | Name of an environment variable that holds a bearer token for the http server. Sends 'Authorization: Bearer <value>'. The input is the variable name, not the token, so the token never appears in the command line. Requires a CLI that has --bearer-env. |
| `header-env` | empty | HTTP headers whose values are read from environment variables, as 'Name: VAR', one per line. Only used with http. Requires a CLI that has --header-env. |
| `env` | empty | Environment variables for the stdio server as NAME=value, one per line. |
| `cwd` | empty | Working directory for the stdio server. |
| `timeout` | `60` | Seconds to wait for the server to start and list its tools. |
Expand Down Expand Up @@ -323,6 +337,8 @@ None of the inputs is marked required in `action.yml`. The wrapper still needs e
| `lint-report` | Path to lint.html if that file was written. Empty otherwise. |
| `diff-report` | Path to diff.html if that file was written. Empty otherwise. |

`bearer-env` and `header-env` need a CLI that has `--bearer-env` / `--header-env`. If you set them and the installed tool lacks the flags, the Action fails fast with a message instead of a generic "unrecognized option".

`strict`, `transport`, and `report` are off by default, so an unchanged workflow runs the same commands as before. `strict` is lint-only. `transport` is only used with `http`. `report` is a directory, not a file: the Action writes `lint.html` and/or `diff.html` there (both checks run by default, so a single file path would overwrite one report with the other). The job summary stays the plain-text report. Upload is left to your workflow.

`config` is the path of a [`mcpprobe.json`](#config-file-and-ignore-rules) for lint. Leave it empty and lint finds one on its own, starting in the step's working directory (the repository root after `actions/checkout`), so a committed `mcpprobe.json` is used without any input. `config` needs a CLI that has `--config`, which is 0.5.0-preview or later; the Action fails fast with a message if the installed tool lacks it.
Expand Down Expand Up @@ -372,7 +388,7 @@ steps:
baseline: mcp-tools.json
```

The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action), `config` and `lintBaseline`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. `config` and `lintBaseline` need `refs/tags/v0.5.0-preview` or later. Upload is a separate step; the template does not publish an artifact:
The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action), `config`, `lintBaseline`, `bearerEnv` and `headerEnv`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. `config` and `lintBaseline` need `refs/tags/v0.5.0-preview` or later. `bearerEnv` and `headerEnv` need a CLI that has `--bearer-env` / `--header-env`. Upload is a separate step; the template does not publish an artifact:

```yaml
- task: PublishPipelineArtifact@1
Expand Down
17 changes: 17 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,21 @@ inputs:
log these values; they often carry tokens.
required: false
default: ''
bearer-env:
description: >-
Name of an environment variable that holds a bearer token for the http
server. Sends 'Authorization: Bearer <value>'. The input is the variable
name, not the token, so the token never appears in the command line.
Requires a CLI that has --bearer-env.
required: false
default: ''
header-env:
description: >-
HTTP headers whose values are read from environment variables, as
'Name: VAR', one per line. Only used with http. Requires a CLI that has
--header-env.
required: false
default: ''
env:
description: Environment variables for the stdio server as NAME=value, one per line.
required: false
Expand Down Expand Up @@ -151,6 +166,8 @@ runs:
MCPPROBE_FROM_FILE: ${{ inputs.from-file }}
MCPPROBE_BASELINE: ${{ inputs.baseline }}
MCPPROBE_HEADER: ${{ inputs.header }}
MCPPROBE_BEARER_ENV: ${{ inputs.bearer-env }}
MCPPROBE_HEADER_ENV: ${{ inputs.header-env }}
MCPPROBE_ENV: ${{ inputs.env }}
MCPPROBE_CWD: ${{ inputs.cwd }}
MCPPROBE_TIMEOUT: ${{ inputs.timeout }}
Expand Down
12 changes: 12 additions & 0 deletions action/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,14 @@ config_path=$(trim_ws "${MCPPROBE_CONFIG:-}")
if [[ -n "$config_path" && "$run_lint" == true ]]; then
require_cli_flag config --config
fi
bearer_env=$(trim_ws "${MCPPROBE_BEARER_ENV:-}")
if [[ -n "${MCPPROBE_HEADER_ENV:-}" ]]; then
require_cli_flag header-env --header-env
fi
if [[ -n "$bearer_env" ]]; then
require_cli_flag bearer-env --bearer-env
fi

lint_baseline=$(trim_ws "${MCPPROBE_LINT_BASELINE:-}")
if [[ -n "$lint_baseline" && "$run_lint" == true ]]; then
require_cli_flag lint-baseline --baseline
Expand All @@ -297,6 +305,10 @@ fi
while IFS= read -r line; do
common_args+=(--header "$line")
done < <(each_nonempty_line "${MCPPROBE_HEADER:-}")
while IFS= read -r line; do
common_args+=(--header-env "$line")
done < <(each_nonempty_line "${MCPPROBE_HEADER_ENV:-}")
[[ -n "$bearer_env" ]] && common_args+=(--bearer-env "$bearer_env")
while IFS= read -r line; do
common_args+=(--env "$line")
done < <(each_nonempty_line "${MCPPROBE_ENV:-}")
Expand Down
4 changes: 2 additions & 2 deletions src/McpProbe.Cli/ConnectError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public static string Describe(HttpRequestException ex, Uri endpoint, HttpTranspo
{
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>'.";
? $"401 Unauthorized from {url}. The credentials were rejected{challenge}."
: $"401 Unauthorized from {url}. The server wants authentication{challenge}. Pass --header 'Authorization: Bearer <token>', or --bearer-env <VAR> to read the token from an environment variable.";
}

if (status is HttpStatusCode.BadRequest or HttpStatusCode.NotFound or HttpStatusCode.MethodNotAllowed)
Expand Down
91 changes: 90 additions & 1 deletion src/McpProbe.Cli/ServerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ internal sealed class ServerOptions
AllowMultipleArgumentsPerToken = false,
};

private readonly Option<string[]> _headerEnv = new("--header-env")
{
Description = "HTTP header whose value is read from an environment variable, as 'Name: VAR'. Repeatable. Only with --http. The value is never printed.",
AllowMultipleArgumentsPerToken = false,
};

private readonly Option<string> _bearerEnv = new("--bearer-env")
{
Description = "Name of an environment variable that holds a bearer token. Sends 'Authorization: Bearer <value>'. Only with --http. The value is never printed.",
};

private readonly Option<string[]> _env = new("--env")
{
Description = "Environment variable for the stdio server as NAME=value. Repeatable. Only with --stdio.",
Expand Down Expand Up @@ -65,6 +76,8 @@ public void AddTo(Command command)
command.Options.Add(_http);
command.Options.Add(_transport);
command.Options.Add(_headers);
command.Options.Add(_headerEnv);
command.Options.Add(_bearerEnv);
command.Options.Add(_env);
command.Options.Add(_cwd);
command.Options.Add(_timeout);
Expand Down Expand Up @@ -102,6 +115,13 @@ public void AddTo(Command command)
result.AddError("--transport must be auto, streamable-http, or sse.");
}
}

var hasHeaderEnv = result.GetResult(_headerEnv) is { Implicit: false };
var hasBearerEnv = result.GetResult(_bearerEnv) is { Implicit: false };
if ((hasHeaderEnv || hasBearerEnv) && result.GetResult(_http) is null)
{
result.AddError("--header-env and --bearer-env can only be used with --http.");
}
});
}

Expand All @@ -127,7 +147,7 @@ public async Task<ToolSurface> CaptureAsync(ParseResult parse, TextWriter stderr
var target = new ServerTarget(
parse.GetValue(_stdio),
parse.GetValue(_http) is { } url ? ParseHttpUrl(url) : null,
ParsePairs(parse.GetValue(_headers), ':', "--header", "Name: value"),
BuildHttpHeaders(parse),
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,
Expand Down Expand Up @@ -188,6 +208,75 @@ public async Task<ToolSurface> CaptureAsync(ParseResult parse, TextWriter stderr
_ => null,
};

/// <summary>
/// Builds the HTTP headers from <c>--header</c>, then <c>--header-env</c>, then <c>--bearer-env</c>. Later sources win
/// for the same header name (compared case-insensitively). Environment-backed values are read here and never printed.
/// </summary>
private Dictionary<string, string> BuildHttpHeaders(ParseResult parse)
{
var headers = ParsePairs(parse.GetValue(_headers), ':', "--header", "Name: value");
var headerEnv = parse.GetValue(_headerEnv) ?? [];
var bearerEnv = parse.GetValue(_bearerEnv);

if ((headerEnv.Length > 0 || bearerEnv is not null) && parse.GetResult(_http) is null)
{
throw new ArgumentException("--header-env and --bearer-env can only be used with --http.");
}

foreach (var pair in headerEnv)
{
var index = pair.IndexOf(':', StringComparison.Ordinal);
if (index <= 0)
{
throw new ArgumentException($"Invalid --header-env '{pair}'. Use 'Name: VAR', where VAR is the name of an environment variable.");
}

var name = pair[..index].Trim();
var variable = pair[(index + 1)..].Trim();
if (name.Length == 0)
{
throw new ArgumentException($"Invalid --header-env '{pair}'. Use 'Name: VAR', where VAR is the name of an environment variable.");
}

SetHeader(headers, name, ReadVariable(variable, "--header-env"));
}

if (bearerEnv is not null)
{
var token = ReadVariable(bearerEnv.Trim(), "--bearer-env");
var value = token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) ? token : "Bearer " + token;
SetHeader(headers, "Authorization", value);
}

return headers;
}

private static string ReadVariable(string variable, string option)
{
if (variable.Length == 0 || variable.Any(c => char.IsWhiteSpace(c) || c is '=' or ':'))
{
throw new ArgumentException($"Invalid environment variable name '{variable}' for {option}.");
}

var value = Environment.GetEnvironmentVariable(variable);
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException($"Environment variable '{variable}' for {option} is not set or is empty.");
}

return value.Trim();
}

private static void SetHeader(Dictionary<string, string> headers, string name, string value)
{
foreach (var existing in headers.Keys.Where(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase)).ToList())
{
headers.Remove(existing);
}

headers[name] = value;
}

private static Dictionary<string, string> ParsePairs(string[]? values, char separator, string option, string format)
{
var result = new Dictionary<string, string>(StringComparer.Ordinal);
Expand Down
8 changes: 8 additions & 0 deletions templates/azure-pipelines/mcpprobe.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ parameters:
- name: header
type: string
default: ''
- name: bearerEnv
type: string
default: ''
- name: headerEnv
type: string
default: ''
- name: env
type: string
default: ''
Expand Down Expand Up @@ -124,6 +130,8 @@ steps:
MCPPROBE_FROM_FILE: ${{ parameters.fromFile }}
MCPPROBE_BASELINE: ${{ parameters.baseline }}
MCPPROBE_HEADER: ${{ parameters.header }}
MCPPROBE_BEARER_ENV: ${{ parameters.bearerEnv }}
MCPPROBE_HEADER_ENV: ${{ parameters.headerEnv }}
MCPPROBE_ENV: ${{ parameters.env }}
MCPPROBE_CWD: ${{ parameters.cwd }}
MCPPROBE_TIMEOUT: ${{ parameters.timeout }}
Expand Down
Loading
Loading