访问上下文对象
在工具内部访问请求上下文。
访问上下文对象 是 CoddyKit 上的免费 MCP Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MCP Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MCP Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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. 🔌
常见问题解答
「访问上下文对象」课时是免费的吗?
是的 — 「访问上下文对象」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MCP Academy 课程的其余内容,请升级到 CoddyKit PRO。 MCP Academy 课程共包含 4 节课。
「访问上下文对象」这节课中我会学到什么?
在工具内部访问请求上下文。 你通过在浏览器中直接运行的动手代码来练习 MCP Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 MCP Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 MCP Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「访问上下文对象」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 MCP Academy 课中编写并运行代码吗?
能。每节 MCP Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 生命周期启动钩子
- 通过应用上下文共享状态
- 访问上下文对象
- 干净关闭与资源释放