MCP'den Kaynak ve İstem Getir
Döviz sunucun bir kaynak (file://currencies.txt) ve bir istem (convert_currency_prompt) sunuyor; bunlar, kullanıcının isteğini görev-özel bağlam ve kurallarla birleştiriyor. Bir LLM'e veri sağlamak için istemcinin her ikisini de tek seferde alması gerekir. Çağıranın iletiyi oluşturabilmesi için, kaynak metni ve istem metnini (kullanıcının sorgusu zaten içinde olacak şekilde) döndüren get_context_from_mcp() adlı bir yardımcı fonksiyon uygula.
currency_server.py dosyasında bir araç, kaynak ve istem mevcut. Aynı oturumu kullanarak kaynağı oku ve kullanıcının girdisiyle istemi al.
Bu egzersiz, kursun bir parçasıdır
Model Context Protocol (MCP) Giriş
Egzersiz talimatları
- Oturum içinde,
"file://currencies.txt"konumundaki kaynağı okumak için yöntemi çağır. - Kullanıcının girdisiyle ada göre istemi almak için yöntemi çağır:
"convert_currency_prompt"istem adını ve anahtarı"currency_request", değeriuser_queryolan birargumentssözlüğü kullan.
Uygulamalı etkileşimli egzersiz
Bu egzersizi bu örnek kodu tamamlayarak deneyin.
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?")))