Tài nguyên trong máy chủ MCP

Giới thiệu về Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Tài nguyên MCP là gì?

 

Chương 2

  • Tài nguyên + Lời nhắc

primitive1.png

Giới thiệu về Model Context Protocol (MCP)

Tài nguyên MCP là gì?

 

Chương 2

  • Tài nguyên và lời nhắc
  • Tích hợp với API và cơ sở dữ liệu

Tài nguyên: dữ liệu chỉ đọc hoặc đối tượng dữ liệu do client MCP truy xuất

  • Không nhất thiết do LLM gọi
  • Do ứng dụng điều khiển → ví dụ: tùy chọn người dùng
  • Do người dùng điều khiển → ví dụ: tải tệp lên

primitive2.png

Giới thiệu về Model Context Protocol (MCP)

Tài nguyên MCP trong ứng dụng AI

 

mcp_resources.png

Giới thiệu về Model Context Protocol (MCP)

Định nghĩa tài nguyên máy chủ 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: định danh tài nguyên thống nhất

    • Có thể trỏ tới tệp cục bộ, API, máy chủ từ xa, v.v.
    • Có thể chèn tham số động như User ID
  • locations.txt (phía máy chủ) → danh sách múi giờ

Giới thiệu về Model Context Protocol (MCP)

Định nghĩa tài nguyên máy chủ MCP

@mcp.resource("file://locations.txt")
def get_locations() -> str:
    """
    Lấy danh sách thành phố để chuyển đổi múi giờ.

    Returns:
        Nội dung tệp locations.txt với tên các thành phố
    """
    try:
        with open('locations.txt', 'r') as f:
            content = f.read()
        return content
    except FileNotFoundError:
        return "locations.txt file not found"
Giới thiệu về Model Context Protocol (MCP)

Lưu máy chủ: 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")
Giới thiệu về Model Context Protocol (MCP)

Client: Liệt kê tài nguyên

async def list_resources():
    """Liệt kê mọi tài nguyên khả dụng từ máy chủ MCP."""
    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("Tài nguyên khả dụng:") for resource in response.resources: print(f" - {resource.uri}") print(f" Tên: {resource.name}") print(f" Mô tả: {resource.description}") return response.resources
Giới thiệu về Model Context Protocol (MCP)

Client: Liệt kê tài nguyên

print(asyncio.run(list_resources()))
Tài nguyên khả dụng:
 - file://locations.txt/
   Tên: get_locations
   Mô tả: 
    Lấy danh sách thành phố để chuyển đổi múi giờ.

    Returns:
        Nội dung tệp locations.txt với tên các thành phố

[Resource(name='get_locations', title=None, uri=AnyUrl('file://locations.txt/'),
          description='\n    Lấy danh sách thành phố để chuyển đổi múi giờ.\n\n...',
          mimeType='text/plain', size=None, icons=None, annotations=None, meta=None)]
Giới thiệu về Model Context Protocol (MCP)

Client: Đọc tài nguyên

async def read_resource(resource_uri: str):
    """Đọc một tài nguyên theo 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"Đang đọc tài nguyên: {resource_uri}") resource_content = await session.read_resource(resource_uri)
for content in resource_content.contents: print(f"\nNội dung ({content.mimeType}):") print(content.text) return resource_content
Giới thiệu về Model Context Protocol (MCP)

Client: Đọc tài nguyên

print(asyncio.run(read_resource('file://locations.txt/')))
Đang đọc tài nguyên: file://locations.txt

Nội dung (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...')])
Giới thiệu về Model Context Protocol (MCP)

Ayo berlatih!

Giới thiệu về Model Context Protocol (MCP)

Preparing Video For Download...