Acceder al objeto de contexto
Acceda al contexto de la solicitud desde una herramienta.
Acceder al objeto de contexto es una lección gratuita de MCP Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de MCP Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de MCP Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Meet the Context Object
The Context object is your tool's gateway to the request: it carries shared state plus helpers for logging and progress.
Ask for It by Type
Add a parameter type-hinted as Context and FastMCP injects it automatically. Clients never see this argument.
from mcp.server.fastmcp import Context
@mcp.tool()
async def greet(name: str, ctx: Context) -> str:
return "hi " + nameReach Your Shared State
Drill into ctx.request_context.lifespan_context to get the exact object your lifespan yielded at startup.
app = ctx.request_context.lifespan_context
rows = await app.db.query("...")Use the Live Connection
Now your tool runs work against the shared pool instead of opening a brand new connection on every call.
Log Through the Context
Call ctx.info to send a log line to the client, which is far more useful than a hidden print on the server.
await ctx.info("loading user " + str(user_id))Report Progress Too
For slow work, ctx.report_progress streams percent-done updates so the host can show the user a moving bar.
await ctx.report_progress(progress=3, total=10)It's Injected, Not Passed
The model never fills in ctx. FastMCP recognizes the type hint and supplies it, so it stays out of your tool schema.
Async Tools Love Context
Most context helpers are awaitable, so define context-using tools as async functions to call them cleanly.
Name It Anything
The parameter name is up to you; the type hint is what matters. People often just call it ctx by convention.
One Context per Request
Each tool call gets its own request context, but they all point at the same long-lived lifespan state underneath.
Read Request Metadata
The context also exposes request metadata, so a tool can inspect details about the specific call it is handling.
Quick Check
How do you get the Context object inside a FastMCP tool?
Recap: The Context Object
You reach shared state via ctx.request_context.lifespan_context and use ctx for logging and progress. Next: shutting down cleanly. 🔌
Preguntas frecuentes
¿La lección «Acceder al objeto de contexto» es gratis?
Sí — el texto completo de «Acceder al objeto de contexto» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de MCP Academy, actualiza a CoddyKit PRO. El curso de MCP Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Acceder al objeto de contexto»?
Acceda al contexto de la solicitud desde una herramienta. Practicas MCP Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar MCP Academy?
No se requiere experiencia previa. MCP Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Acceder al objeto de contexto»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de MCP Academy?
Sí. Cada lección de MCP Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- El hook de inicio del ciclo de vida
- Compartir estado mediante el contexto de la aplicación
- Acceder al objeto de contexto
- Cierre limpio y liberación de recursos