Ресурсы в MCP-серверах

Введение в Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Что такое ресурсы MCP?

 

Глава 2

  • Ресурсы + Промпты

primitive1.png

Введение в Model Context Protocol (MCP)

Что такое ресурсы MCP?

 

Глава 2

  • Ресурсы и промпты
  • Интеграция с API и базами данных

Ресурсы: данные или объекты данных, доступные только для чтения, запрашиваемые MCP-клиентом

  • Не обязательно вызываются LLM
  • Инициируются приложением → например, настройки пользователя
  • Инициируются пользователем → например, загрузка файла

primitive2.png

Введение в Model Context Protocol (MCP)

Ресурсы MCP в ИИ-приложениях

 

mcp_resources.png

Введение в Model Context Protocol (MCP)

Определение ресурсов MCP-сервера

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")


@mcp.resource("file://locations.txt")
def get_locations(): try: with open('locations.txt', 'r') as f: content = f.read() return content except FileNotFoundError: return "locations.txt file not found"

 

  • URI: унифицированный идентификатор ресурса

    • Может указывать на локальные файлы, API, удалённые серверы и другое
    • Поддерживает динамическую подстановку параметров, например ID пользователя
  • locations.txt (на стороне сервера) → список часовых поясов

Введение в Model Context Protocol (MCP)

Определение ресурсов MCP-сервера

@mcp.resource("file://locations.txt")
def get_locations() -> str:
    """
    Get the list of cities for timezone conversion.

    Returns:
        Contents of the locations.txt file with city names
    """
    try:
        with open('locations.txt', 'r') as f:
            content = f.read()
        return content
    except FileNotFoundError:
        return "locations.txt file not found"
Введение в Model Context Protocol (MCP)

Сохранение сервера: timezone_server.py

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")

# Tools from before...

@mcp.resource("file://locations.txt")
def get_locations() -> str:
    # ...

if __name__ == "__main__":
    mcp.run(transport="stdio")
Введение в Model Context Protocol (MCP)

Клиент: получение списка ресурсов

async def list_resources():
    """List all available resources from the MCP server."""
    params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

response = await session.list_resources()
print("Available resources:") for resource in response.resources: print(f" - {resource.uri}") print(f" Name: {resource.name}") print(f" Description: {resource.description}") return response.resources
Введение в Model Context Protocol (MCP)

Клиент: получение списка ресурсов

print(asyncio.run(list_resources()))
Available resources:
 - file://locations.txt/
   Name: get_locations
   Description: 
    Get the list of cities for timezone conversion.

    Returns:
        Contents of the locations.txt file with city names

[Resource(name='get_locations', title=None, uri=AnyUrl('file://locations.txt/'),
          description='\n    Get the list of cities for timezone conversion.\n\n...',
          mimeType='text/plain', size=None, icons=None, annotations=None, meta=None)]
Введение в Model Context Protocol (MCP)

Клиент: чтение ресурсов

async def read_resource(resource_uri: str):
    """Read a specific resource by URI."""
    params = StdioServerParameters(command=sys.executable, args=["timezone_server.py"])

    async with stdio_client(params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()

print(f"Reading resource: {resource_uri}") resource_content = await session.read_resource(resource_uri)
for content in resource_content.contents: print(f"\nContent ({content.mimeType}):") print(content.text) return resource_content
Введение в Model Context Protocol (MCP)

Клиент: чтение ресурсов

print(asyncio.run(read_resource('file://locations.txt/')))
Reading resource: file://locations.txt

Content (text/plain):
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
...

ReadResourceResult(meta=None, contents=[TextResourceContents(uri=AnyUrl('file://locations.txt/'),
                   mimeType='text/plain', meta=None, text='Africa/Abidjan\nAfrica/Accra...')])
Введение в Model Context Protocol (MCP)

Вперёд, практиковаться!

Введение в Model Context Protocol (MCP)

Preparing Video For Download...