Skip to content

Commit 8c39436

Browse files
PederHPclaude
andcommitted
Address the second Copilot review of modelcontextprotocol#1864
The client now validates every entry returned by skills/list and skills/get against the specification's structural requirements and throws SkillVerificationException for one a host must not load. The server-side handlers apply the same validation to entries from a custom catalog and report a failure as an internal error rather than publishing it. The explicit-frontmatter escape hatch now covers only valid YAML the reader does not support (anchors, aliases, tags, complex keys, nested flow collections, multi-line quoted scalars). A SKILL.md that is not UTF-8, has no frontmatter block, or is malformed is rejected regardless, since no host could parse it either. SkillFrontmatter rejects a compact mapping inside a flow sequence ("[a: b]"), which reference parsers read as a mapping, and unpaired surrogates from \u escapes, while still accepting a surrogate pair. URI validation uses System.Uri for syntax and then checks the raw segments, so "1 bad://x/SKILL.md" is rejected and "file:///x/SKILL.md" is accepted. Optional frontmatter fields that are present but null are rejected rather than treated as absent. A self-comparing test assertion is fixed. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01P6omaTvQiryHtzFHRqUE3b
1 parent f18d7dc commit 8c39436

11 files changed

Lines changed: 296 additions & 47 deletions

File tree

‎docs/concepts/skills/skills.md‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,12 @@ host verifies a skill by parsing the fetched `SKILL.md` itself and comparing fie
9393
entry; a value that one side types as a number and the other as a string is a verification failure. Quote values
9494
such as version numbers that are meant to be strings.
9595

96-
Anchors, aliases, tags, multi-document streams, complex keys, and tab indentation are rejected with a
97-
<xref:System.FormatException> naming the construct. For such a file, the `Create` and `CreateFromDirectory`
98-
overloads that take an explicit `JsonObject` supply the frontmatter directly. When the reader can parse the file,
99-
an explicit object must match it exactly, or the skill is rejected at construction rather than by every host.
96+
Anchors, aliases, tags, complex keys, nested flow collections, and multi-line quoted scalars are valid YAML the
97+
reader does not support; it rejects them with a <xref:System.FormatException> naming the construct. For such a
98+
file, the `Create` and `CreateFromDirectory` overloads that take an explicit `JsonObject` supply the frontmatter
99+
directly. That escape hatch covers only valid-but-unsupported YAML: a file with no frontmatter block, malformed
100+
YAML, or invalid UTF-8 is rejected regardless, since no host could parse it either. When the reader can parse the
101+
file, an explicit object must match it exactly, or the skill is rejected at construction rather than by every host.
100102

101103
#### Custom catalogs
102104

