Inviteurs dans les serveurs MCP

Introduction au Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Qu'est-ce qu'un inviteur MCP?

 

Inviteurs : gabarits réutilisables qui optimisent les LLM pour des tâches précises

  • Flux de travail et comportements
  • Réduisent la charge d'invite sur l'utilisateur

inviteurs.png

Introduction au Model Context Protocol (MCP)

Le besoin d'invite

entrées_ambiguës.png

Introduction au Model Context Protocol (MCP)

L'inviteur du convertisseur de fuseau horaire

You are a timezone conversion engine.

Your task is to:
1. Extract the source datetime from the user's natural language input.
2. Identify the source timezone (explicit or inferred).
3. Convert the datetime into the target timezone.

Rules:
- If the date is ambiguous (e.g., "next Friday"), resolve it relative to the provided datetime.
- If the input cannot be resolved confidently, seek clarification.

→ Exposez cet inviteur pour la tâche de conversion de fuseaux horaires

Introduction au Model Context Protocol (MCP)

Définir des inviteurs de serveur MCP

@mcp.prompt(title="Timezone Conversion")

def convert_timezone_prompt(user_input: str) -> str:
return f"""You are a timezone conversion engine. Your task is to: 1. Extract the source datetime... Rules: - If the date is ambiguous (e.g., "next Friday"), resolve it relative to the provided datetime. - If the input cannot be resolved confidently, seek clarification. User's timezone conversion request: {user_input}"""
Introduction au Model Context Protocol (MCP)

Serveur MCP local : timezone_server.py

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")

# Tools and resources from before...

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

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

Client : lister les inviteurs

async def list_prompts():
    """Répertorie tous les inviteurs disponibles depuis le serveur 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()

# Lister les inviteurs disponibles prompts = await session.list_prompts() print(f"Available prompts: {[p.name for p in prompts.prompts]}")
Introduction au Model Context Protocol (MCP)

Client : lister les inviteurs

print(asyncio.run(list_prompts()))
Available prompts: ['convert_timezone_prompt']

Le name de l'inviteur n'est pas le même que son title

@mcp.prompt(title="Timezone Conversion")
def convert_timezone_prompt(timezone_request: str) -> str:
    # ...
Introduction au Model Context Protocol (MCP)

Client : lister les inviteurs

print(asyncio.run(list_prompts()))
Available prompts: ['convert_timezone_prompt']

Le name de l'inviteur n'est pas le même que son title

# Lister les inviteurs disponibles
prompts = await session.list_prompts()
print(f"Available prompts: {[p.name for p in prompts.prompts]}")
  • L'attribut .name est utilisé côté client (pas .title)
Introduction au Model Context Protocol (MCP)

Client : récupérer des inviteurs

async def read_prompt(user_input: str, prompt_name: str = "convert_timezone_prompt") -> str:
    """Récupère un inviteur du serveur MCP avec l'entrée utilisateur."""
    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()

            prompts = await session.list_prompts()

# Récupérer l'inviteur if prompts.prompts: prompt = await session.get_prompt(prompt_name, arguments={"timezone_request": user_input})
print(f"Prompt result: {prompt.messages[0].content.text}") return prompt.messages[0].content.text
Introduction au Model Context Protocol (MCP)
print(asyncio.run(read_prompt(user_input="It is 9:50 AM in the UK in January. What time is
    it in Lisbon, Portugal?")))
You are a timezone conversion engine.

Your task is to:
1. Extract the source datetime from the user's natural language input.
2. Identify the source timezone (explicit or inferred).
3. Convert the datetime into the target timezone.

Rules:
- If the date is ambiguous (e.g., "next Friday"), resolve it relative to the...
- If the input cannot be resolved confidently, seek clarification.

User's timezone conversion request: It is 9:50 AM in the UK in January. What time is it in
Lisbon, Portugal?
Introduction au Model Context Protocol (MCP)

Passons à la pratique !

Introduction au Model Context Protocol (MCP)

Preparing Video For Download...