AI Genel Çalışma Rehberi

Blog / Lab serisi

MCP ile Private Agentic Akışları

Son güncelleme: Ocak 2026


Hızlı Bakış

Ne: Local LLM'ler ile tamamen offline çalışan agent sistemleri kurma rehberi

Neden: Hassas veriler (sağlık, finans, hukuk) cloud API'lere gönderilemez - GDPR, HIPAA, KVKK uyumluluğu

Nasıl: LM Studio + Python + MCP protokolü ile private agent mimarisi

Kimler için: Veri güvenliği gerektiren projelerde çalışan geliştiriciler


GenAI'da Gizlilik Paradoksu

Geleneksel LLM'ler sadece sorulara cevap verirken, Agentic AI sistemleri düşünebilir, planlayabilir ve kullanıcı adına aksiyon alabilir.

Bu güçlü yetenek, özellikle sağlık, finans, hukuk ve savunma gibi düzenlenmiş sektörlerde kritik bir kısıtlamayla gelir: Public API'ler kabul edilemez.

Hassas verilerin (tıbbi kayıtlar, finansal işlemler, müşteri bilgileri) üçüncü taraf endpoint'lere gönderilmesi:

gibi düzenlemeleri ve veri egemenliği ilkelerini ihlal eder.


Public vs Private Agent

Public Agent, verilerinizi işlemek için dış API'lere (OpenAI, Anthropic vb.) gönderir. Bu durum hassas veriler için ciddi riskler oluşturur:

Private Agent ise tüm işlemleri kendi altyapınızda (local bilgisayar veya private cloud) gerçekleştirir. Veri hiçbir zaman dışarı çıkmaz.

💡 Düşünsenize: Public Agent kullanmak, hassas dosyalarınızı kalabalık bir kafede çalışan birine emanet etmek gibi - yanındaki masaya baksalar ne görürler? Private Agent ise kendi ofisinizde, kilitli bir odada çalışan uzman - başka kimsenin işi yok.

flowchart LR subgraph public ["☁️ Public Agent"] direction LR U1["👤 Kullanıcı"] --> P1["📤 Prompt"] P1 --> API["🌐 External API<br/>(OpenAI, Anthropic)"] API --> R1["📥 Yanıt"] end subgraph private ["🔒 Private Agent"] direction LR U2["👤 Kullanıcı"] --> P2["📤 Prompt"] P2 --> LOCAL["🖥️ Local LLM<br/>(LM Studio)"] LOCAL --> R2["📥 Yanıt"] end style public fill:#ffe6e6,stroke:#ff6666 style private fill:#e6ffe6,stroke:#66cc66

Üç Katmanlı Mimari

Hani şöyle bir durum var ya - agent'ı üç katlı bir bina gibi düşünebilirsiniz. Her katın kendine has bir görevi var:

flowchart TB subgraph SYSTEM ["🏗️ PRIVATE AGENT MİMARİSİ"] direction TB subgraph ACTION ["🎯 ACTION LAYER"] T1["🔧 Tools"] T2["📁 File Operations"] T3["🗄️ Database Queries"] end subgraph AUG ["📚 AUGMENTATION LAYER"] R1["📄 Resources"] R2["💾 RAG / VectorDB"] R3["📝 Prompt Templates"] end subgraph FOUND ["🧠 FOUNDATION LAYER"] LLM["🤖 Local LLM<br/>(qwen, llama)"] end ACTION --> AUG AUG --> FOUND end USER["👤 Kullanıcı Sorusu"] --> ACTION FOUND --> OUTPUT["📤 Yanıt"] style FOUND fill:#e6f3ff,stroke:#3399ff style AUG fill:#fff2e6,stroke:#ff9933 style ACTION fill:#f2e6ff,stroke:#9933ff

Foundation Layer (Temel Katman)

Augmentation Layer (Zenginleştirme Katmanı)

Action Layer (Eylem Katmanı)


Dikkat: Private = %100 Güvenli DEĞİL!

Evet, local'de çalıştırıyorsunuz ama bazı riskler devam ediyor:

Data Embedding via Fine-Tuning Modeli özel verilerle fine-tune ettiyseniz, o veriler model ağırlıklarına gömülür. Yani modele erişimi olan herkes potansiyel olarak o verileri çıkarabilir. Teknik olarak zor ama imkansız değil.

