Skip to content

Skills._handle_read_directory reports handler ValidationError as INVALID_PARAMS and skips outbound re-validation #3882

Open

Description

@0718lol

Initial Checks

Release line

2.x (current stable)

Description

In src/mcp/server/skills.py, Skills documents that a non-conformant handler result is a server fault reported as INTERNAL_ERROR, not the caller's INVALID_PARAMS.

_handle_list (lines 112-116) and _handle_get (lines 123-127) enforce this by wrapping the handler call and outbound re-validation (model_validate(result.model_dump())) in try ... except ValidationError.

_handle_read_directory (lines 132-142) omits both:

  1. await self._read_directory(ctx, params) runs outside try ... except ValidationError, so a ValidationError raised while building ReadDirectoryResult escapes to the framework's default handler and returns -32602 (INVALID_PARAMS) instead of -32603 (INTERNAL_ERROR).
  2. It never calls ReadDirectoryResult.model_validate(result.model_dump()), so a handler that mutates a field after construction (e.g. setting an invalid cache_scope) ships a non-conformant payload over the wire.

Example Code

import anyio
from mcp.client import Client
from mcp.server.mcpserver import MCPServer
from mcp.server.skills import Skills
from mcp.shared.exceptions import MCPError
from mcp.shared.skills import (
    ListSkillsResult,
    ReadDirectoryParams,
    ReadDirectoryRequest,
    ReadDirectoryResult,
)
from mcp_types import Resource
from mcp_types.jsonrpc import INTERNAL_ERROR, INVALID_PARAMS
from pydantic import BaseModel, ConfigDict


class _RawResult(BaseModel):
    model_config = ConfigDict(extra="allow")


async def list_skills(ctx, params):
    return ListSkillsResult(skills=[])


async def get_skill(ctx, params):
    raise MCPError(code=INVALID_PARAMS, message="unknown")


async def bad_construct(ctx, params):
    return ReadDirectoryResult(resources=[], cache_scope="everyone")  # type: ignore[arg-type]


async def bad_mutate(ctx, params):
    res = ReadDirectoryResult(resources=[Resource(uri="skill://pdf/a.txt", name="a.txt")])
    res.cache_scope = "invalid-scope"  # type: ignore[assignment]
    return res


async def main():
    s1 = MCPServer("s1", extensions=[Skills(list_skills=list_skills, get_skill=get_skill, read_directory=bad_construct)])
    async with Client(s1) as client:
        try:
            await client.session.send_request(ReadDirectoryRequest(params=ReadDirectoryParams(uri="skill://pdf")), _RawResult)
        except MCPError as exc:
            print(f"Case 1: code={exc.error.code} (expected {INTERNAL_ERROR}), message={exc.error.message!r}")

    s2 = MCPServer("s2", extensions=[Skills(list_skills=list_skills, get_skill=get_skill, read_directory=bad_mutate)])
    async with Client(s2) as client:
        raw = await client.session.send_request(ReadDirectoryRequest(params=ReadDirectoryParams(uri="skill://pdf")), _RawResult)
        print(f"Case 2: leaked invalid payload -> cacheScope={raw.model_extra.get('cacheScope')!r}")


anyio.run(main)

Observed output:

Case 1: code=-32602 (expected -32603), message='Invalid request parameters'
Case 2: leaked invalid payload -> cacheScope='invalid-scope'

Expected behavior: both cases should raise MCPError(code=INTERNAL_ERROR, message="Handler returned an invalid result"), matching _handle_list and _handle_get.

I have a minimal fix (wrapping await self._read_directory(ctx, params) and ReadDirectoryResult.model_validate(result.model_dump()) in try ... except ValidationError) and regression tests ready locally, and would be happy to submit a PR if assigned.

Python & MCP Python SDK

  • Python: 3.14.8
  • mcp: 2.3.1.dev20+77001c96 (main @ 77001c9)

AI disclosure: AI assistance was used to help investigate and draft this issue; the reproduction and observed output were verified locally.

Activity

  1. added
    bugSomething isn't working
    v2Affects the v2 line (2.x on main)
    on Nov 21, 2026
  2. Shanmukh-l33t commented on Nov 22, 2026

    @Shanmukh-l33t

    Root cause: _handle_read_directory calls await self._read_directory(ctx, params) outside the try ... except ValidationError guard that _handle_list and _handle_get use, and it never re-validates the outbound result with ReadDirectoryResult.model_validate(result.model_dump()). A ValidationError raised while the handler builds the result therefore reaches the framework's default handler and becomes -32602 (INVALID_PARAMS), and a handler that mutates a field after construction ships the non-conformant payload.

    Branch fix/3882-read-directory-error-mapping wraps the handler call and the outbound re-validation in the same ValidationError guard as the other two methods, leaving the existing directory-shape check unchanged. The change is 8 lines in src/mcp/server/skills.py plus two regression tests in tests/server/test_skills.py.

    RED at parent 77001c9 with the new tests: -32602 where -32603 is expected, and DID NOT RAISE MCPError for the mutated result, whose invalid cacheScope reached the client. GREEN after the fix: tests/server/test_skills.py 29 passed, and coverage limited to src/mcp/server/skills.py is 100.00 percent (75 statements, 6 branches, 0 missing, 0 partial, report exit 0). ruff check, the ruff format check, and pyright on the touched files pass.

    Compare: main...Shanmukh-l33t:fix/3882-read-directory-error-mapping

    The patch is ready on that branch if a maintainer assigns this issue.

    AI assistance disclosure: AI assistance was used to prepare the fix and this comment; I reviewed the diff and the test output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingv2Affects the v2 line (2.x on main)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions