Skills._handle_read_directory reports handler ValidationError as INVALID_PARAMS and skips outbound re-validation
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 76/100
Línea de trabajo
Lee src/mcp/server/skills.py alrededor de las líneas 132-142 y compara _handle_read_directory con _handle_list (112-116) y _handle_get (123-127), que ya envuelven la llamada al handler junto con model_validate(result.model_dump()) en try ... except ValidationError. Replica ese patrón para que ambas rutas de fallo lancen MCPError(code=INTERNAL_ERROR, message="Handler returned an invalid result"). Reproduce con el script de dos casos del issue y luego ejecuta las pruebas existentes del servidor de skills para confirmar que los demás handlers siguen comportándose igual. Ten en cuenta que quien reportó tiene un arreglo local listo y pidió que se le asigne, así que consulta con los mantenedores antes de empezar.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Initial Checks
- I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
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:
await self._read_directory(ctx, params)runs outsidetry ... except ValidationError, so aValidationErrorraised while buildingReadDirectoryResultescapes to the framework's default handler and returns-32602(INVALID_PARAMS) instead of-32603(INTERNAL_ERROR).- It never calls
ReadDirectoryResult.model_validate(result.model_dump()), so a handler that mutates a field after construction (e.g. setting an invalidcache_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 @ 77001c96)
AI disclosure: AI assistance was used to help investigate and draft this issue; the reproduction and observed output were verified locally.
- Lenguaje dominante
- Python
- Estrellas
- 25k
- Forks
- 4.2k
- Merge medio
- 10 min
- PR fusionados (30 d)
- 1
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de modelcontextprotocol/python-sdk
-
v2
Dificultad 1/5 Menos de una hora Aptitud para principiantes 86/100
modelcontextprotocol/python-sdk#3978 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
Client serves cached tools after its context exits with an exceptionPosiblemente ocupada @jonxsong la tomó hace 1 día. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
modelcontextprotocol/python-sdk#3968 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
modelcontextprotocol/python-sdk#3957 ·
Los mantenedores suelen responder en 1 día
-
v2
Dificultad 1/5 Menos de una hora Aptitud para principiantes 91/100
modelcontextprotocol/python-sdk#3934 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
bug v1
Dificultad 2/5 1-3 horas Aptitud para principiantes 79/100
modelcontextprotocol/python-sdk#3929 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de modelcontextprotocol/python-sdk
Issues similares
-
soup prune-prompt exits 1 after writing its output on a file over 100,000 rows, and reports a capped row count otherwisePosiblemente ocupada @abdulwaarith0 la tomó hoy. Abiertoneeds-triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
MakazhanAlpamys/Soup#3690 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
-
bug data-types native-format
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
ClickHouse/clickhouse-connect#1320 ·
Los mantenedores suelen responder en 1 día
-
Public benchmark import end-to-end test fails when the test stack's worker runs the parity jobAbiertoaccepted
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
future-agi/future-agi#6392 ·
Los mantenedores suelen responder en 1 día