Skip to content

Commit f18d7dc

Browse files
PederHPclaude
andcommitted
Address the Copilot review of modelcontextprotocol#1864
Catalogs now receive an McpSkillRequestContext carrying the JSON-RPC request, the caller's ClaimsPrincipal when the transport supplies one, and per-request items. The skills methods are raw handlers and do not pass through the request filters that guard the resource methods, so a catalog whose skills are not visible to every caller needs the caller to decide with; the docs and API remarks now say so plainly. The interface changes before it ships rather than after. InMemoryMcpSkillCatalog keeps its own copy of each entry, so mutating a Skill (or McpServerSkill.ProtocolSkill) after registration cannot make the published manifest disagree with the served bytes. Validation tightens to what the specifications require: resource and skill URIs must be absolute, without query or fragment, and without empty, '.', or '..' path segments, so a prefix check establishes containment; the total size check cannot overflow; and the Agent Skills frontmatter limits are enforced (description at most 1024 characters, compatibility 1 to 500, license and allowed-tools strings, metadata a map of strings). CreateFromDirectory rejects a root directory that is itself a link, to match its documented behaviour. SkillFrontmatter rejects malformed block scalar headers (repeated indicators or trailing text), comments inside flow collections (which YAML treats as running to the end of the line), and \U escapes that are not Unicode scalar values, each with a FormatException. The catalog contract now describes cursors as opaque positions a catalog may resume from rather than tokens it must have issued. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01P6omaTvQiryHtzFHRqUE3b
1 parent 932c318 commit f18d7dc

12 files changed

Lines changed: 400 additions & 48 deletions

File tree