Regulatory Compliance GDPR ve HIPAA "unutulma hakkı" istiyor. Peki modele gömülmüş bir veriyi nasıl sileceksiniz? İşte bu teknik olarak çok karmaşık ve tam anlamıyla mümkün değil. Eksik kalır.

Insider Threats Güvenlik sadece dış saldırılar demek değil. Yetkili kullanıcılar da yanlışlıkla (veya kasıtlı) veriyi açığa çıkarabilir. İçeriden gelen tehditler bazen dışarıdan gelenlerden daha tehlikeli.

Temel Önlemler:


MCP (Model Context Protocol) Nedir?

Hani USB-C ile her cihazı bağlayabiliyorsunuz ya? MCP de tam öyle - AI uygulamalarını harici sistemlere bağlamak için Anthropic'in geliştirdiği standart bir protokol.

flowchart LR subgraph HOST ["💻 MCP Host (Python Client)"] CLIENT["MCP Client"] end subgraph SERVERS ["📦 MCP Servers"] FS["📁 Filesystem<br/>Server"] MEM["🧠 Memory<br/>Server"] DB["🗄️ SQLite<br/>Server"] end CLIENT <--> |"JSON-RPC<br/>(stdio)"| FS CLIENT <--> |"JSON-RPC<br/>(stdio)"| MEM CLIENT <--> |"JSON-RPC<br/>(stdio)"| DB style HOST fill:#e6f3ff,stroke:#3399ff style SERVERS fill:#fff2e6,stroke:#ff9933

MCP üç temel primitive sunar:

Tools (Action Layer)

Resources (Augmentation Layer)

Prompts (Augmentation Layer)


Lab İçerikleri

Bu yazının teorik kısmını okudunuz. Şimdi sıra uygulamalı lab'lerde:

Lab 0: LM Studio kurulumu ve model indirme
Lab 1: Foundation Layer - Local LLM testi
Lab 2: Tool Calling Agent (Python fonksiyonları)
Lab 3: MCP Client Agent (MCP protokolü + Human-in-the-loop)
Lab 4: Custom Tool ekleme
Lab 5: Interactive File Analyzer (kapsamlı örnek)

Lab içeriklerine erişmek için GitHub hesabınızla giriş yapmanız gerekmektedir.


MCP'nin Rolü

MCP, AI uygulamalarını harici sistemlere bağlamak için Anthropic tarafından geliştirilen açık bir protokoldür. "AI için USB-C portu" gibi düşünebilirsiniz.

MCP Üç Temel Primitive Sunar:


Lab Ortamı ve Hands-on Çalışmalar

Bu modülün devamında 5 adet uygulamalı lab bulunmaktadır:

LabBaşlıkAmaç
Lab 1Foundation LayerLocal LLM API testi
Lab 2Tool Calling AgentPython fonksiyonları ile tool calling
Lab 3MCP Client AgentPython MCP client + Human-in-the-loop
Lab 4Custom Tool EklemeAgent'a yeni tool eklemeyi öğrenme
Lab 5Interactive AgentKapsamlı interaktif file analyzer

🔒 Lab içeriklerine erişmek için GitHub hesabınızla giriş yapmanız gerekmektedir.


Kaynaklar

Teknik Dokümantasyon:

Tool Calling / Function Calling:

Düzenleyici Standartlar:


Bu modül, Private Agent kavramını ve MCP ile local LLM entegrasyonunu öğretmek için hazırlanmıştır.


Bu sayfa, MCP ile Private Agentic Akışları modülünün uygulamalı lab bölümlerini içermektedir.


Lab Ortamı Kurulumu

Gereksinimler

Yazılımlar:

Model:

Tool Calling (Function Calling) Nedir?

Hani LLM'ler sadece metin üretirdi ya? Tool calling ile artık dış fonksiyonları çağırabiliyorlar. Mesela "dosyaları listele" dediğinizde, model "tamam bunu yapmak için list_directory() fonksiyonunu çağırmalıyım" diye karar veriyor.

flowchart LR A["👤 Kullanıcı: Dosyaları listele"] --> B["🤖 LLM Analiz"] B --> C{"Tool gerekli mi?"} C -->|Evet| D["🔧 list_directory()"] C -->|Hayır| E["💬 Direkt yanıt"] D --> F["📋 Sonuç"] F --> G["🤖 LLM Özetleme"] G --> H["📤 Kullanıcıya yanıt"]

