مرور عملی roots (Roots walkthrough)
هدف یادگیری: پیادهسازی serverای که قبل از هر عمل filesystem روی roots مشورت میکند.
مثال عملی — Python (server که فقط فایلهای داخل roots را list میکند)
from pathlib import Path
from mcp.server.fastmcp import FastMCP, Context
from mcp.server.session import ServerSession
mcp = FastMCP("RootedFS")
@mcp.tool()
async def list_files(ctx: Context[ServerSession, None]) -> list[str]:
"""List files inside the client-advertised roots."""
roots_resp = await ctx.session.list_roots()
out = []
for r in roots_resp.roots:
# spec requires file:// URI; strip the scheme
base = Path(r.uri.replace("file://", ""))
for p in base.rglob("*"):
if p.is_file():
out.append(str(p))
return out
اشتباهات رایج
- فرار با symlink. path را resolve کنید و دوباره چک کنید که path resolve شده زیر root است.
- hard-code کردن root. همیشه دوباره fetch کنید.