‎docs/concepts/skills/skills.md‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,9 @@ builder.Services.AddMcpServer().WithHttpTransport().WithSkills([gitWorkflow, ref
7575
```
7676

7777
All of these validate the skill against the specification and throw <xref:System.ArgumentException> with a
78-
specific message when, for example, the frontmatter `name` does not match the URI, `SKILL.md` is missing, or the
79-
skill exceeds the per-skill limits of 512 files or 16 MiB. File contents are copied when the skill is created, so
78+
specific message when, for example, the frontmatter `name` does not match the URI, `description` exceeds the
79+
Agent Skills limit of 1024 characters, `metadata` is not a map of strings, a resource URI escapes the skill's
80+
directory, `SKILL.md` is missing, or the skill exceeds the per-skill limits of 512 files or 16 MiB. File contents are copied when the skill is created, so
8081
later changes to a caller's buffer or to files on disk do not affect what is served. `CreateFromDirectory` does not
8182
follow symbolic links, since a link can point outside the skill directory; it throws if it encounters one. File
8283
names containing characters with URI syntax (such as `{`, `?`, or a space) are percent-encoded in the resource URIs.
@@ -105,21 +106,26 @@ When skills come from a database, a file share, or a large or generated catalog,
105106
```csharp
106107
public sealed class DatabaseSkillCatalog(SkillRepository repository) : IMcpSkillCatalog
107108
{
108-
public async ValueTask<McpSkillPage> ListAsync(string? cursor, CancellationToken cancellationToken)
109+
public async ValueTask<McpSkillPage> ListAsync(string? cursor, McpSkillRequestContext context, CancellationToken cancellationToken)
109110
{
110-
var (skills, nextCursor) = await repository.GetPageAsync(cursor, pageSize: 50, cancellationToken);
111+
string tenant = GetTenant(context.User);
112+
var (skills, nextCursor) = await repository.GetPageAsync(tenant, cursor, pageSize: 50, cancellationToken);
111113
return new McpSkillPage { Skills = skills, NextCursor = nextCursor };
112114
}
113115

114-
public ValueTask<Skill?> GetAsync(string uri, CancellationToken cancellationToken) =>
115-
repository.FindAsync(uri, cancellationToken);
116+
public ValueTask<Skill?> GetAsync(string uri, McpSkillRequestContext context, CancellationToken cancellationToken) =>
117+
repository.FindAsync(GetTenant(context.User), uri, cancellationToken);
116118
}
117119
```
118120

121+
Both methods receive an <xref:ModelContextProtocol.Extensions.Skills.McpSkillRequestContext> with the JSON-RPC request,
122+
the caller's <xref:System.Security.Claims.ClaimsPrincipal> when the transport supplies one (the ASP.NET Core
123+
transport does), and any items that incoming-message filters attached to the request.
124+
119125
A catalog supplies entries only; the skills' files must still be served as resources, since hosts read them with
120126
`resources/read`. A catalog may list only part of what it serves, or nothing at all, as long as `GetAsync` answers
121-
for every skill the server serves. Throw <xref:ModelContextProtocol.McpProtocolException> with
122-
<xref:ModelContextProtocol.McpErrorCode.InvalidParams> for a cursor the catalog did not issue.
127+
for every skill the server serves to the caller. Throw <xref:ModelContextProtocol.McpProtocolException> with
128+
<xref:ModelContextProtocol.McpErrorCode.InvalidParams> for a cursor the catalog cannot interpret.
123129
<xref:ModelContextProtocol.Extensions.Skills.InMemoryMcpSkillCatalog> is the built-in implementation over a fixed
124130
set of entries and can be composed into a custom one.
125131

@@ -175,6 +181,12 @@ that read resources through other means.
175181
Skill content is instructional text delivered to a model and is therefore a prompt-injection surface. The
176182
specification places most of the burden on hosts. In particular:
177183

184+
- `skills/list` and `skills/get` are registered as raw request handlers, so they do not pass through the request
185+
filters that guard the built-in resource methods, including the ASP.NET Core authorization filters. A listing
186+
therefore discloses frontmatter, file names, sizes, and digests to any caller the transport admits. If some
187+
callers must not see some skills, implement <xref:ModelContextProtocol.Extensions.Skills.IMcpSkillCatalog> and
188+
decide from the request context's user, and guard the corresponding resources the same way. The built-in
189+
in-memory catalog serves the same entries to every caller.
178190
- Treat MCP-served skill content as untrusted model input, and tag it with its originating server when it enters
179191
the model's context.
180192
- Digests are unsigned and come from the same server as the content. A match proves consistency between the entry

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

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ namespace ModelContextProtocol.Extensions.Skills;
1717
/// A catalog is responsible only for the entries. The skills' files must additionally be served as ordinary
1818
/// resources through <c>resources/read</c>, since that is how hosts fetch skill content.
1919
/// </para>
20+
/// <para>
21+
/// The skills methods do not pass through the request filters that guard the built-in resource methods, so a
22+
/// catalog whose skills are not visible to every caller must decide what to return from the
23+
/// <see cref="McpSkillRequestContext"/> it receives, and the corresponding resources must be guarded the same way.
24+
/// </para>
2025
/// </remarks>
2126
public interface IMcpSkillCatalog
2227
{
@@ -26,28 +31,32 @@ public interface IMcpSkillCatalog
2631
/// <param name="cursor">
2732
/// An opaque cursor returned by a previous call, or <see langword="null"/> to start at the first page.
2833
/// </param>
34+
/// <param name="context">The request being answered, including the caller's identity when the transport supplies one.</param>
2935
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
3036
/// <returns>
3137
/// A page of entries, and the cursor for the following page when more entries remain. A skill's manifest is
3238
/// never split across pages.
3339
/// </returns>
3440
/// <remarks>
3541
/// Returning an empty page is valid. Hosts must not treat an empty listing as proof that a server has no skills.
36-
/// Throw <see cref="McpProtocolException"/> with <see cref="McpErrorCode.InvalidParams"/> for a cursor that
37-
/// this catalog did not issue.
42+
/// Throw <see cref="McpProtocolException"/> with <see cref="McpErrorCode.InvalidParams"/> for a cursor this
43+
/// catalog cannot interpret. A cursor is an opaque position, not a capability: a catalog may resume from a
44+
/// well-formed cursor it does not recognize, as <see cref="InMemoryMcpSkillCatalog"/> does.
3845
/// </remarks>
39-
ValueTask<McpSkillPage> ListAsync(string? cursor, CancellationToken cancellationToken);
46+
ValueTask<McpSkillPage> ListAsync(string? cursor, McpSkillRequestContext context, CancellationToken cancellationToken);
4047

4148
/// <summary>
4249
/// Gets the entry for a single skill by the URI of its <c>SKILL.md</c>.
4350
/// </summary>
4451
/// <param name="uri">The URI of the skill's <c>SKILL.md</c>.</param>
52+
/// <param name="context">The request being answered, including the caller's identity when the transport supplies one.</param>
4553
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
4654
/// <returns>
47-
/// The skill's entry, or <see langword="null"/> if this catalog does not serve a skill at <paramref name="uri"/>.
55+
/// The skill's entry, or <see langword="null"/> if this catalog does not serve a skill at <paramref name="uri"/>
56+
/// to this caller.
4857
/// </returns>
4958
/// <remarks>
50-
/// This must answer for every skill the server serves, including skills omitted from <see cref="ListAsync"/>.
59+
/// This must answer for every skill the server serves to the caller, including skills omitted from <see cref="ListAsync"/>.
5160
/// </remarks>
52-
ValueTask<Skill?> GetAsync(string uri, CancellationToken cancellationToken);
61+
ValueTask<Skill?> GetAsync(string uri, McpSkillRequestContext context, CancellationToken cancellationToken);
5362
}

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,13 @@ namespace ModelContextProtocol.Extensions.Skills;
1111
/// so a server cannot publish an entry a conforming host would refuse to load.
1212
/// </para>
1313
/// <para>
14-
/// Entries are ordered by URI so that pagination is stable across calls. Cursors are keyset cursors over that
15-
/// order rather than offsets.
14+
/// The catalog keeps its own copy of every entry, so later changes to the objects passed to the constructor do
15+
/// not affect what is served. Entries are ordered by URI so that pagination is stable across calls. Cursors are
16+
/// keyset cursors over that order rather than offsets.
17+
/// </para>
18+
/// <para>
19+
/// Every caller sees the same entries. For a catalog whose contents depend on the caller, implement
20+
/// <see cref="IMcpSkillCatalog"/> directly and consult <see cref="McpSkillRequestContext.User"/>.
1621
/// </para>
1722
/// </remarks>
1823
public sealed class InMemoryMcpSkillCatalog : IMcpSkillCatalog
@@ -54,7 +59,7 @@ public InMemoryMcpSkillCatalog(IEnumerable<Skill> skills, int pageSize = 50)
5459
throw new ArgumentException($"Duplicate skill URI '{skill.Uri}'.", nameof(skills));
5560
}
5661

57-
_byUri.Add(skill.Uri, skill);
62+
_byUri.Add(skill.Uri, SkillValidation.Snapshot(skill));
5863
}
5964

6065
_ordered = [.. _byUri.Values];
@@ -68,7 +73,7 @@ public InMemoryMcpSkillCatalog(IEnumerable<Skill> skills, int pageSize = 50)
6873
public int Count => _ordered.Length;
6974

7075
/// <inheritdoc />
71-
public ValueTask<McpSkillPage> ListAsync(string? cursor, CancellationToken cancellationToken)
76+
public ValueTask<McpSkillPage> ListAsync(string? cursor, McpSkillRequestContext context, CancellationToken cancellationToken)
7277
{
7378
cancellationToken.ThrowIfCancellationRequested();
7479

@@ -97,7 +102,7 @@ public ValueTask<McpSkillPage> ListAsync(string? cursor, CancellationToken cance
97102
}
98103

99104
/// <inheritdoc />
100-
public ValueTask<Skill?> GetAsync(string uri, CancellationToken cancellationToken)
105+
public ValueTask<Skill?> GetAsync(string uri, McpSkillRequestContext context, CancellationToken cancellationToken)
101106
{
102107
#if NET
103108
ArgumentNullException.ThrowIfNull(uri);

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ private McpServerSkill(Skill protocolSkill, IReadOnlyList<McpServerResource> res
4242
/// <summary>
4343
/// Gets the skill's entry, as returned by <c>skills/list</c> and <c>skills/get</c>.
4444
/// </summary>
45+
/// <remarks>
46+
/// The catalog that <c>WithSkills</c> creates keeps its own copy of this entry, so changes made to this object
47+
/// after registration do not affect what is served.
48+
/// </remarks>
4549
public Skill ProtocolSkill { get; }
4650

4751
/// <summary>
@@ -400,6 +404,14 @@ private static List<McpServerSkillFile> ReadDirectory(string directoryPath)
400404
throw new DirectoryNotFoundException($"The skill directory '{fullDirectory}' does not exist.");
401405
}
402406

407+
if ((File.GetAttributes(fullDirectory) & FileAttributes.ReparsePoint) != 0)
408+
{
409+
throw new ArgumentException(
410+
$"'{fullDirectory}' is a symbolic link or other reparse point. Links are not followed when loading a skill directory, " +
411+
"because a link can point outside the intended location. Pass the target directory instead.",
412+
nameof(directoryPath));
413+
}
414+
403415
if (!fullDirectory.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
404416
{
405417
fullDirectory += Path.DirectorySeparatorChar;
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
using ModelContextProtocol.Protocol;
2+
using System.Security.Claims;
3+
4+
namespace ModelContextProtocol.Extensions.Skills;
5+
6+
/// <summary>
7+
/// Describes the request an <see cref="IMcpSkillCatalog"/> is answering.
8+
/// </summary>
9+
/// <remarks>
10+
/// <para>
11+
/// The skills methods are registered as raw request handlers, so they do not pass through the typed request
12+
/// filter pipeline that guards the built-in resource methods (for example, the ASP.NET Core authorization
13+
/// filters). A catalog that must not disclose every skill to every caller makes that decision itself, from the
14+
/// <see cref="User"/> and any <see cref="Items"/> that incoming-message filters attached to the request.
15+
/// </para>
16+
/// <para>
17+
/// <see cref="User"/> is populated by the ASP.NET Core transport from the HTTP request's principal. For other
18+
/// transports, or when no authentication is configured, it is <see langword="null"/>.
19+
/// </para>
20+
/// </remarks>
21+
public sealed class McpSkillRequestContext
22+
{
23+
/// <summary>
24+
/// Initializes a new instance of the <see cref="McpSkillRequestContext"/> class.
25+
/// </summary>
26+
/// <param name="jsonRpcRequest">The JSON-RPC request being answered.</param>
27+
/// <exception cref="ArgumentNullException"><paramref name="jsonRpcRequest"/> is <see langword="null"/>.</exception>
28+
public McpSkillRequestContext(JsonRpcRequest jsonRpcRequest)
29+
{
30+
#if NET
31+
ArgumentNullException.ThrowIfNull(jsonRpcRequest);
32+
#else
33+
if (jsonRpcRequest is null) throw new ArgumentNullException(nameof(jsonRpcRequest));
34+
#endif
35+
36+
JsonRpcRequest = jsonRpcRequest;
37+
}
38+
39+
/// <summary>
40+
/// Gets the JSON-RPC request being answered.
41+
/// </summary>
42+
public JsonRpcRequest JsonRpcRequest { get; }
43+
44+
/// <summary>
45+
/// Gets the authenticated user making the request, or <see langword="null"/> if none is associated with it.
46+
/// </summary>
47+
public ClaimsPrincipal? User => JsonRpcRequest.Context?.User;
48+
49+
/// <summary>
50+
/// Gets the per-request items that incoming-message filters attached to the request, if any.
51+
/// </summary>
52+
public IDictionary<string, object?>? Items => JsonRpcRequest.Context?.Items;
53+
54+
/// <summary>
55+
/// Gets the protocol version the request was made under, when the transport or the request carried one.
56+
/// </summary>
57+
public string? ProtocolVersion => JsonRpcRequest.Context?.ProtocolVersion;
58+
}

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,12 @@ public static IMcpServerBuilder WithSkillsFromDirectory(
195195
/// automatically, build the skills with <see cref="McpServerSkill"/> and use the
196196
/// <see cref="WithSkills(IMcpServerBuilder, IEnumerable{McpServerSkill}, Action{McpSkillsOptions})"/> overload.
197197
/// </para>
198+
/// <para>
199+
/// <c>skills/list</c> and <c>skills/get</c> are registered as raw request handlers and do not pass through the
200+
/// request filters that guard the built-in resource methods, such as the ASP.NET Core authorization filters.
201+
/// When some callers must not see some skills, the catalog decides from the <see cref="McpSkillRequestContext"/>
202+
/// it receives, and the corresponding file resources must be guarded separately.
203+
/// </para>
198204
/// </remarks>
199205
public static IMcpServerBuilder WithSkills(
200206
this IMcpServerBuilder builder,
@@ -258,7 +264,7 @@ public void Configure(McpServerOptions options)
258264
private async ValueTask<JsonNode?> HandleListSkillsAsync(JsonRpcRequest request, CancellationToken cancellationToken)
259265
{
260266
var requestParams = DeserializeParams(request, McpSkillsJsonContext.Default.ListSkillsRequestParams);
261-
var page = await catalog.ListAsync(requestParams?.Cursor, cancellationToken).ConfigureAwait(false);
267+
var page = await catalog.ListAsync(requestParams?.Cursor, new McpSkillRequestContext(request), cancellationToken).ConfigureAwait(false);
262268

263269
var result = new ListSkillsResult
264270
{
@@ -288,7 +294,7 @@ public void Configure(McpServerOptions options)
288294
throw new McpProtocolException("The 'uri' parameter is required.", McpErrorCode.InvalidParams);
289295
}
290296

291-
var skill = await catalog.GetAsync(requestParams!.Uri, cancellationToken).ConfigureAwait(false) ??
297+
var skill = await catalog.GetAsync(requestParams!.Uri, new McpSkillRequestContext(request), cancellationToken).ConfigureAwait(false) ??
292298
throw new McpProtocolException($"No skill is served at '{requestParams.Uri}'.", McpErrorCode.InvalidParams);
293299

294300
var result = new GetSkillResult { Skill = skill };

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

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -437,27 +437,39 @@ private string CollectPlainContinuation(string first, int parentIndent, int line
437437
bool literal = header[0] == '|';
438438
char chomping = 'c';
439439
int explicitIndent = 0;
440-
for (int i = 1; i < header.Length; i++)
440+
int headerPos = 1;
441+
for (; headerPos < header.Length && header[headerPos] != ' '; headerPos++)
441442
{
442-
char c = header[i];
443+
char c = header[headerPos];
443444
if (c is '-' or '+')
444445
{
446+
if (chomping != 'c')
447+
{
448+
throw new FormatException($"Line {lineNumber}: invalid block scalar header '{header}': repeated chomping indicator.");
449+
}
450+
445451
chomping = c == '-' ? 's' : 'k';
446452
}
447453
else if (c is >= '1' and <= '9')
448454
{
455+
if (explicitIndent != 0)
456+
{
457+
throw new FormatException($"Line {lineNumber}: invalid block scalar header '{header}': repeated indentation indicator.");
458+
}
459+
449460
explicitIndent = c - '0';
450461
}
451-
else if (c == ' ' || c == '#')
452-
{
453-
break;
454-
}
455462
else
456463
{
457464
throw new FormatException($"Line {lineNumber}: invalid block scalar header '{header}'.");
458465
}
459466
}
460467

468+
if (StripComment(header.Substring(headerPos)).Trim().Length != 0)
469+
{
470+
throw new FormatException($"Line {lineNumber}: invalid block scalar header '{header}': only a comment may follow the indicators.");
471+
}
472+
461473
// Gather the raw lines of the block: everything blank, plus everything indented more than the parent.
462474
var raw = new List<string>();
463475
int contentIndent = explicitIndent > 0 ? parentIndent + explicitIndent : -1;
@@ -676,6 +688,11 @@ private static JsonObject ParseFlowMapping(string text, int lineNumber)
676688
int start = pos;
677689
while (pos < text.Length && terminators.IndexOf(text[pos]) < 0)
678690
{
691+
if (text[pos] == '#' && (pos == start || text[pos - 1] is ' ' or '\t'))
692+
{
693+
throw new FormatException($"Line {lineNumber}: a comment inside a flow collection runs to the end of the line, leaving the collection unterminated. Move the comment after the closing bracket.");
694+
}
695+
679696
pos++;
680697
}
681698

@@ -744,7 +761,16 @@ private static string ParseQuotedScalar(string text, int start, int lineNumber,
744761
case 'P': builder.Append('\u2029'); break;
745762
case 'x': builder.Append((char)ParseHex(text, i + 1, 2, lineNumber)); i += 2; break;
746763
case 'u': builder.Append((char)ParseHex(text, i + 1, 4, lineNumber)); i += 4; break;
747-
case 'U': builder.Append(char.ConvertFromUtf32(ParseHex(text, i + 1, 8, lineNumber))); i += 8; break;
764+
case 'U':
765+
int scalar = ParseHex(text, i + 1, 8, lineNumber);
766+
if (scalar is < 0 or > 0x10FFFF or (>= 0xD800 and <= 0xDFFF))
767+
{
768+
throw new FormatException($"Line {lineNumber}: '\\U{text.Substring(i + 1, 8)}' is not a valid Unicode scalar value.");
769+
}
770+
771+
builder.Append(char.ConvertFromUtf32(scalar));
772+
i += 8;
773+
break;
748774
default:
749775
throw new FormatException($"Line {lineNumber}: unsupported escape sequence '\\{e}' in double-quoted scalar.");
750776
}

0 commit comments

Comments
 (0)