MCP Sunucularında Kaynaklar

Model Context Protocol (MCP) Giriş

James Chapman

AI Curriculum Manager, DataCamp

MCP Kaynakları Nedir?

 

Bölüm 2

  • Kaynaklar + İstemler

ilkel1.png

Model Context Protocol (MCP) Giriş

MCP Kaynakları Nedir?

 

Bölüm 2

  • Kaynaklar ve istemler
  • API ve veritabanlarıyla entegrasyon

Kaynaklar: MCP istemcisinin aldığı salt-okunur veriler veya veri nesneleri

  • Mutlaka bir LLM tarafından çağrılmak zorunda değildir
  • Uygulama odaklı → ör. kullanıcı tercihleri
  • Kullanıcı odaklı → ör. dosya yükleme

ilkel2.png

Model Context Protocol (MCP) Giriş

Yapay Zekâ Uygulamalarında MCP Kaynakları

 

mcp_resources.png

Model Context Protocol (MCP) Giriş

MCP Sunucu Kaynaklarını Tanımlama

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: tekdüzen kaynak tanımlayıcısı

    • Yerel dosyaları, API'leri, uzak sunucuları vb. gösterebilir
    • Kullanıcı Kimliği gibi parametreleri dinamik ekleyebilir
  • locations.txt (sunucu tarafı) → saat dilimi konumlarının listesi

Model Context Protocol (MCP) Giriş

MCP Sunucu Kaynaklarını Tanımlama

@mcp.resource("file://locations.txt")
def get_locations() -> str:
    """
    Saat dilimi dönüşümü için şehir listesini alın.

    Returns:
        Şehir adlarını içeren locations.txt dosyasının içeriği
    """
    try:
        with open('locations.txt', 'r') as f:
            content = f.read()
        return content
    except FileNotFoundError:
        return "locations.txt file not found"
Model Context Protocol (MCP) Giriş

Sunucuyu Kaydetme: timezone_server.py

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Timezone Converter")

# Önceki araçlar...

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

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

İstemci: Kaynakları Listeleme

async def list_resources():
    """MCP sunucusundaki tüm mevcut kaynakları listeleyin."""
    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("Mevcut kaynaklar:") for resource in response.resources: print(f" - {resource.uri}") print(f" Ad: {resource.name}") print(f" Açıklama: {resource.description}") return response.resources
Model Context Protocol (MCP) Giriş

İstemci: Kaynakları Listeleme

print(asyncio.run(list_resources()))
Mevcut kaynaklar:
 - file://locations.txt/
   Ad: get_locations
   Açıklama: 
    Saat dilimi dönüşümü için şehir listesini alın.

    Returns:
        Şehir adlarını içeren locations.txt dosyasının içeriği

[Resource(name='get_locations', title=None, uri=AnyUrl('file://locations.txt/'),
          description='\n    Saat dilimi dönüşümü için şehir listesini alın.\n\n...',
          mimeType='text/plain', size=None, icons=None, annotations=None, meta=None)]
Model Context Protocol (MCP) Giriş

İstemci: Kaynak Okuma

async def read_resource(resource_uri: str):
    """URI ile belirli bir kaynağı okuyun."""
    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"Kaynak okunuyor: {resource_uri}") resource_content = await session.read_resource(resource_uri)
for content in resource_content.contents: print(f"\nİçerik ({content.mimeType}):") print(content.text) return resource_content
Model Context Protocol (MCP) Giriş

İstemci: Kaynak Okuma

print(asyncio.run(read_resource('file://locations.txt/')))
Kaynak okunuyor: file://locations.txt

İçerik (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...')])
Model Context Protocol (MCP) Giriş

Hadi pratik yapalım!

Model Context Protocol (MCP) Giriş

Preparing Video For Download...