始める無料で始める

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

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

@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)
コードを編集して実行