π The fast, Pythonic way to build MCP servers and clients.
Parse skills frontmatter with yaml.safe_load, falling back to the line parser (#4701)
Vishnu J58d903c84b0a
diff --git a/fastmcp_slim/fastmcp/server/providers/skills/_common.py b/fastmcp_slim/fastmcp/server/providers/skills/_common.pyindex 340d289e5..916cbf533 100644--- a/fastmcp_slim/fastmcp/server/providers/skills/_common.py+++ b/fastmcp_slim/fastmcp/server/providers/skills/_common.py@@ -8,6 +8,8 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any+import yaml+@dataclassclass SkillFileInfo:@@ -30,14 +32,61 @@ class SkillInfo:frontmatter: dict[str, Any] = field(default_factory=dict)+def _parse_frontmatter_line_based(frontmatter_text: str) -> dict[str, Any]:+ """Legacy line-based frontmatter parser (key: value only).++ Used as a fallback when full YAML parsing fails so plain scalar keys+ (including values that contain `: `) are not discarded entirely.+ Multiline YAML block scalars (`|` / `>`) are not supported here β+ those require a successful `yaml.safe_load`.+ """+ frontmatter: dict[str, Any] = {}+ for line in frontmatter_text.strip().split("\n"):+ if ":" not in line:+ continue+ key, _, value = line.partition(":")+ key = key.strip()+ value = value.strip()++ # Handle quoted strings+ if (value.startswith('"') and value.endswith('"')) or (+ value.startswith("'") and value.endswith("'")+ ):+ value = value[1:-1]++ # Handle lists [a, b, c]+ if value.startswith("[") and value.endswith("]"):+ items = value[1:-1].split(",")+ value = [item.strip().strip("\"'") for item in items if item.strip()]++ frontmatter[key] = value+ return frontmatter++def parse_frontmatter(content: str) -> tuple[dict[str, Any], str]:"""Parse YAML frontmatter from markdown content.+ Uses `yaml.BaseLoader` so multiline block scalars (`|` / `>`) work while+ every scalar value is returned as a plain string. `SkillInfo.frontmatter`+ is a public mapping; letting a full loader (e.g. `safe_load`) apply+ implicit scalar typing would silently turn `version: 1.10` into the float+ `1.1`, `enabled: yes` into `True`, or a date-like value into+ `datetime.date` for every skill author, which is a backwards-incompatible+ surprise rather than an internal detail. `BaseLoader` has no such+ constructors, so values round-trip as written. If YAML parsing fails+ (invalid YAML, recursion limit, etc.), falls back to a line-based+ key:value parser so plain frontmatter is not discarded.+Args:content: Markdown content potentially starting with ---Returns:- Tuple of (frontmatter dict, remaining content)+ Tuple of (frontmatter dict, remaining content). If no frontmatter+ block is found at all (no opening/closing `---` delimiters),+ returns `({}, content)` unchanged. If a delimited block is found+ but is empty or does not parse to a YAML mapping (and the line-based+ fallback also yields nothing), returns `({}, remaining)` with the+ delimited block stripped."""content = content.removeprefix("\ufeff")@@ -52,28 +101,16 @@ def parse_frontmatter(content: str) -> tuple[dict[str, Any], str]:frontmatter_text = content[3 : 3 + end_match.start()]remaining = content[3 + end_match.end() :]- # Parse YAML (simple key: value parsing, no complex types)- frontmatter: dict[str, Any] = {}- for line in frontmatter_text.strip().split("\n"):- if ":" in line:- key, _, value = line.partition(":")- key = key.strip()- value = value.strip()-- # Handle quoted strings- if (value.startswith('"') and value.endswith('"')) or (- value.startswith("'") and value.endswith("'")- ):- value = value[1:-1]-- # Handle lists [a, b, c]- if value.startswith("[") and value.endswith("]"):- items = value[1:-1].split(",")- value = [item.strip().strip("\"'") for item in items if item.strip()]+ try:+ parsed = yaml.load(frontmatter_text, Loader=yaml.BaseLoader)+ except (yaml.YAMLError, RecursionError):+ # Prefer partial recovery over discarding every key (issue #4416 review).+ return _parse_frontmatter_line_based(frontmatter_text), remaining- frontmatter[key] = value+ if not isinstance(parsed, dict):+ return {}, remaining- return frontmatter, remaining+ return parsed, remainingdef compute_file_hash(path: Path) -> str:diff --git a/tests/server/providers/test_skills_provider.py b/tests/server/providers/test_skills_provider.pyindex cfc03e7d2..dadeea2bb 100644--- a/tests/server/providers/test_skills_provider.py+++ b/tests/server/providers/test_skills_provider.py@@ -60,6 +60,150 @@ Contentassert frontmatter["description"] == "A skill with quotes"assert frontmatter["version"] == "2.0.0"+ def test_frontmatter_multiline_literal_block(self):+ content = """---+description: |+ This is a multiline+ description for the skill+---++# Skill Content+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["description"] == (+ "This is a multiline\ndescription for the skill"+ )+ assert body.strip().startswith("# Skill Content")++ def test_frontmatter_multiline_folded_block(self):+ content = """---+description: >+ This is a folded+ multiline description+---++# Skill Content+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["description"] == "This is a folded multiline description"+ assert body.strip().startswith("# Skill Content")++ def test_frontmatter_malformed_falls_back_to_line_parser(self):+ # Invalid YAML list β safe_load fails; line parser keeps plain keys.+ content = """---+description: [unclosed+name: still-parsed+---++Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["name"] == "still-parsed"+ assert frontmatter["description"] == "[unclosed"+ assert body == "Body\n"++ def test_frontmatter_colon_in_value_falls_back_preserves_keys(self):+ # Real skill files sometimes contain unquoted values with ": " that+ # PyYAML rejects; must not drop description (FastMCP #4416 review).+ content = """---+name: oss-daily+description: Use when Vishnu wants: daily OSS drafting+---++# Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["name"] == "oss-daily"+ assert "daily OSS drafting" in frontmatter["description"]+ assert body.strip().startswith("# Body")++ def test_frontmatter_non_dict_returns_empty(self):+ content = """---+- item1+- item2+---++Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter == {}+ assert body == "Body\n"++ def test_frontmatter_scalars_are_preserved_as_strings(self):+ """`SkillInfo.frontmatter` is public; it must not silently retype values.++ `yaml.BaseLoader` parses block scalars (unlike the old line parser)+ but applies no implicit scalar resolution, so every value comes back+ exactly as written instead of being coerced to float/bool/date the+ way a full loader (e.g. `safe_load`) would.++ The `description: null` case looks surprising but is intentional:+ under `BaseLoader`, YAML's null token resolves to the *string*+ `"null"`, not Python `None`. This matches the pre-existing line-based+ parser (which did `value.strip()` on the raw text and also produced+ `"null"`), so this restores original behavior rather than inventing+ a new one. Do not "fix" this back to `None`.+ """+ content = """---+version: 1.10+enabled: yes+released: 2024-01-01+description: null+---++Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["version"] == "1.10"+ assert frontmatter["enabled"] == "yes"+ assert frontmatter["released"] == "2024-01-01"+ assert frontmatter["description"] == "null"+ for value in frontmatter.values():+ assert isinstance(value, str)++ def test_frontmatter_description_bool_recovers_original_text(self):+ content = """---+description: true+---++Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["description"] == "true"+ assert isinstance(frontmatter["description"], str)++ def test_frontmatter_description_yes_not_coerced_to_true(self):+ # FastMCP #4416 regression: `yes` bare word previously coerced to True.+ content = """---+description: yes+---++Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["description"] == "yes"++ def test_frontmatter_description_no_not_coerced_to_false(self):+ content = """---+description: no+---++Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["description"] == "no"++ def test_frontmatter_description_numeric_scalar_preserves_original_text(self):+ # YAML resolves `1.10` to float 1.1, dropping the trailing zero the author wrote.+ content = """---+description: 1.10+---++Body+"""+ frontmatter, body = parse_frontmatter(content)+ assert frontmatter["description"] == "1.10"+class TestSkillProvider:"""Tests for SkillProvider - single skill folder."""