Ama dikkat: Tüm modeller tool calling desteklemez! Destekleyen modellerin özellikleri:

⚠️ Vision-Language (VL) modeller görsel anlama için tasarlanmıştır ve genellikle tool calling için uygun değildir.

Destekleyen model aileleri:


Lab 0: LM Studio Kurulumu

  1. lmstudio.ai adresinden LM Studio'yu indirin ve kurun

  2. LM Studio'yu açın ve Discover sekmesinden model arayın

  3. Tool calling destekli bir model indirin:

    • qwen2.5-7b-instruct (~4.5GB) ✅ Önerilen
    • llama-3.1-8b-instruct (~4.5GB) ✅ Alternatif
    • mistral-7b-instruct-v0.3 (~4GB) ✅ Alternatif
  4. Model info'da "Trained for Tool Use" badge'i olduğundan emin olun

  5. Local Server sekmesine gidin ve sunucuyu başlatın:

    ✅ Server listening on http://localhost:1234

Lab 1: Foundation Layer — Local LLM Testi

Amaç: Local LLM'in çalıştığını doğrulamak.

Terminal'den API Testi

curl http://localhost:1234/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen2.5-7b-instruct",
    "messages": [
      {"role": "user", "content": "Merhaba! Sen kimsin?"}
    ],
    "temperature": 0.7
  }'

Python ile Test

import requests
 
response = requests.post(
    "http://localhost:1234/v1/chat/completions",
    json={
        "model": "qwen2.5-7b-instruct",
        "messages": [
            {"role": "user", "content": "Private Agent ne demek? Kısaca açıkla."}
        ]
    }
)
 
print(response.json()["choices"][0]["message"]["content"])

Beklenen Sonuç: Model yerel olarak yanıt üretir, hiçbir veri dışarı çıkmaz.

flowchart LR A["📝 curl/Python"] --> B["🌐 localhost:1234"] B --> C["🤖 Local LLM"] C --> D["📤 Yanıt"] style B fill:#e6ffe6,stroke:#66cc66 style C fill:#e6f3ff,stroke:#3399ff

Lab 2: Tool Calling Agent (Python)

Amaç: LM Studio API'sini kullanarak Python'da tool calling agent oluşturmak.

Proje Yapısını Oluşturma

macOS / Linux:

mkdir -p ~/Documents/privateAgents/lab
cd ~/Documents/privateAgents/lab
python3 -m venv .venv
source .venv/bin/activate
pip install requests

Windows (PowerShell):

New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\Documents\privateAgents\lab"
Set-Location "$env:USERPROFILE\Documents\privateAgents\lab"
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install requests

Simple Agent Kodu

simple_agent.py dosyası oluşturun:

"""
Private Agent Lab - Simple Tool Calling Agent
LM Studio + Python ile local tool calling örneği
"""
 
import json
import os
import requests
 
LM_STUDIO_URL = "http://localhost:1234/v1/chat/completions"
MODEL_NAME = "qwen2.5-7b-instruct"
 
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "list_directory",
            "description": "List files and folders in a directory",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "The directory path to list"
                    }
                },
                "required": ["path"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Read the contents of a file",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "The file path to read"
                    }
                },
                "required": ["path"]
            }
        }
    }
]
 
def list_directory(path: str) -> str:
    """List files in a directory"""
    try:
        items = os.listdir(path)
        result = []
        for item in items:
            full_path = os.path.join(path, item)
            item_type = "📁" if os.path.isdir(full_path) else "📄"
            result.append(f"{item_type} {item}")
        return "\n".join(result) if result else "Empty directory"
    except Exception as e:
        return f"Error: {str(e)}"
 
def read_file(path: str) -> str:
    """Read a file's contents"""
    try:
        with open(path, 'r', encoding='utf-8') as f:
            return f.read()
    except Exception as e:
        return f"Error: {str(e)}"
 
TOOL_FUNCTIONS = {
    "list_directory": list_directory,
    "read_file": read_file
}
 
def call_llm(messages: list, tools: list = None) -> dict:
    """Call LM Studio API"""
    payload = {
        "model": MODEL_NAME,
        "messages": messages,
        "temperature": 0.7,
    }
    if tools:
        payload["tools"] = tools
        payload["tool_choice"] = "auto"
    response = requests.post(LM_STUDIO_URL, json=payload, timeout=60)
    return response.json()
 
