Repository navigation
Description
Description
McpClient.ReadResourceAsync(uriTemplate, arguments) throws ArgumentOutOfRangeException when a reserved ({+var}) or fragment ({#var}) URI-template expansion contains a supplementary Unicode character, such as an emoji. This prevents a client from reading resources whose template arguments include those characters, before a resources/read request is sent.
Reproduction
On main at 3338e88e15c42cfc27465143c140d7d10f1a2707, with a connected client and a resource handler that echoes the requested URI:
var result = await client.ReadResourceAsync(
"test://resource/{+name}",
new Dictionary<string, object?> { ["name"] = "hello\U0001F600" });Expected: The request URI is test://resource/hello%F0%9F%98%80, with U+1F600 percent-encoded as UTF-8, and the resource can be read.
Actual: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'ch'). The focused regression test fails on net10.0 with this stack:
at System.Text.Rune..ctor(Char ch)
at ModelContextProtocol.UriTemplate.<Encode>g__AppendHex|6_0(...) in UriTemplate.cs:487
at ModelContextProtocol.UriTemplate.Encode(String value, Boolean allowReserved) in UriTemplate.cs:467
at ModelContextProtocol.UriTemplate.FormatUri(...) in UriTemplate.cs:392
at ModelContextProtocol.Client.McpClient.ReadResourceAsync(...) in McpClient.Methods.cs:596
I reproduced this by adding a [Fact] to McpClientResourceTemplateTests using its in-memory client/server fixture, then running:
dotnet test tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj -f net10.0 --filter "FullyQualifiedName~ReservedExpansion_EncodesSupplementaryUnicodeScalar"
Result: 1 failed, 0 passed. The client/server connection completed; expansion failed before the read request.
Cause and possible fix
The reserved-expansion encoder loops over UTF-16 char values and calls new Rune(c) for each non-ASCII character. A supplementary Unicode scalar is a surrogate pair, so constructing a Rune from its first char throws. Decode the scalar from the input span (and advance past both UTF-16 code units) before writing its UTF-8 percent-encoded bytes. A regression test could cover {+name} and {#name} with supplementary Unicode characters.
Relevant code: UriTemplate.cs:487, McpClient.Methods.cs:596. RFC 6570 specifies UTF-8 percent encoding for characters outside the allowed URI set.
Activity
pournasserian commentedon Oct 14, 2026
I'd like to take this one. The fix reads the whole surrogate pair before UTF-8 encoding it in
UriTemplate.Encode. I'm adding regression tests for{+var}and{#var}. A PR is coming shortly.