Parameterized Context loses request state in resource and prompt handlers
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Accessibilité débutants
- 55/100
- Type d'issue
- Bug
- Clarté
- Clairement spécifiée
- Activité
- Calme
- Stack technique
- python
- Domaine
- backend-api-design
Piste de recherche
Commencez par ResourceTemplate.from_function et Prompt.from_function, puis comparez leur chemin de validation avec FuncMetadata.call_fn_with_arg_validation utilisé par tools. Reproduisez les appels de resource et de prompt de l’exemple minimal et vérifiez si le Context injecté conserve son identité et l’état de la requête. C’est terminé lorsque les arguments du client restent validés, tandis que le Context créé par le serveur atteint les deux handlers sans modification.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
Description
A resource-template or prompt handler annotated with a parameterized Context[LifespanContextT] receives a different Context object from the one the server injected. The reconstructed object has none of the private request state, so accessing ctx.request_context, ctx.session, ctx.request_id, or lifespan state fails with:
ValueError: Context is not available outside of a request
The equivalent tool handler works, and handlers annotated with unparameterized Context happen to work. This makes the documented typed lifespan-context pattern unusable specifically in dynamic resources and prompts.
Minimal reproduction
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
import anyio
from mcp.client import Client
from mcp.server.mcpserver import Context, MCPServer
@asynccontextmanager
async def lifespan(_: MCPServer[str]) -> AsyncIterator[str]:
yield "live-state"
async def main() -> None:
server = MCPServer("probe", lifespan=lifespan)
@server.resource("probe://{name}")
async def resource(name: str, ctx: Context[str]) -> str:
return f"{name}:{ctx.request_context.lifespan_context}"
@server.prompt("probe")
async def prompt(name: str, ctx: Context[str]) -> str:
return f"{name}:{ctx.request_context.lifespan_context}"
async with Client(server) as client:
await client.read_resource("probe://value")
await client.get_prompt("probe", {"name": "value"})
anyio.run(main)
Both calls fail. Each should return content containing value:live-state.
Root cause
ResourceTemplate.from_function and Prompt.from_function correctly omit the detected context parameter from their public argument schemas, but then wrap the original handler with pydantic.validate_call. At invocation time they inject the live Context into the wrapped handler, so Pydantic validates it again.
For a generic annotation, Pydantic converts the unparameterized runtime instance into Context[str, Any]. That creates a new model instance and does not carry over Context's private _request_context, _mcp_server, and related attributes:
server-created Context
|
v
validate_call parameter: Context[str]
|
v
new Context[str, Any] instance
|
v
private request state absent
A direct identity probe on current main shows:
Context -> same object, request state present
Context[str] -> new object, request state absent
Tools avoid this because FuncMetadata.call_fn_with_arg_validation validates only client-supplied arguments and passes injected values directly to the raw handler.
Impact
This affects resource templates and prompts that use typed lifespan context, including otherwise valid code following the SDK's generic Context[LifespanContextT] typing. It can also hide in tests that only assert that ctx is non-null rather than reading request-scoped state.
A compatible fix should preserve the existing validation/coercion of client-supplied resource or prompt arguments while passing the server-created context object directly, with its identity and private state intact.
Environment
- MCP Python SDK: 2.0.0 and current
mainata4f4ccd091138771535e17191123f20b30fda68e - Python: 3.12.13
- Pydantic: 2.12.5
AI assistance was used to investigate and draft this report.
- Langage dominant
- Python
- Étoiles
- 24.3k
- Forks
- 4k
- Merge moyen
- 1 j 11 h
- PR mergées (30 j)
- 30
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de modelcontextprotocol/python-sdk
-
Difficulté 2/5 1-3 heures Accessibilité débutants 75/100
modelcontextprotocol/python-sdk#3566 ·
-
Streamable HTTP client logs a WARNING for valid 202 Accepted on session termination (DELETE) Ouvertev1 v2
Difficulté 2/5 1-3 heures Accessibilité débutants 85/100
modelcontextprotocol/python-sdk#3546 · 5 commentaires ·
-
v1 v2
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
modelcontextprotocol/python-sdk#3545 · 1 commentaire ·
-
v1 v2
Difficulté 1/5 Moins d'une heure Accessibilité débutants 91/100
modelcontextprotocol/python-sdk#3508 · 2 commentaires ·
-
Difficulté 2/5 1-3 heures Accessibilité débutants 64/100
modelcontextprotocol/python-sdk#3504 ·
Toutes les issues de modelcontextprotocol/python-sdk
Issues similaires
-
enhancement
Difficulté 2/5 1-3 heures Accessibilité débutants 70/100
canonical/paas-charm#368 · 1 commentaire ·
-
Difficulté 2/5 1-3 heures Accessibilité débutants 75/100
-
tech debt
Difficulté 2/5 1-3 heures Accessibilité débutants 75/100
-
addition to tracking list Ouverte
Difficulté 1/5 Moins d'une heure Accessibilité débutants 90/100
StevenBlack/hosts#3256 ·
-
Difficulté 1/5 Moins d'une heure Accessibilité débutants 90/100
qualcomm/qai-appbuilder#275 ·