MCP · Lesson 22 of 120
Safe File Tools
Stay inside a folder.
A tool that reads files is useful, and risky. A model might ask for dot dot slash secrets, and escape the folder you meant to share. Safe file tools resolve every path, and check it stays inside.

- Useful and risky
- ../ escapes
- Check every path
A guarded file reader
Docs is the only folder we share. Read doc resolves the full path, then checks it's still inside docs. We ask for a real page, and for a path that tries to escape. Run it. The page is read. The escape is refused.
safe_files.pypython
from pathlib import Path
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from tester import call
DOCS = Path("data/rag/northwind").resolve()
mcp = MCPServer("docs")
@mcp.tool()
def read_doc(name: str) -> str:
"""Read one Northwind help page, like shipping.md."""
path = (DOCS / name).resolve()
if not path.is_relative_to(DOCS) or not path.is_file():
raise ToolError(f"No help page called {name}")
return path.read_text()[:60]
for name in ["shipping.md", "../../../secrets.txt"]:
print(call(mcp, "read_doc", {"name": name}).content[0].text)Output
# Shipping and delivery ## UK delivery Standard delivery in Error executing tool read_doc: No help page called ../../../secrets.txt
Also uses tester.py
import asyncio
from mcp import Client
def call(server, tool, args=None, **options):
async def go():
async with Client(server, **options) as client:
return await client.call_tool(tool, args or {})
return asyncio.run(go())
def tools(server):
async def go():
async with Client(server) as client:
return (await client.list_tools()).tools
return asyncio.run(go())File tool rules
Share one folder, never the whole disk. Resolve paths, and check they stay inside. Limit file sizes. And think hard before adding a tool that writes or deletes files.
| key | value |
|---|---|
| Share | one folder |
| Resolve | then check |
| Limit | file size |
| Writes | think twice |
Summary
Resolve every path, and refuse anything outside the shared folder. Next, tool annotations.
Key takeaways- resolve()
- is_relative_to
- Refuse escapes
Next up: Tool Annotations — read-only or destructive