Read a file only if it's inside the roots
You built is_path_allowed() in the last exercise — now put it to work. A read_file tool should never hand back a file the user didn't grant access to, so it has to check the path against the client's roots before reading anything.
FastMCP, Context, and Path are imported and the server mcp is created. Your is_path_allowed() is provided. run_tool(path) calls your tool through a real MCP client–server session: the connected client grants /tmp/mcp_allowed_root (holding notes.txt), and mcp_secret.txt sits outside it.
本练习是课程的一部分
Model Context Protocol: Advanced Topics
练习说明
- Guard the read: call
is_path_allowed()with the requestedPathandctx, so the tool refuses when it returnsFalse. - When the path is allowed, read the file with
Path.read_text()and return its contents.
交互式实操练习
通过完成这段示例代码来试试这个练习。
@mcp.tool()
async def read_file(path: str, ctx: Context) -> str:
requested = Path(path)
# Refuse paths outside the roots
if not await is_path_allowed(____, ctx):
return "Access denied: that path is outside the allowed roots."
# Read and return the file
return requested.____()
# Try a file inside the allowed root, and one outside it
inside = run_tool("/tmp/mcp_allowed_root/notes.txt")
outside = run_tool("/tmp/mcp_secret.txt")
print(inside)
print(outside)