0Pricing
MCP Academy · Урок

Чтение файла с диска

Превратите локальный файл в динамический ресурс MCP.

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

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

From Fixed to Live

Returning a hardcoded string is fine, but real servers expose actual files. You can read a file from disk and serve its contents live.

Read Inside the Handler

Your resource function simply opens the file and returns its text. Because it runs on each request, the client always gets the current content. 📂

A Basic File Resource

Open the file, read it, and return the string. The resource now reflects whatever is saved on disk at read time.

@mcp.resource("file:///notes.txt")
def notes():
    with open("notes.txt") as f:
        return f.read()

Use Pathlib Cleanly

The pathlib library reads small files in one line and handles paths safely across systems, which keeps your handler short and clear.

from pathlib import Path

@mcp.resource("file:///notes.txt")
def notes():
    return Path("notes.txt").read_text()

Handle Missing Files

A file can vanish or be renamed. Wrap the read so a missing file returns a clear error message instead of crashing the server.

try:
    return Path(p).read_text()
except FileNotFoundError:
    raise ValueError("File not found")

Mind the Encoding

Text files have an encoding. Read with utf-8 explicitly so accented and non-English characters survive the trip to the model.

Path("notes.txt").read_text(encoding="utf-8")

Watch the File Size

Returning a huge file floods the model with tokens and may hit limits. Keep served files small, or read only the part the model truly needs.

Never Trust the Path

If a path comes from input, an attacker could request files outside your folder. Always confine reads to a safe base directory you control.

Resolve Within a Base

Compute an absolute path and check it stays inside your allowed root. This blocks path traversal tricks like climbing up with dot-dot.

base = Path("data").resolve()
target = (base / name).resolve()
if base not in target.parents: raise ValueError("Denied")

Read-Only by Nature

Resources only read; they never write. Serving a file as a resource exposes its contents without ever letting the model modify the file.

Verify the Live Read

Change the file on disk, then read the URI again. Seeing the new text proves your server reads live rather than caching stale content.

Quick Check

Security check on serving files.

Recap

Read a file inside the handler so content stays live. Set utf-8, handle missing files, watch size, and confine paths to a safe root. ✅

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

Урок «Чтение файла с диска» бесплатный?

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

Чему я научусь в уроке «Чтение файла с диска»?

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

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

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

Сколько времени занимает урок «Чтение файла с диска»?

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

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

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

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

  1. Объяснение URI ресурсов
  2. Предоставление статического текстового ресурса
  3. Чтение файла с диска
  4. Выбор правильного типа MIME
← Назад к MCP Academy