EmpezarEmpieza gratis

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.

Este ejercicio forma parte del curso

Model Context Protocol: Advanced Topics

Ver curso

Instrucciones del ejercicio

  • 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.

ejercicio interactivo práctico

Prueba este ejercicio completando este código de ejemplo.

@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)
Editar y ejecutar código