Sebelum memulai praktik, pastikan Anda telah memahami konsep dasar pada materi kelas AI Agent & PHP di infokoding.

BAB 10

Integrasi MCP (Model Context Protocol)

Mengintegrasikan MCP (Model Context Protocol) ke dalam AI Agent PHP: setup MCP Client, registrasi dan testing tool, serta menjalankan tools melalui protokol MCP standar.

Terakhir diperbarui:

TL;DR (Ringkasan Cepat)

  • MCP Client bertugas sebagai jembatan antara AI Agent dan MCP Server.
  • Tool diregistrasikan ke MCP Server, yang kemudian bisa dipanggil oleh agent mana pun.
  • Komunikasi MCP menggunakan protokol JSON-RPC 2.0 melalui stdio atau HTTP.
  • Satu MCP Server bisa digunakan oleh banyak agent berbeda.

Konsep MCP dalam PHP

Karena ekosistem PHP MCP masih berkembang, kita akan membangun implementasi MCP yang ringan dan fungsional menggunakan prinsip-prinsip protokol MCP.

Membuat MCP Server

<?php

namespace App\MCP;

use App\Tools\ToolInterface;

/**
 * MCP Server sederhana yang menyediakan tools via protokol JSON-RPC.
 */
class McpServer
{
    private array $tools = [];

    public function register(string $name, ToolInterface $tool): self
    {
        $this->tools[$name] = $tool;
        return $this;
    }

    /**
     * List semua tools yang tersedia (untuk MCP list_tools).
     */
    public function listTools(): array
    {
        $definitions = [];
        foreach ($this->tools as $name => $tool) {
            $def = $tool->getDefinition();
            $definitions[] = $def['function'] ?? $def;
        }
        return $definitions;
    }

    /**
     * Eksekusi tool berdasarkan nama (untuk MCP call_tool).
     */
    public function callTool(string $name, array $args): mixed
    {
        if (!isset($this->tools[$name])) {
            throw new \InvalidArgumentException("Tool '$name' tidak terdaftar di MCP Server.");
        }

        return $this->tools[$name]->execute($args);
    }
}

Membuat MCP Client

<?php

namespace App\MCP;

/**
 * MCP Client yang menghubungkan AI Agent dengan MCP Server.
 */
class McpClient
{
    private McpServer $server;

    public function __construct(McpServer $server)
    {
        $this->server = $server;
    }

    /**
     * Dapatkan semua definisi tool dalam format OpenAI Function Calling.
     */
    public function getToolDefinitions(): array
    {
        $tools = $this->server->listTools();
        return array_map(fn($tool) => [
            'type'     => 'function',
            'function' => $tool,
        ], $tools);
    }

    /**
     * Eksekusi tool dari request AI (tool_calls dari OpenAI).
     */
    public function executeToolCall(array $toolCall): array
    {
        $name   = $toolCall['function']['name'];
        $args   = json_decode($toolCall['function']['arguments'], true) ?? [];
        $callId = $toolCall['id'];

        try {
            $result = $this->server->callTool($name, $args);
            return [
                'role'         => 'tool',
                'tool_call_id' => $callId,
                'content'      => json_encode($result, JSON_UNESCAPED_UNICODE),
            ];
        } catch (\Throwable $e) {
            return [
                'role'         => 'tool',
                'tool_call_id' => $callId,
                'content'      => json_encode(['error' => $e->getMessage()]),
            ];
        }
    }
}

Registrasi dan Testing Tool

<?php
// setup-mcp.php
require_once __DIR__ . '/vendor/autoload.php';

use App\MCP\McpServer;
use App\MCP\McpClient;
use App\Tools\WeatherTool;
use App\Tools\DatabaseTool;

// Buat MCP Server
$mcpServer = new McpServer();

// Registrasi tools
$mcpServer
    ->register('get_weather', new WeatherTool())
    ->register('search_user', new DatabaseTool($pdo));

// Buat MCP Client
$mcpClient = new McpClient($mcpServer);

// Tampilkan daftar tools yang tersedia
echo "Tools yang tersedia:\n";
foreach ($mcpClient->getToolDefinitions() as $tool) {
    echo " - " . $tool['function']['name'] . ": " . $tool['function']['description'] . "\n";
}

// Test eksekusi langsung
$testCall = [
    'id'       => 'test-001',
    'function' => [
        'name'      => 'get_weather',
        'arguments' => '{"city": "Jakarta", "unit": "celsius"}',
    ],
];

$result = $mcpClient->executeToolCall($testCall);
echo "\nHasil test tool:\n";
echo json_encode(json_decode($result['content']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

Poin Kunci Bab 10

MCP memberikan struktur yang bersih untuk mengelola tools. Dengan memisahkan MCP Server dan MCP Client, kita mendapatkan arsitektur yang modular — tools bisa ditambah atau diubah tanpa mengubah logika inti Agent.