Aan de slagBegin 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.

Deze oefening maakt deel uit van de cursus

Model Context Protocol: Advanced Topics

Bekijk cursus

Oefeninstructies

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

Interactieve oefening met praktijkervaring

Probeer deze oefening door deze voorbeeldcode aan te vullen.

@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)
Code bewerken en uitvoeren