def run_agent(user_message: str) -> str:
    """Run the agent with a user message"""
    print(f"\n👤 User: {user_message}\n")
    
    messages = [
        {
            "role": "system",
            "content": "You are a helpful assistant with access to filesystem tools. "
                       "Use tools when the user asks about files or directories."
        },
        {"role": "user", "content": user_message}
    ]
    
    print("🤖 Calling LLM...")
    response = call_llm(messages, TOOLS)
    assistant_message = response["choices"][0]["message"]
    
    if "tool_calls" in assistant_message and assistant_message["tool_calls"]:
        print(f"🔧 Tool calls detected!\n")
        messages.append(assistant_message)
        
        for tool_call in assistant_message["tool_calls"]:
            tool_name = tool_call["function"]["name"]
            arguments = json.loads(tool_call["function"]["arguments"])
            
            print(f"   📞 Tool: {tool_name}")
            print(f"   📋 Args: {arguments}")
            
            result = TOOL_FUNCTIONS[tool_name](**arguments)
            print(f"   ✅ Result: {result[:100]}...\n" if len(result) > 100 else f"   ✅ Result: {result}\n")
            
            messages.append({
                "role": "tool",
                "tool_call_id": tool_call["id"],
                "name": tool_name,
                "content": result
            })
        
        final_response = call_llm(messages)
        return final_response["choices"][0]["message"]["content"]
    
    return assistant_message.get("content", "No response")
 
if __name__ == "__main__":
    print("🔒 Private Agent - Tool Calling Demo")
    print("="*40)
    result = run_agent("List the files in the current directory")
    print(f"🤖 Assistant: {result}")

Çalıştırma

python simple_agent.py

Beklenen Çıktı:

🔒 Private Agent - Tool Calling Demo
========================================
 
👤 User: List the files in the current directory
 
🤖 Calling LLM...
🔧 Tool calls detected!
 
   📞 Tool: list_directory
   📋 Args: {'path': '.'}
   ✅ Result: 📄 simple_agent.py
 
🤖 Assistant: The current directory contains:
📄 simple_agent.py

Lab 3: MCP Client Agent (Python)

Amaç: Gerçek MCP protokolünü kullanarak Python'da MCP client agent oluşturmak + Human-in-the-loop güvenlik mekanizması.

💡 Lab 2 vs Lab 3: Lab 2'de tool'lar Python fonksiyonlarıydı, agent içinde tanımlıydı. Lab 3'te ise tool'lar harici MCP sunucusunda, JSON-RPC ile haberleşiyoruz.

flowchart LR subgraph TC ["Lab 2: Tool Calling"] A1["🐍 Python Agent"] --> A2["🔧 Python Function"] end subgraph MCP ["Lab 3: MCP Protocol"] B1["🐍 Python Client"] --> |"JSON-RPC"| B2["📦 MCP Server"] B2 --> B3["🔧 Tool Execution"] end style TC fill:#e6f3ff,stroke:#3399ff style MCP fill:#fff2e6,stroke:#ff9933

Human-in-the-Loop Nedir?

İşte tam burada devreye giriyor Human-in-the-loop (HITL). LLM tool çağrısı yapmadan önce kullanıcı onayı ister. Neden kritik?

flowchart TB A["👤 User: Dosyaları sil"] --> B["🤖 LLM"] B --> C["🔧 Tool: delete_files()"] subgraph HITL ["🔐 Human-in-the-Loop"] C --> D{"⚠️ Onay ister"} D -->|"✅ Evet"| E["🗑️ Dosyalar silinir"] D -->|"❌ Hayır"| F["🛑 İşlem iptal"] end

Çünkü:

MCP Agent Kodu

mcp_agent.py dosyası oluşturun:

"""
Private Agent Lab - MCP Client Agent
MCP protokolü ile tool calling örneği
"""
 
import json
import subprocess
import requests
 
LM_STUDIO_URL = "http://localhost:1234/v1/chat/completions"
MODEL_NAME = "qwen2.5-7b-instruct"
 
