1. Learn
  2. /
  3. 课程
  4. /
  5. Model Context Protocol: Advanced Topics

Connected

道练习

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.

说明

100 XP
  • Guard the read: call is_path_allowed() with the requested Path and ctx, so the tool refuses when it returns False.
  • When the path is allowed, read the file with Path.read_text() and return its contents.