Resurse în serverele MCP

Introducere în Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Ce sunt resursele MCP?

 

Capitolul 2

  • Resurse + Prompturi

primitive1.png

Introducere în Model Context Protocol (MCP)

Ce sunt resursele MCP?

 

Capitolul 2

  • Resurse și prompturi
  • Integrare cu API-uri și baze de date

Resurse: date sau obiecte de date disponibile doar în citire, accesate de clientul MCP

  • _Nu_ sunt neapărat apelate de un LLM
  • Conduse de aplicație → ex.: preferințele utilizatorului
  • Conduse de utilizator → ex.: încărcare fișier

primitive2.png

Introducere în Model Context Protocol (MCP)

Resurse MCP în aplicații AI

 

mcp_resources.png

Introducere în Model Context Protocol (MCP)

Definirea resurselor serverului 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: identificator uniform de resursă

    • Poate indica fișiere locale, API-uri, servere la distanță și altele
    • Poate insera dinamic parametri, precum ID-ul utilizatorului
  • locations.txt (pe server) → listă de locații de fus orar

Introducere în Model Context Protocol (MCP)

Definirea resurselor serverului 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"
Introducere în Model Context Protocol (MCP)

Salvarea serverului: 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")
Introducere în Model Context Protocol (MCP)

Client: Listarea resurselor

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
Introducere în Model Context Protocol (MCP)

Client: Listarea resurselor

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)]
Introducere în Model Context Protocol (MCP)

Client: Citirea resurselor

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
Introducere în Model Context Protocol (MCP)

Client: Citirea resurselor

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...')])
Introducere în Model Context Protocol (MCP)

Să exersăm!

Introducere în Model Context Protocol (MCP)

Preparing Video For Download...