Skip to content

Commit 82f0943

Browse files
PederHPclaude
andcommitted
Enforce skill limits while reading a directory; match Core's URI equivalence
CreateFromDirectory now applies the 512-file and 16 MiB limits while walking the directory, using each file's reported length, so an oversized or overly broad directory fails naming the limit before anything is read. The manifest built from the bytes actually read is still validated against the same limits afterwards. WithSkills detects files shared between skills with the same equivalence the server's resource collection uses for concrete URIs, System.Uri equality, under which scheme and authority are case-insensitive. Two skills whose file URIs differ only in authority case previously passed the ordinal check and were then merged silently by the collection, so reads of the second returned the first's bytes. Same content still registers once; different content is an error that names both URIs. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01P6omaTvQiryHtzFHRqUE3b
1 parent 8593f0d commit 82f0943

4 files changed

Lines changed: 97 additions & 8 deletions

File tree

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

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,8 @@ private static List<McpServerSkillFile> ReadDirectory(string directoryPath)
425425
}
426426

427427
var files = new List<McpServerSkillFile>();
428-
CollectFiles(fullDirectory, fullDirectory, files);
428+
long totalSize = 0;
429+
CollectFiles(fullDirectory, fullDirectory, files, ref totalSize);
429430
return files;
430431
}
431432

