Fetch Resource and Prompt from MCP
Your currency server exposes a resource (file://currencies.txt) and a prompt (convert_currency_prompt) that combine the user's request with task-specific context and rules. To feed an LLM, the client must fetch both in one go. Implement a helper function called get_context_from_mcp() that returns the resource text and the prompt text (with the user's query already in it) so the caller can build the message.
The currency_server.py file is available with a tool, resource, and prompt. Use the same session to read the resource and get the prompt with the user's input.
Este ejercicio forma parte del curso
Introduction to Model Context Protocol (MCP)
Instrucciones del ejercicio
- Inside the session, call the method to read the resource at
"file://currencies.txt". - Call the method to get the prompt by name with the user's input: use prompt name
"convert_currency_prompt"and anargumentsdict with key"currency_request"and valueuser_query.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def get_context_from_mcp(user_query: str) -> tuple[str, str]:
"""Fetch resource content and prompt text from the MCP server."""
params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
# Read the resource (supported currencies)
resource_result = await session.____("file://currencies.txt")
resource_text = resource_result.contents[0].text
# Get the prompt with the user's query
prompt_result = await session.____("convert_currency_prompt",
arguments={"currency_request": user_query})
prompt_text = prompt_result.messages[0].content.text
return resource_text, prompt_text
print(asyncio.run(get_context_from_mcp("How much is 50 GBP in euros?")))