Break Data Silos for LLMs with Model Context Protocol (MCP) – PHP SDK Guide

This article explains the data‑isolation problem facing large language models, introduces the Model Context Protocol (MCP) as a standard bridge to external data sources, and provides a step‑by‑step PHP SDK tutorial—including installation, server and client code, and optional advanced logging—to help developers integrate AI models securely and efficiently.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Break Data Silos for LLMs with Model Context Protocol (MCP) – PHP SDK Guide

Background

Large language models (LLMs) are increasingly powerful but suffer from data‑isolation, limiting their ability to access real‑time information such as weather or personal calendars. Each new data source requires custom integration, creating bottlenecks that prevent LLMs from reaching their full potential.

MCP Overview

Model Context Protocol (MCP) is an open standard released by Anthropic in November 2024. It defines a unified communication protocol between LLMs and external data sources or tools, enabling safe, standardized access to local and remote resources and thus breaking the data‑silo barrier.

Function Calling lets AI models invoke functions; MCP extends this by providing a protocol for seamless API interaction, while an AI Agent can use both to achieve specific goals.

MCP Architecture

MCP Architecture Diagram
MCP Architecture Diagram

MCP Hosts – applications that launch the connection (e.g., Cursor, Claude Desktop, Cline).

MCP Clients – maintain a 1:1 connection to the server inside a host.

MCP Servers – provide context, tools, and prompts via the standardized protocol.

Local Data Sources – files, databases, and APIs on the same machine.

Remote Services – external files, databases, and APIs.

PHP SDK

The PHP SDK implements the full MCP specification, allowing developers to build clients and servers that communicate with LLMs using the protocol. It separates context handling from direct LLM interaction and is based on the official Python SDK.

Overview

Build MCP clients that can connect to any MCP server.

Create MCP servers that expose public prompts, tools, and resources.

Support standard transports such as stdio and Server‑Sent Events (SSE).

Handle all MCP protocol messages and lifecycle events.

Installation

composer require logiscape/mcp-sdk-php

Basic Usage

Create an MCP Server

Example example_server.php shows a minimal server that registers two prompt handlers (list and get) and runs with a ServerRunner:

<?php
require 'vendor/autoload.php';
use Mcp\Server\Server;
use Mcp\Server\ServerRunner;
use Mcp\Types\Prompt;
use Mcp\Types\PromptArgument;
use Mcp\Types\PromptMessage;
use Mcp\Types\ListPromptsResult;
use Mcp\Types\TextContent;
use Mcp\Types\Role;
use Mcp\Types\GetPromptResult;
use Mcp\Types\GetPromptRequestParams;

$server = new Server('example-server');
$server->registerHandler('prompts/list', function($params) {
    $prompt = new Prompt(
        name: 'example-prompt',
        description: 'An example prompt template',
        arguments: [new PromptArgument(name: 'arg1', description: 'Example argument', required: true)]
    );
    return new ListPromptsResult([$prompt]);
});
$server->registerHandler('prompts/get', function(GetPromptRequestParams $params) {
    if ($params->name !== 'example-prompt') {
        throw new \InvalidArgumentException("Unknown prompt: {$params->name}");
    }
    $argValue = $params->arguments ? $params->arguments->arg1 : 'none';
    $prompt = new Prompt(
        name: 'example-prompt',
        description: 'An example prompt template',
        arguments: [new PromptArgument(name: 'arg1', description: 'Example argument', required: true)]
    );
    return new GetPromptResult(
        messages: [new PromptMessage(role: Role::USER, content: new TextContent(text: "Example prompt text with argument: $argValue"))],
        description: 'Example prompt'
    );
});
$initOptions = $server->createInitializationOptions();
$runner = new ServerRunner($server, $initOptions);
$runner->run();
?>

Create an MCP Client

Example example_client.php connects to the server, lists available prompts, and prints their details:

<?php
require 'vendor/autoload.php';
use Mcp\Client\Client;
use Mcp\Client\Transport\StdioServerParameters;
use Mcp\Types\TextContent;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Formatter\LineFormatter;

$logger = new Logger('mcp-client');
$handler = new StreamHandler(__DIR__.'/client_log.txt', Logger::DEBUG);
$dateFormat = "Y-m-d H:i:s";
$output = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%
";
$formatter = new LineFormatter($output, $dateFormat);
$handler->setFormatter($formatter);
$logger->pushHandler($handler);

$serverParams = new StdioServerParameters(
    command: 'php',
    args: ['example_server.php'],
    env: null
);

echo "Creating client
";
$client = new Client($logger);
try {
    echo "Starting to connect
";
    $session = $client->connect(
        commandOrUrl: $serverParams->getCommand(),
        args: $serverParams->getArgs(),
        env: $serverParams->getEnv()
    );
    echo "Starting to get available prompts
";
    $promptsResult = $session->listPrompts();
    if (!empty($promptsResult->prompts)) {
        echo "Available prompts:
";
        foreach ($promptsResult->prompts as $prompt) {
            echo "  - Name: {$prompt->name}
";
            echo "    Description: {$prompt->description}
";
            echo "    Arguments:
";
            if (!empty($prompt->arguments)) {
                foreach ($prompt->arguments as $argument) {
                    $req = $argument->required ? 'required' : 'optional';
                    echo "      - {$argument->name} ({$req}): {$argument->description}
";
                }
            } else {
                echo "      (None)
";
            }
        }
    } else {
        echo "No prompts available.
";
    }
} catch (\Exception $e) {
    echo "Error: {$e->getMessage()}
";
    exit(1);
} finally {
    if (isset($client)) {
        $client->close();
    }
}
?>

Advanced Logging for Debugging

Server with Detailed Logs

Enable comprehensive error reporting and Monolog logging to capture server activity:

<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__.'/php_errors.log');
error_reporting(E_ALL);
require 'vendor/autoload.php';
use Mcp\Server\Server;
use Mcp\Server\ServerRunner;
use Mcp\Types\Prompt;
use Mcp\Types\PromptArgument;
use Mcp\Types\PromptMessage;
use Mcp\Types\ListPromptsResult;
use Mcp\Types\TextContent;
use Mcp\Types\Role;
use Mcp\Types\GetPromptResult;
use Mcp\Types\GetPromptRequestParams;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Formatter\LineFormatter;

$logger = new Logger('mcp-server');
@unlink(__DIR__.'/server_log.txt');
$handler = new StreamHandler(__DIR__.'/server_log.txt', Logger::DEBUG);
$dateFormat = "Y-m-d H:i:s";
$output = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%
";
$formatter = new LineFormatter($output, $dateFormat);
$handler->setFormatter($formatter);
$logger->pushHandler($handler);

$server = new Server('example-server', $logger);
// Register handlers (same as basic example) …
$initOptions = $server->createInitializationOptions();
$runner = new ServerRunner($server, $initOptions, $logger);
try {
    $runner->run();
} catch (\Throwable $e) {
    echo "An error occurred: {$e->getMessage()}
";
    $logger->error('Server run failed', ['exception' => $e]);
}
?>

Client with Detailed Logs

Similar logging setup can be applied to the client to trace request/response cycles.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LLMMCPBackend DevelopmentModel Context ProtocolPHP SDK
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.