@@ -434,7 +435,7 @@ private static List<McpServerSkillFile> ReadDirectory(string directoryPath)
434435
/// outside the skill directory, and a file reached through one would be published under a URI that looks like
435436
/// it lives inside the skill. Rather than try to decide which link targets are acceptable, links are rejected.
436437
/// </summary>
437-
private static void CollectFiles(string root, string directory, List<McpServerSkillFile> files)
438+
private static void CollectFiles(string root, string directory, List<McpServerSkillFile> files, ref long totalSize)
438439
{
439440
foreach (string entry in Directory.EnumerateFileSystemEntries(directory))
440441
{
@@ -450,10 +451,30 @@ private static void CollectFiles(string root, string directory, List<McpServerSk
450451

451452
if ((attributes & FileAttributes.Directory) != 0)
452453
{
453-
CollectFiles(root, entry, files);
454+
CollectFiles(root, entry, files, ref totalSize);
454455
continue;
455456
}
456457

458+
// Apply the specification's per-skill limits before reading, so an oversized or overly broad directory
459+
// fails with the limit named rather than after allocating everything under it. The manifest built from
460+
// the bytes actually read is validated against the same limits afterwards.
461+
if (files.Count >= SkillsProtocol.MaxResourcesPerSkill)
462+
{
463+
throw new ArgumentException(
464+
$"The skill directory '{root}' contains more than {SkillsProtocol.MaxResourcesPerSkill} files, the limit per skill.",
465+
"directoryPath");
466+
}
467+
468+
long length = new FileInfo(entry).Length;
469+
if (length > SkillsProtocol.MaxTotalSizeBytes - totalSize)
470+
{
471+
throw new ArgumentException(
472+
$"The files under '{root}' total more than {SkillsProtocol.MaxTotalSizeBytes} bytes, the limit per skill.",
473+
"directoryPath");
474+
}
475+
476+
totalSize += length;
477+
457478
string relativePath = entry.Substring(root.Length).Replace(Path.DirectorySeparatorChar, '/');
458479
if (Path.AltDirectorySeparatorChar != Path.DirectorySeparatorChar)
459480
{

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

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ public static IMcpServerBuilder WithSkills(
4949
#endif
5050

5151
var entries = new List<Skill>();
52-
var registeredFiles = new Dictionary<string, string>(StringComparer.Ordinal);
52+
53+
// The server's resource collection keys concrete resources by System.Uri equality, under which scheme and
54+
// authority are case-insensitive, and it registers silently. Detect shared files under those same
55+
// semantics, so two URIs the collection would merge are caught here rather than served as one another.
56+
var registeredFiles = new Dictionary<Uri, (string Uri, string Digest)>();
5357
foreach (var skill in skills)
5458
{
5559
if (skill is null)
@@ -63,19 +67,22 @@ public static IMcpServerBuilder WithSkills(
6367
for (int i = 0; i < manifest.Count; i++)
6468
{
6569
var entry = manifest[i];
66-
if (registeredFiles.TryGetValue(entry.Uri, out string? existingDigest))
70+
var key = new Uri(entry.Uri, UriKind.Absolute);
71+
if (registeredFiles.TryGetValue(key, out var existing))
6772
{
68-
if (!string.Equals(existingDigest, entry.Digest, StringComparison.Ordinal))
73+
if (!string.Equals(existing.Digest, entry.Digest, StringComparison.Ordinal))
6974
{
7075
throw new ArgumentException(
71-
$"The file '{entry.Uri}' is listed by more than one skill with different content.",
76+
string.Equals(existing.Uri, entry.Uri, StringComparison.Ordinal)
77+
? $"The file '{entry.Uri}' is listed by more than one skill with different content."
78+
: $"The file '{entry.Uri}' is equivalent to '{existing.Uri}', which another skill lists with different content. Resource URIs are compared case-insensitively in their scheme and authority.",
7279
nameof(skills));
7380
}
7481

7582
continue;
7683
}
7784

78-
registeredFiles.Add(entry.Uri, entry.Digest);
85+
registeredFiles.Add(key, (entry.Uri, entry.Digest));
7986
builder.Services.AddSingleton(skill.Resources[i]);
8087
}
8188
}

‎tests/ModelContextProtocol.Tests/Server/McpServerSkillTests.cs‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,51 @@ public void CreateFromDirectory_RejectsDirectorySymbolicLinks()
424424
}
425425
#endif
426426

427+
[Fact]
428+
public void CreateFromDirectory_RejectsTooManyFilesBeforeReadingThem()
429+
{
430+
string directory = Path.Combine(Path.GetTempPath(), "mcp-skill-many-" + Guid.NewGuid().ToString("N"));
431+
try
432+
{
433+
Directory.CreateDirectory(directory);
434+
File.WriteAllText(Path.Combine(directory, "SKILL.md"), SkillMarkdown);
435+
for (int i = 0; i < SkillsProtocol.MaxResourcesPerSkill; i++)
436+
{
437+
File.WriteAllText(Path.Combine(directory, $"f{i:D4}.txt"), "x");
438+
}
439+
440+
var exception = Assert.Throws<ArgumentException>(() => McpServerSkill.CreateFromDirectory(SkillUri, directory));
441+
Assert.Contains(SkillsProtocol.MaxResourcesPerSkill.ToString(), exception.Message);
442+
}
443+
finally
444+
{
445+
Directory.Delete(directory, recursive: true);
446+
}
447+
}
448+
449+
[Fact]
450+
public void CreateFromDirectory_RejectsOversizedContentBeforeReadingIt()
451+
{
452+
string directory = Path.Combine(Path.GetTempPath(), "mcp-skill-big-" + Guid.NewGuid().ToString("N"));
453+
try
454+
{
455+
Directory.CreateDirectory(directory);
456+
File.WriteAllText(Path.Combine(directory, "SKILL.md"), SkillMarkdown);
457+
using (var big = new FileStream(Path.Combine(directory, "big.bin"), FileMode.CreateNew))
458+
{
459+
// A sparse file: the size check must trip without the bytes ever being read.
460+
big.SetLength(SkillsProtocol.MaxTotalSizeBytes + 1);
461+
}
462+
463+
var exception = Assert.Throws<ArgumentException>(() => McpServerSkill.CreateFromDirectory(SkillUri, directory));
464+
Assert.Contains(SkillsProtocol.MaxTotalSizeBytes.ToString(), exception.Message);
465+
}
466+
finally
467+
{
468+
Directory.Delete(directory, recursive: true);
469+
}
470+
}
471+
427472
[Fact]
428473
public void CreateFromDirectory_WithMissingDirectory_Throws()
429474
{

‎tests/ModelContextProtocol.Tests/Server/McpServerSkillsFromDirectoryTests.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,22 @@ public async Task ServedFiles_VerifyAgainstTheirManifest()
6868
}
6969
}
7070

71+
[Fact]
72+
public void WithSkills_DetectsFilesThatCollideUnderUriEquivalence()
73+
{
74+
// The resource collection compares URIs case-insensitively in scheme and authority, so these two skills
75+
// would silently share one registered resource. With different content that must be an error.
76+
var upper = McpServerSkill.Create("skill://Acme/refunds/SKILL.md", [McpServerSkillFile.FromText("SKILL.md", "---\nname: refunds\ndescription: upper\n---\n")]);
77+
var lower = McpServerSkill.Create("skill://acme/refunds/SKILL.md", [McpServerSkillFile.FromText("SKILL.md", "---\nname: refunds\ndescription: lower\n---\n")]);
78+
79+
var exception = Assert.Throws<ArgumentException>(() => new ServiceCollection().AddMcpServer().WithSkills([upper, lower]));
80+
Assert.Contains("equivalent", exception.Message);
81+
82+
// Identical content is the nested-skill case and is allowed: the file is registered once.
83+
var same = McpServerSkill.Create("skill://ACME/refunds/SKILL.md", [McpServerSkillFile.FromText("SKILL.md", "---\nname: refunds\ndescription: upper\n---\n")]);
84+
new ServiceCollection().AddMcpServer().WithSkills([upper, same]);
85+
}
86+
7187
[Fact]
7288
public void WithSkillsFromDirectory_RejectsDirectoriesWithoutSkills()
7389
{

0 commit comments

Comments
 (0)