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) 입문

AI 앱에서의 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...