class MCPClient:
    """Simple MCP Client that communicates with MCP servers via stdio"""
    
    def __init__(self, server_command: list[str]):
        self.server_command = server_command
        self.process = None
        self.request_id = 0
        self.tools = []
        
    def start(self):
        """Start the MCP server process"""
        print(f"🚀 Starting MCP server: {' '.join(self.server_command)}")
        self.process = subprocess.Popen(
            self.server_command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1
        )
        self._initialize()
        
    def _send_request(self, method: str, params: dict = None) -> dict:
        """Send JSON-RPC request to MCP server"""
        self.request_id += 1
        request = {
            "jsonrpc": "2.0",
            "id": self.request_id,
            "method": method,
        }
        if params:
            request["params"] = params
            
        request_str = json.dumps(request) + "\n"
        self.process.stdin.write(request_str)
        self.process.stdin.flush()
        
        response_str = self.process.stdout.readline()
        return json.loads(response_str) if response_str else {}
    
    def _initialize(self):
        """Initialize MCP connection"""
        response = self._send_request("initialize", {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {"name": "private-agent-lab", "version": "1.0.0"}
        })
        
        if "result" in response:
            server_name = response['result'].get('serverInfo', {}).get('name', 'unknown')
            print(f"✅ MCP initialized: {server_name}")
        
        self._send_request("notifications/initialized")
        self._list_tools()
        
    def _list_tools(self):
        """Get available tools from MCP server"""
        response = self._send_request("tools/list")
        if "result" in response:
            self.tools = response["result"].get("tools", [])
            print(f"🔧 MCP Tools: {[t['name'] for t in self.tools]}")
    
    def call_tool(self, name: str, arguments: dict) -> str:
        """Call an MCP tool via JSON-RPC"""
        response = self._send_request("tools/call", {
            "name": name,
            "arguments": arguments
        })
        
        if "result" in response:
            content = response["result"].get("content", [])
            if content:
                return content[0].get("text", str(content))
        return "No result"
    
    def stop(self):
        if self.process:
            self.process.terminate()
 
def main():
    import os
    
    print("\n" + "="*60)
    print("🔒 Private Agent Lab - MCP Client Agent")
    print("="*60)
    
    allowed_dir = os.path.expanduser("~/Documents")
    print(f"📁 Allowed directory: {allowed_dir}\n")
    
    client = MCPClient([
        "npx", "-y", "@modelcontextprotocol/server-filesystem", 
        allowed_dir
    ])
    
    try:
        client.start()
        
        print("\n📂 Listing directory via MCP...")
        result = client.call_tool("list_directory", {"path": allowed_dir})
        print(f"Result: {result[:200]}...")
        
    except FileNotFoundError:
        print("❌ npx not found! Install Node.js: https://nodejs.org/")
    finally:
        client.stop()
 
if __name__ == "__main__":
    main()

Gereksinim

node --version  # v18+ gerekli

Çalıştırma

python mcp_agent.py

Lab 4: Custom Tool Ekleme

Amaç: Kendi tool'unuzu tanımlayıp agent'a eklemeyi öğrenmek.

Yeni Tool Tanımlama

simple_agent.py'deki TOOLS listesine ekleyin:

{
    "type": "function",
    "function": {
        "name": "search_notes",
        "description": "Search through saved notes and return matching content",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "The search query"
                }
            },
            "required": ["query"]
        }
    }
}

Tool Implementation

NOTES_STORE = {
    "project": "Private Agent Eğitimi - AI geliştiriciler için 2 saatlik modül",
    "tools": "list_directory, read_file, write_file, search_notes",
    "status": "Geliştirme aşamasında, Lab 3 tamamlandı"
}
 
def search_notes(query: str) -> str:
    """Search through notes"""
    results = []
    query_lower = query.lower()
    for key, value in NOTES_STORE.items():
        if query_lower in key.lower() or query_lower in value.lower():
            results.append(f"📝 {key}: {value}")
    return "\n".join(results) if results else "No matching notes found"
 
# TOOL_FUNCTIONS'a ekleyin:
TOOL_FUNCTIONS["search_notes"] = search_notes

Lab 5: Interactive File Analyzer

Amaç: Tüm öğrendiklerimizi birleştiren kapsamlı bir interaktif agent.

interactive_agent.py dosyası oluşturun:

"""
Private Agent Lab - Interactive File Analyzer
"""
 
import json
import os
import requests
from datetime import datetime
 
