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

Connected

道练习

Stop your tool from escaping its roots

The MCP SDK does not stop a tool from touching files outside the directories a user granted — that's on you. You'll write is_path_allowed(), which checks a requested path against the client's roots before any file is accessed.

FastMCP and Context are imported and the server mcp is created. check_access(path) runs your function through a real MCP client–server session: the connected client grants one directory (/tmp/mcp_allowed_root, holding video.mp4), and mcp_outside.mp4 sits outside it. root_to_path() converts a root to a Path.

说明

100 XP
  • Call ctx.session.list_roots() to get the directories the server may access.
  • Return True when the requested path is inside one of the roots.