@@ -166,7 +168,10 @@ Skill skill = await client.GetSkillAsync("skill://git-workflow/SKILL.md");
166168
ReadResourceResult contents = await client.ReadSkillResourceAsync(skill, skill.Uri);
167169
```
168170

169-
`ReadSkillResourceAsync` throws <xref:ModelContextProtocol.Extensions.Skills.SkillVerificationException> when the
171+
`ListSkillsAsync` and `GetSkillAsync` validate every entry the server returns against the specification's structural
172+
requirements and throw <xref:ModelContextProtocol.Extensions.Skills.SkillVerificationException> for an entry a host
173+
must not load, such as one whose manifest omits its own `SKILL.md`, carries a malformed digest, or lists a file
174+
outside the skill. `ReadSkillResourceAsync` throws the same exception when the
170175
content's size or digest does not match the manifest, or when the URI is not listed in it at all. In both cases the
171176
content must not be used. To recover, refresh the entry with `GetSkillAsync` and proceed from the new manifest;
172177
because the manifest changed, any approval bound to the previous one is revoked and must be obtained again.

‎src/ModelContextProtocol.Extensions.Skills/Client/McpSkillsClientExtensions.cs‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ public static bool SupportsSkills(this McpClient client)
3939
/// <returns>The listed skills.</returns>
4040
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
4141
/// <exception cref="InvalidOperationException">The server did not declare the MCP Skills extension.</exception>
42+
/// <exception cref="SkillVerificationException">
43+
/// The server returned an entry that violates the specification (for example, a name that does not match its
44+
/// URI, a malformed digest, or a manifest over the per-skill limits). Hosts must not load such entries.
45+
/// </exception>
4246
/// <exception cref="McpException">The request failed or the server returned an error response.</exception>
4347
/// <remarks>
4448
/// <para>
@@ -73,9 +77,10 @@ public static async ValueTask<IList<Skill>> ListSkillsAsync(this McpClient clien
7377
/// <param name="client">The client.</param>
7478
/// <param name="requestParams">The request parameters, including the cursor of the page to retrieve.</param>
7579
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
76-
/// <returns>The page, as returned by the server.</returns>
80+
/// <returns>The page, as returned by the server, with every entry validated against the specification.</returns>
7781
/// <exception cref="ArgumentNullException"><paramref name="client"/> or <paramref name="requestParams"/> is <see langword="null"/>.</exception>
7882
/// <exception cref="InvalidOperationException">The server did not declare the MCP Skills extension.</exception>
83+
/// <exception cref="SkillVerificationException">The server returned an entry that violates the specification.</exception>
7984
/// <exception cref="McpException">The request failed or the server returned an error response.</exception>
8085
public static async ValueTask<ListSkillsResult> ListSkillsAsync(
8186
this McpClient client,
@@ -99,8 +104,15 @@ public static async ValueTask<ListSkillsResult> ListSkillsAsync(
99104
};
100105

101106
JsonRpcResponse response = await client.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
102-
return response.Result?.Deserialize(McpSkillsJsonContext.Default.ListSkillsResult) ??
107+
var result = response.Result?.Deserialize(McpSkillsJsonContext.Default.ListSkillsResult) ??
103108
throw new JsonException($"Unexpected JSON result in the response to '{SkillsProtocol.MethodSkillsList}'.");
109+
110+
foreach (var skill in result.Skills)
111+
{
112+
SkillValidation.ValidateReceived(skill, SkillsProtocol.MethodSkillsList);
113+
}
114+
115+
return result;
104116
}
105117

106118
/// <summary>
@@ -109,9 +121,10 @@ public static async ValueTask<ListSkillsResult> ListSkillsAsync(
109121
/// <param name="client">The client.</param>
110122
/// <param name="uri">The URI of the skill's <c>SKILL.md</c>.</param>
111123
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
112-
/// <returns>The skill's entry.</returns>
124+
/// <returns>The skill's entry, validated against the specification.</returns>
113125
/// <exception cref="ArgumentNullException"><paramref name="client"/> or <paramref name="uri"/> is <see langword="null"/>.</exception>
114126
/// <exception cref="InvalidOperationException">The server did not declare the MCP Skills extension.</exception>
127+
/// <exception cref="SkillVerificationException">The server returned an entry that violates the specification.</exception>
115128
/// <exception cref="McpException">
116129
/// The request failed or the server returned an error response, including <see cref="McpErrorCode.InvalidParams"/>
117130
/// when the server serves no skill at <paramref name="uri"/>.
@@ -165,8 +178,11 @@ public static async ValueTask<GetSkillResult> GetSkillAsync(
165178
};
166179

167180
JsonRpcResponse response = await client.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
168-
return response.Result?.Deserialize(McpSkillsJsonContext.Default.GetSkillResult) ??
181+
var result = response.Result?.Deserialize(McpSkillsJsonContext.Default.GetSkillResult) ??
169182
throw new JsonException($"Unexpected JSON result in the response to '{SkillsProtocol.MethodSkillsGet}'.");
183+
184+
SkillValidation.ValidateReceived(result.Skill, SkillsProtocol.MethodSkillsGet);
185+
return result;
170186
}
171187

172188
/// <summary>

‎src/ModelContextProtocol.Extensions.Skills/Server/McpServerSkill.cs‎

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -308,31 +308,38 @@ private static McpServerSkill CreateCore(string? uri, string? uriPrefix, JsonObj
308308
}
309309

310310
// Read the frontmatter from SKILL.md (always first after sorting). When the caller supplied frontmatter,
311-
// the file is still read so that the two can be checked against each other; if the file uses YAML the
312-
// reader does not support, the caller's frontmatter stands on its own.
311+
// the file is still read so that the two can be checked against each other. The caller's frontmatter
312+
// stands on its own only when the file uses valid YAML the reader does not support; a file that is not
313+
// UTF-8, has no frontmatter block, or is malformed cannot be reproduced by any host and is rejected.
314+
if (!TryDecodeUtf8(contents[0], out string? skillMarkdown))
315+
{
316+
throw new ArgumentException($"{SkillsProtocol.SkillFileName} is not valid UTF-8.", filesParamName);
317+
}
318+
313319
JsonObject? fileFrontmatter = null;
314-
FormatException? frontmatterError = null;
315320
try
316321
{
317-
if (!TryDecodeUtf8(contents[0], out string? skillMarkdown))
318-
{
319-
throw new FormatException($"{SkillsProtocol.SkillFileName} is not valid UTF-8.");
320-
}
321-
322322
fileFrontmatter = SkillFrontmatter.Parse(skillMarkdown!);
323323
}
324+
catch (SkillFrontmatter.UnsupportedYamlException e) when (frontmatter is null)
325+
{
326+
throw new ArgumentException(
327+
$"The frontmatter of {SkillsProtocol.SkillFileName} uses YAML that {nameof(SkillFrontmatter)} does not support: {e.Message} " +
328+
"Supply the frontmatter explicitly with the overload that takes a JsonObject.",
329+
filesParamName);
330+
}
331+
catch (SkillFrontmatter.UnsupportedYamlException)
332+
{
333+
// Explicit frontmatter covers this case.
334+
}
324335
catch (FormatException e)
325336
{
326-
frontmatterError = e;
337+
throw new ArgumentException($"The frontmatter of {SkillsProtocol.SkillFileName} could not be read: {e.Message}", filesParamName);
327338
}
328339

329340
if (frontmatter is null)
330341
{
331-
frontmatter = fileFrontmatter ?? throw new ArgumentException(
332-
$"The frontmatter of {SkillsProtocol.SkillFileName} could not be read: {frontmatterError!.Message} " +
333-
$"If the file uses YAML that {nameof(SkillFrontmatter)} does not support, supply the frontmatter explicitly " +
334-
"with the overload that takes a JsonObject.",
335-
filesParamName);
342+
frontmatter = fileFrontmatter!;
336343
}
337344
else if (fileFrontmatter is not null && !JsonNode.DeepEquals(fileFrontmatter, frontmatter))
338345
{

‎src/ModelContextProtocol.Extensions.Skills/Server/McpSkillsBuilderExtensions.cs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,10 @@ public void Configure(McpServerOptions options)
265265
{
266266
var requestParams = DeserializeParams(request, McpSkillsJsonContext.Default.ListSkillsRequestParams);
267267
var page = await catalog.ListAsync(requestParams?.Cursor, new McpSkillRequestContext(request), cancellationToken).ConfigureAwait(false);
268+
foreach (var entry in page.Skills)
269+
{
270+
ValidateCatalogEntry(entry);
271+
}
268272

269273
var result = new ListSkillsResult
270274
{
@@ -296,6 +300,7 @@ public void Configure(McpServerOptions options)
296300

297301
var skill = await catalog.GetAsync(requestParams!.Uri, new McpSkillRequestContext(request), cancellationToken).ConfigureAwait(false) ??
298302
throw new McpProtocolException($"No skill is served at '{requestParams.Uri}'.", McpErrorCode.InvalidParams);
303+
ValidateCatalogEntry(skill);
299304

300305
var result = new GetSkillResult { Skill = skill };
301306
if (IsJuly2026OrLaterProtocolRequest(request))
@@ -306,6 +311,22 @@ public void Configure(McpServerOptions options)
306311
return JsonSerializer.SerializeToNode(result, McpSkillsJsonContext.Default.GetSkillResult);
307312
}
308313

314+
/// <summary>
315+
/// A custom catalog is trusted to answer, but not to be correct: an invalid entry is a server bug, reported
316+
/// as an internal error rather than published to hosts that would have to reject it.
317+
/// </summary>
318+
private static void ValidateCatalogEntry(Skill? entry)
319+
{
320+
try
321+
{
322+
SkillValidation.Validate(entry!, "entry");
323+
}
324+
catch (ArgumentException e)
325+
{
326+
throw new McpProtocolException($"The skill catalog returned an invalid entry: {e.Message}", McpErrorCode.InternalError);
327+
}
328+
}
329+
309330
private static T? DeserializeParams<T>(JsonRpcRequest request, JsonTypeInfo<T> typeInfo) where T : class
310331
{
311332
if (request.Params is null)

‎src/ModelContextProtocol.Extensions.Skills/SkillFrontmatter.cs‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ public static class SkillFrontmatter
2828
{
2929
private const string Delimiter = "---";
3030

31+
/// <summary>
32+
/// Thrown for YAML that is valid but outside the subset this reader supports, as opposed to malformed
33+
/// frontmatter. Callers that accept explicitly supplied frontmatter may fall back on it for this case only.
34+
/// </summary>
35+
internal sealed class UnsupportedYamlException(string message) : FormatException(message);
36+
3137
/// <summary>
3238
/// Parses the frontmatter at the start of <paramref name="skillMarkdown"/>.
3339
/// </summary>
@@ -222,7 +228,7 @@ private JsonObject ParseMapping(int indent)
222228
string content = line.Content;
223229
if (content[0] == '?')
224230
{
225-
throw new FormatException($"Line {line.Number}: complex mapping keys ('? ') are not supported in frontmatter.");
231+
throw new UnsupportedYamlException($"Line {line.Number}: complex mapping keys ('? ') are not supported in frontmatter.");
226232
}
227233

228234
int consumed;
@@ -351,7 +357,7 @@ private JsonArray ParseSequence(int indent)
351357
return ParseBlockScalar(rest, parentIndent, lineNumber);
352358

353359
case '&' or '*' or '!':
354-
throw new FormatException($"Line {lineNumber}: YAML anchors, aliases, and tags are not supported in frontmatter.");
360+
throw new UnsupportedYamlException($"Line {lineNumber}: YAML anchors, aliases, and tags are not supported in frontmatter.");
355361

356362
case '[':
357363
return ParseFlowSequence(rest, lineNumber);
@@ -675,7 +681,7 @@ private static JsonObject ParseFlowMapping(string text, int lineNumber)
675681
char c = text[pos];
676682
if (c is '[' or '{')
677683
{
678-
throw new FormatException($"Line {lineNumber}: nested flow collections are not supported in frontmatter.");
684+
throw new UnsupportedYamlException($"Line {lineNumber}: nested flow collections are not supported in frontmatter.");
679685
}
680686

681687
if (c is '"' or '\'')
@@ -697,9 +703,14 @@ private static JsonObject ParseFlowMapping(string text, int lineNumber)
697703
}
698704

699705
string plain = text.Substring(start, pos - start).Trim();
706+
if (FindKeySeparator(plain) >= 0)
707+
{
708+
throw new UnsupportedYamlException($"Line {lineNumber}: compact mappings inside flow sequences ('[key: value]') are not supported in frontmatter.");
709+
}
710+
700711
if (plain.Length > 0 && plain[0] is '&' or '*' or '!')
701712
{
702-
throw new FormatException($"Line {lineNumber}: YAML anchors, aliases, and tags are not supported in frontmatter.");
713+
throw new UnsupportedYamlException($"Line {lineNumber}: YAML anchors, aliases, and tags are not supported in frontmatter.");
703714
}
704715

705716
if (plain.Length > 0 && plain[0] is '@' or '`' or '%')
@@ -729,7 +740,20 @@ private static string ParseQuotedScalar(string text, int start, int lineNumber,
729740
}
730741

731742
end = i + 1;
732-
return builder.ToString();
743+
string result = builder.ToString();
744+
for (int k = 0; k < result.Length; k++)
745+
{
746+
if (char.IsHighSurrogate(result[k]) && k + 1 < result.Length && char.IsLowSurrogate(result[k + 1]))
747+
{
748+
k++;
749+
}
750+
else if (char.IsSurrogate(result[k]))
751+
{
752+
throw new FormatException($"Line {lineNumber}: the quoted scalar contains an unpaired surrogate escape, which is not a valid Unicode character.");
753+
}
754+
}
755+
756+
return result;
733757
}
734758

735759
if (quote == '"' && c == '\\')
@@ -783,7 +807,7 @@ private static string ParseQuotedScalar(string text, int start, int lineNumber,
783807
i++;
784808
}
785809

786-
throw new FormatException($"Line {lineNumber}: unterminated quoted scalar; multi-line quoted scalars are not supported.");
810+
throw new UnsupportedYamlException($"Line {lineNumber}: unterminated quoted scalar; multi-line quoted scalars are not supported.");
787811
}
788812

789813
private static int ParseHex(string text, int start, int length, int lineNumber)

0 commit comments

Comments
 (0)