Resources in MCP-servers

Introductie tot Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Wat zijn MCP-resources?

 

Hoofdstuk 2

  • Resources + prompts

primitief1.png

Introductie tot Model Context Protocol (MCP)

Wat zijn MCP-resources?

 

Hoofdstuk 2

  • Resources en prompts
  • Integratie met API's en databases

Resources: alleen-lezen data of dataobjecten opgehaald door de MCP-client

  • Niet per se aangeroepen door een LLM
  • Toepassingsgestuurd → bijv. gebruikersvoorkeuren
  • Gebruikersgestuurd → bijv. bestandsupload

primitief2.png

Introductie tot Model Context Protocol (MCP)

MCP-resources in AI-apps

 

mcp_resources.png

Introductie tot Model Context Protocol (MCP)

MCP-serverresources definiëren

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: uniforme resource-identificator

    • Kan verwijzen naar lokale files, API's, remote servers, enz.
    • Kan dynamisch parameters invoegen, zoals User ID
  • locations.txt (server-side) → lijst met tijdzone-locaties

Introductie tot Model Context Protocol (MCP)

MCP-serverresources definiëren

@mcp.resource("file://locations.txt")
def get_locations() -> str:
    """
    Haal de lijst met steden op voor tijdzoneconversie.

    Returns:
        Inhoud van het bestand locations.txt met stadsnamen
    """
    try:
        with open('locations.txt', 'r') as f:
            content = f.read()
        return content
    except FileNotFoundError:
        return "locations.txt file not found"
Introductie tot Model Context Protocol (MCP)

De server opslaan: timezone_server.py

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")

# Tools van eerder...

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

if __name__ == "__main__":
    mcp.run(transport="stdio")
Introductie tot Model Context Protocol (MCP)

Client: resources opvragen

async def list_resources():
    """Toon alle beschikbare resources van de 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("Beschikbare resources:") for resource in response.resources: print(f" - {resource.uri}") print(f" Naam: {resource.name}") print(f" Omschrijving: {resource.description}") return response.resources
Introductie tot Model Context Protocol (MCP)

Client: resources opvragen

print(asyncio.run(list_resources()))
Beschikbare resources:
 - file://locations.txt/
   Naam: get_locations
   Omschrijving: 
    Haal de lijst met steden op voor tijdzoneconversie.

    Returns:
        Inhoud van het bestand locations.txt met stadsnamen

[Resource(name='get_locations', title=None, uri=AnyUrl('file://locations.txt/'),
          description='\n    Haal de lijst met steden op voor tijdzoneconversie.\n\n...',
          mimeType='text/plain', size=None, icons=None, annotations=None, meta=None)]
Introductie tot Model Context Protocol (MCP)

Client: resources lezen

async def read_resource(resource_uri: str):
    """Lees een specifieke resource via de 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"Resource lezen: {resource_uri}") resource_content = await session.read_resource(resource_uri)
for content in resource_content.contents: print(f"\nInhoud ({content.mimeType}):") print(content.text) return resource_content
Introductie tot Model Context Protocol (MCP)

Client: resources lezen

print(asyncio.run(read_resource('file://locations.txt/')))
Resource lezen: file://locations.txt

Inhoud (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...')])
Introductie tot Model Context Protocol (MCP)

Laten we oefenen!

Introductie tot Model Context Protocol (MCP)

Preparing Video For Download...