MCP en LLM's: prompts en resources

Introductie tot Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Resources en prompts in de LLM-flow

 

  • Resources: alleen-lezen context
  • Prompts: instructiesjablonen om het gedrag te sturen en het model voor de taak te optimaliseren

 

→ Verder met de Anthropic Messages API

 

LLM-primitieven

Introductie tot Model Context Protocol (MCP)

De prompt-resource-workflow

 

Prompt-resource-workflow

Introductie tot Model Context Protocol (MCP)

De prompt-resource-workflow

 

Prompt-resource-workflow

Introductie tot Model Context Protocol (MCP)

De prompt-resource-workflow

 

Prompt-resource-workflow

Introductie tot Model Context Protocol (MCP)

De prompt-resource-workflow

 

Prompt-resource-workflow

Introductie tot Model Context Protocol (MCP)
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")

@mcp.tool()
def convert_timezone(date_time: str, from_timezone: str, to_timezone: str) -> str:
    # ...

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

@mcp.prompt(title="Timezone Conversion")
def convert_timezone_prompt(timezone_request: str) -> str:
    # ...

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

Client-hulpfuncties

 

  • read_resource(resource_uri): haalt de inhoud van een resource op via URI
  • read_prompt(prompt_name, user_input): haalt de prompttemplate op met de gebruikersvraag ingevuld
Introductie tot Model Context Protocol (MCP)

1. Resource en prompt ophalen

async def get_context_from_mcp(user_query: str) -> tuple[str, str]:
    """Haal resource-inhoud en prompttekst op 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()

# Get the resource (supported locations) resource_result = await session.read_resource("file://locations.txt") resource_text = resource_result.contents[0].text
# Get the prompt with the user's query prompt_result = await session.get_prompt("convert_timezone_prompt", arguments={"timezone_request": user_query}) prompt_text = prompt_result.messages[0].content.text
return resource_text, prompt_text
Introductie tot Model Context Protocol (MCP)

2. Systeembericht opbouwen en LLM aanroepen

async def call_llm_with_context(user_query: str):
    """Roep de LLM aan met resource- en promptcontext van MCP."""

resource_text, prompt_text = await get_context_from_mcp(user_query)
# Combine prompt (task + rules + user request) with resource (supported locations) full_prompt = prompt_text + "\n\nSupported locations:\n" + resource_text
client = AsyncAnthropic(api_key="<ANTHROPIC_API_TOKEN>") response = await client.messages.create( model="claude-sonnet-4-6", max_tokens=1024, messages=[{"role": "user", "content": full_prompt}], tools=anthropic_tools, # from get_tools_from_mcp(), formatted for Anthropic )
Introductie tot Model Context Protocol (MCP)

3. De response afhandelen

    if response.stop_reason == "end_turn":
        text = next((b.text for b in response.content if b.type == "text"), "")
        print(f"\nAssistant: {text}")
        return str(text)

if response.stop_reason == "tool_use": tool_use = next(b for b in response.content if b.type == "tool_use") result = await call_mcp_tool( tool_use.name, tool_use.input) # ... send the tool_result back in a follow-up # request, then print the reply, as before
Introductie tot Model Context Protocol (MCP)

Voorbeeld: vage vraag

if __name__ == "__main__":
    asyncio.run(call_llm_with_context("What time is it in Canada?"))
Assistant: Canada heeft meerdere tijdzones. Welke stad of regio bedoel je?
Bijv. Toronto, Vancouver of Halifax?
Introductie tot Model Context Protocol (MCP)

Voorbeeld: duidelijke vraag

if __name__ == "__main__":
    asyncio.run(call_llm_with_context("It is 9:50 AM in the UK in January. What
        time is it in Lisbon, Portugal?"))
Assistant: In Lissabon is het ook 9:50 AM.
Introductie tot Model Context Protocol (MCP)

Samenvatting: resources en prompts met de LLM

 

Prompt-resource-workflow

Introductie tot Model Context Protocol (MCP)

Laten we oefenen!

Introductie tot Model Context Protocol (MCP)

Preparing Video For Download...