LM_STUDIO_URL = "http://localhost:1234/v1/chat/completions"
MODEL_NAME = "qwen2.5-7b-instruct"
 
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "list_directory",
            "description": "List files and folders in a directory",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string", "description": "Directory path"}},
                "required": ["path"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Read contents of a file",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string", "description": "File path"}},
                "required": ["path"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_file_info",
            "description": "Get detailed information about a file",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string", "description": "File path"}},
                "required": ["path"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "analyze_code",
            "description": "Analyze a Python file and return statistics",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string", "description": "Python file path"}},
                "required": ["path"]
            }
        }
    }
]
 
def list_directory(path: str) -> str:
    try:
        items = os.listdir(path)
        result = []
        for item in items:
            full_path = os.path.join(path, item)
            icon = "📁" if os.path.isdir(full_path) else "📄"
            result.append(f"{icon} {item}")
        return "\n".join(result) if result else "Empty directory"
    except Exception as e:
        return f"Error: {str(e)}"
 
def read_file(path: str) -> str:
    try:
        with open(path, 'r', encoding='utf-8') as f:
            return f.read()
    except Exception as e:
        return f"Error: {str(e)}"
 
def get_file_info(path: str) -> str:
    try:
        stat = os.stat(path)
        size = stat.st_size
        modified = datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M')
        return f"Size: {size} bytes\nModified: {modified}\nPath: {os.path.abspath(path)}"
    except Exception as e:
        return f"Error: {str(e)}"
 
def analyze_code(path: str) -> str:
    try:
        with open(path, 'r', encoding='utf-8') as f:
            content = f.read()
        lines = content.split('\n')
        functions = [l for l in lines if l.strip().startswith('def ')]
        classes = [l for l in lines if l.strip().startswith('class ')]
        imports = [l for l in lines if l.strip().startswith('import ') or l.strip().startswith('from ')]
        return f"""📊 Code Analysis:
- Total lines: {len(lines)}
- Functions: {len(functions)}
- Classes: {len(classes)}
- Imports: {len(imports)}
- Comments: {len([l for l in lines if l.strip().startswith('#')])}"""
    except Exception as e:
        return f"Error: {str(e)}"
 
TOOL_FUNCTIONS = {
    "list_directory": list_directory,
    "read_file": read_file,
    "get_file_info": get_file_info,
    "analyze_code": analyze_code
}
 
def call_llm(messages, tools=None):
    payload = {"model": MODEL_NAME, "messages": messages, "temperature": 0.7}
    if tools:
        payload["tools"] = tools
        payload["tool_choice"] = "auto"
    return requests.post(LM_STUDIO_URL, json=payload, timeout=60).json()
 
def run_agent(user_message):
    messages = [
        {"role": "system", "content": "You are a file system assistant. Use tools to help users explore and analyze files."},
        {"role": "user", "content": user_message}
    ]
    
    response = call_llm(messages, TOOLS)
    assistant_message = response["choices"][0]["message"]
    
    if "tool_calls" in assistant_message and assistant_message["tool_calls"]:
        messages.append(assistant_message)
        for tc in assistant_message["tool_calls"]:
            name = tc["function"]["name"]
            args = json.loads(tc["function"]["arguments"])
            print(f"  🔧 {name}({args})")
            result = TOOL_FUNCTIONS[name](**args)
            messages.append({"role": "tool", "tool_call_id": tc["id"], "name": name, "content": result})
        final = call_llm(messages)
        return final["choices"][0]["message"]["content"]
    return assistant_message.get("content", "")
 
if __name__ == "__main__":
    print("\n🔒 Private File Analyzer Agent")
    print("="*40)
    print("Commands: 'quit' to exit\n")
    
    while True:
        user_input = input("👤 You: ").strip()
        if user_input.lower() in ['quit', 'exit', 'q']:
            break
        if user_input:
            print()
            response = run_agent(user_input)
            print(f"\n🤖 Assistant: {response}\n")

Test Prompt'ları

List files in the current directory
Analyze the simple_agent.py file  
Get info about simple_agent.py

Özet: Private Agent Mimarisi

Öğrendiklerimiz


Sonraki Adımlar

  1. Farklı MCP sunucularını deneyin:

    • @modelcontextprotocol/server-sqlite
    • @modelcontextprotocol/server-fetch
    • @modelcontextprotocol/server-memory
  2. Daha büyük modeller test edin:

    • qwen2.5-14b-instruct
    • llama-3.1-8b-instruct
  3. Kendi MCP sunucunuzu yazın