0Pricing
MCP Academy · Урок

Запрос корневых каталогов клиента

Запросите список разрешённых рабочих каталогов.

«Запрос корневых каталогов клиента» — бесплатный урок MCP Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения MCP Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс MCP Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Now Let's Ask for Them

Knowing roots exist is step one. Step two is actually asking the client for its current list so your server can decide where to read or write. 📨

The Server Initiates

Here the direction flips: your server sends the request and the client answers. The method it calls is roots/list, asking for everything the client currently exposes.

{ "method": "roots/list" }

Reach Roots via the Context

In the Python SDK you do not craft raw JSON. You use the request context object handed to your tool, which wraps the live session to the client.

async def my_tool(ctx: Context):
    ...

One Friendly Call

From that context you call list_roots() and await it. The SDK sends roots/list for you and returns the client's answer as a typed result.

result = await ctx.session.list_roots()

What Comes Back

The reply holds a roots list. Each item has a uri and an optional name, exactly the small shape you saw before, ready for you to loop over.

for root in result.roots:
    print(root.uri, root.name)

It May Be Empty

A valid answer can be an empty list. That means the client offers no roots right now, so plan a sensible fallback rather than assuming a folder exists.

Check the Capability First

Calling list_roots only makes sense if the client supports roots. A polite server checks the declared capability before asking, avoiding errors on hosts that lack it.

Ask at the Right Time

Fetch roots when you need them, like at the start of a file tool. Asking lazily keeps you current if the user has since opened a different folder.

Turn a Root into a Path

A root's uri is a string like file:///home/ada. To use it, parse the file:// URI into a real filesystem path before opening anything inside it.

from urllib.parse import urlparse
path = urlparse(root.uri).path

Listen for Changes

If the client supports it, it can send a notification when roots change. Catching that lets you re-fetch the list instead of working from a stale view.

notifications/roots/list_changed

Handle Failures Gently

The request can still fail or time out. Wrap the call so a missing answer leaves your tool with a clear message instead of a crash. 🛟

Quick Check

Pick the right way to get the client's roots in the SDK.

Recap: Asking for Roots

You await list_roots() on the session, loop over the returned roots, parse each file:// uri, and handle empty or failed replies. Re-ask when roots change. ✅

Часто задаваемые вопросы

Урок «Запрос корневых каталогов клиента» бесплатный?

Да — полный текст урока «Запрос корневых каталогов клиента» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс MCP Academy, подпишись на CoddyKit PRO. Курс MCP Academy содержит 4 уроков всего.

Чему я научусь в уроке «Запрос корневых каталогов клиента»?

Запросите список разрешённых рабочих каталогов. Ты практикуешь MCP Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать MCP Academy?

Предыдущий опыт не требуется. MCP Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Запрос корневых каталогов клиента»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке MCP Academy?

Да. Каждый урок MCP Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Что корни сообщают серверу
  2. Запрос корневых каталогов клиента
  3. Согласование возможностей
  4. Соблюдение границ клиента
← Назад к MCP Academy