Формирование содержимого во время чтения
Вычисляйте тело ресурса в момент запроса.
«Формирование содержимого во время чтения» — бесплатный урок MCP Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения MCP Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс MCP Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Lazy, Not Eager
A dynamic resource doesn't store a fixed body. Its content is computed on demand, only when a client actually asks to read it. ⚡
The Read Triggers the Work
Your resource function runs at the moment of a read request. Nothing happens until a client reads it, so you never waste effort building content no one wants.
Return the Body
Whatever your function returns becomes the resource's content. Return a string and the client receives that exact text as the resource body.
@mcp.resource("time://now")
def now() -> str:
return datetime.now().isoformat()Fresh Every Read
Because the body is rebuilt each time, the model always sees current data. Read the clock twice and you get two different timestamps.
Use the URI Variables
Combine read-time building with a template. The captured parameters shape what you compute, so the same function serves tailored content per URI.
@mcp.resource("greeting://{name}")
def greet(name: str) -> str:
return f"Hello, {name}!"Pull From Anywhere
At read time you can do real work: query a database, call an API, or read a file. The result of that work is what you return as the body.
@mcp.resource("stats://summary")
def summary() -> str:
return db.fetch_summary()Async When You Wait
If building content means waiting on I/O, make the function async. The server can serve other reads while yours awaits a slow network call.
@mcp.resource("feed://latest")
async def latest() -> str:
return await fetch_feed()Shape the Returned Text
You decide the format of the body. Returning JSON text is common when the model needs structured data it can reason over cleanly.
import json
def report() -> str:
return json.dumps({"ok": True})Keep It Quick
A read should feel snappy. If the work is heavy, cache the result so repeated reads don't redo expensive computation every single time.
Handle Missing Data
What if the requested thing doesn't exist? Raise an error from the function so the client learns the resource couldn't be read, rather than returning junk.
def get_doc(doc_id: str) -> str:
if doc_id not in store:
raise ValueError("not found")
return store[doc_id]Why This Matters
Read-time building turns a static idea into a live window on your data. The model always reads what is true right now, not a stale snapshot. 🎯
Quick Check
When does the body of a dynamic resource get produced?
Recap
You saw how returning a value from a resource function builds content on read, giving the model fresh, computed data every time. Next: listed vs templated resources. 🚀
Часто задаваемые вопросы
Урок «Формирование содержимого во время чтения» бесплатный?
Да — полный текст урока «Формирование содержимого во время чтения» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 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 — локальная установка не требуется.
Все уроки этого курса
- Параметризованные URI ресурсов
- Формирование содержимого во время чтения
- Списки и шаблонные ресурсы
- Уведомление клиентов об обновлениях