Site icon Efficient Coder

PHP MCP SDK: Streamline AI Integration with Model Context Protocol Implementation

Understanding the MCP SDK for PHP: A Guide to Integrating Large Language Models

In the world of artificial intelligence, large language models (LLMs) are transforming how developers build applications. However, integrating these models into your projects can be challenging, especially when it comes to providing them with the right context to generate meaningful responses. This is where the Model Context Protocol (MCP) and its PHP implementation, the MCP SDK for PHP, come into play. This blog post will guide you through what the MCP SDK for PHP is, how to use it, and why it’s a valuable tool for developers working with LLMs. Designed for readers with at least a college-level education, this article assumes some technical familiarity but explains concepts clearly and practically.

We’ll cover everything from installation to creating MCP servers and clients, with detailed examples straight from the official documentation. By the end, you’ll have a solid understanding of how to leverage this tool in your PHP projects. Let’s dive in.


What is the MCP SDK for PHP?

The Model Context Protocol (MCP) is a standardized way for applications to supply context—such as resources, prompts, or tools—to large language models. It separates the task of preparing this context from the actual interaction with the LLM, making the process more organized and reusable. The MCP SDK for PHP brings this protocol to the PHP ecosystem, allowing developers to build both clients and servers that follow MCP rules.

Why Use It?

Imagine you’re building an application that relies on an LLM to generate text, answer questions, or perform tasks. Without a structured way to feed it information, you’d have to manually handle every detail of the interaction. The MCP SDK for PHP simplifies this by providing a framework to:

  • Create servers that offer context (like prompts or resources) to the LLM.
  • Build clients that connect to these servers and retrieve what’s needed.
  • Standardize communication using methods like stdio or SSE.

This SDK is based on the official Python SDK for MCP and is tailored for PHP developers working on cutting-edge AI solutions. It’s particularly useful if you’re integrating LLMs into web applications, command-line tools, or other PHP-based systems.


Installing the MCP SDK for PHP

Before you can start coding, you need to install the SDK. It’s available through Composer, the dependency manager for PHP, which makes the process straightforward.

Step-by-Step Installation

  1. Open your terminal and navigate to your project directory.

  2. Run this command:

    composer require logiscape/mcp-sdk-php
    
  3. Wait for Composer to download and install the package along with its dependencies.

System Requirements

To ensure everything works smoothly, your system must meet these minimum requirements:

  • PHP 8.1 or higher: The SDK uses modern PHP features, so an up-to-date version is essential.
  • ext-curl: This extension is required for network-related functionality.
  • ext-pcntl (optional): Recommended if you’re running the SDK in a command-line (CLI) environment, as it enhances process control.

Once installed, you’re ready to start building. Let’s explore how to create an MCP server.


Creating an MCP Server with the SDK

An MCP server is the component that provides context to the LLM. It can expose things like a list of prompts, resources, or tools that the model can use. In this section, we’ll walk through building a simple server that offers prompts, using an example directly from the documentation.

Example: A Basic MCP Server

Here’s the full code to create a server that handles prompt-related requests:

<?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;

// Create a server instance
$server = new Server('example-server');

// Handler for listing available prompts
$server->registerHandler('prompts/list'function($params) {
    $prompt = new Prompt(
        name: 'example-prompt',
        description: 'An example prompt template',
        arguments: [
            new PromptArgument(
                name: 'arg1',
                description: 'An example argument',
                required: true
            )
        ]
    );
    return new ListPromptsResult([$prompt]);
});

// Handler for retrieving a specific prompt
$server->registerHandler('prompts/get'function(GetPromptRequestParams $params) {
    $name = $params->name;
    $arguments = $params->arguments;

    if ($name !== 'example-prompt') {
        throw new \InvalidArgumentException("Unknown prompt: {$name}");
    }

    // Get the argument value safely
    $argValue = $arguments ? $arguments->arg1 : 'none';

    $prompt = new Prompt(
        name: 'example-prompt',
        description: 'An example prompt template',
        arguments: [
            new PromptArgument(
                name: 'arg1',
                description: 'An 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'
    );
});

// Set up and run the server
$initOptions = $server->createInitializationOptions();
$runner = new ServerRunner($server, $initOptions);
$runner->run();

Save this file as example_server.php. Let’s break down what’s happening here.

How It Works

  1. Server Setup:

    • We create a new Server instance named 'example-server'. This identifies the server within the MCP ecosystem.
  2. Registering Handlers:

    • The server uses handlers to respond to specific requests. Here, we define two:
      • 'prompts/list': Returns a list of available prompts. In this case, it’s just one prompt called 'example-prompt' with a required argument 'arg1'.
      • 'prompts/get': Retrieves a specific prompt by name. It checks if the requested prompt is 'example-prompt', fetches the value of 'arg1' (or defaults to 'none' if missing), and returns a message incorporating that value.
  3. Running the Server:

    • The ServerRunner class starts the server with default initialization options. Once running, it listens for client requests via stdio or other supported transports.

This server is now ready to provide prompt data to any MCP client that connects to it. Next, we’ll build a client to interact with this server.


Building an MCP Client

An MCP client connects to a server to access its resources. In this example, we’ll create a client that connects to example_server.php and lists its available prompts.

Example: A Basic MCP Client

Here’s the code:

<?php

require 'vendor/autoload.php';

use Mcp\Client\Client;
use Mcp\Client\Transport\StdioServerParameters;
use Mcp\Types\TextContent;

// Define server connection parameters
$serverParams = new StdioServerParameters(
    command: 'php',           // The executable
    args: ['example_server.php'], // Path to the server script
    env: null                 // Optional environment variables
);

// Create a client instance
$client = new Client();

try {
    echo("Starting connection\n");
    // Connect to the server
    $session = $client->connect(
        commandOrUrl: $serverParams->getCommand(),
        args: $serverParams->getArgs(),
        env: $serverParams->getEnv()
    );

    echo("Starting to list available prompts\n");
    // Get the list of prompts
    $promptsResult = $session->listPrompts();

    // Display the prompts
    if (!empty($promptsResult->prompts)) {
        echo "Available prompts:\n";
        foreach ($promptsResult->prompts as $prompt) {
            echo "  - Name: " . $prompt->name . "\n";
            echo "    Description: " . $prompt->description . "\n";
            echo "    Arguments:\n";
            if (!empty($prompt->arguments)) {
                foreach ($prompt->arguments as $argument) {
                    echo "      - " . $argument->name . " (" . ($argument->required ? "required" : "optional") . "): " . $argument->description . "\n";
                }
            } else {
                echo "      (none)\n";
            }
        }
    } else {
        echo "No prompts available.\n";
    }

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
} finally {
    // Clean up by closing the connection
    if (isset($client)) {
        $client->close();
    }
}

Save this as example_client.php. To run it, use:

php example_client.php

How It Works

  1. Connection Setup:

    • The StdioServerParameters class specifies how to launch the server (using php to run example_server.php).
  2. Client Initialization:

    • A new Client instance is created to manage the connection.
  3. Connecting and Querying:

    • The client connects to the server and calls listPrompts() to retrieve the prompt list. It then prints the details of each prompt, including names, descriptions, and arguments.
  4. Error Handling:

    • The code includes a try-catch block to handle errors (e.g., if the server isn’t running) and a finally block to ensure the connection closes properly.

When you run this, you’ll see output like:

Starting connection
Starting to list available prompts
Available prompts:
  - Name: example-prompt
    Description: An example prompt template
    Arguments:
      - arg1 (required): An example argument

This demonstrates a working client-server interaction using the MCP SDK for PHP.


Exploring Advanced Features

The SDK offers additional tools to make development easier. Here are two key features from the documentation.

Logging for Debugging

When building or troubleshooting your MCP application, detailed logs can be a lifesaver. The SDK supports logging on both the client and server sides. While the documentation doesn’t provide a specific PHP example, it notes that you can enable verbose logging to track requests, responses, and errors. For instance:

  • On the server, you could log incoming requests in your handlers.
  • On the client, you could log connection attempts or prompt results.

This feature is especially helpful during development to ensure everything works as expected.

Using the MCP Web Client

The SDK includes a web-based client in the webclient directory, designed for testing your MCP server in a browser. It’s a practical tool for developers who want a visual way to interact with their server.

Setting It Up

  1. Copy the contents of the webclient directory to your web server’s public directory (e.g., public_html on cPanel).
  2. Ensure the MCP SDK is installed in the same directory by running:
    composer require logiscape/mcp-sdk-php
    
  3. Open your browser and navigate to index.php.

Using the Web Client

  • In the interface, enter php in the Command field and test_server.php in the Arguments field.
  • Click Connect to Server.
  • You can now test prompts, tools, or resources exposed by your server.

The web client also includes a debug panel showing the JSON-RPC messages exchanged between the client and server, which is great for understanding the communication flow.

Important Notes

  • This tool is for development and testing only. It’s not secure for production use without additional safeguards.
  • In typical PHP web hosting, long-running processes aren’t supported, so the web client starts a new connection for each request and closes it afterward.

Wrapping Up

The MCP SDK for PHP is a powerful tool for integrating large language models into your PHP applications. By following the Model Context Protocol, it provides a structured way to manage context, making your AI projects more efficient and scalable. In this guide, we’ve covered:

  • Installation: How to get the SDK up and running with Composer.
  • MCP Server: Building a server to supply prompts to an LLM.
  • MCP Client: Creating a client to connect and retrieve data.
  • Advanced Tools: Using logging and the web client for development.

Whether you’re working on a web app, a CLI tool, or an experimental AI project, this SDK offers a solid starting point. It’s designed for developers who want to explore LLMs without getting bogged down in the complexities of context management.

For more details, check out the official MCP documentation. Ready to get started? Install the SDK, try the examples, and see how it fits into your next project.


This article is based entirely on the provided mcp-sdk-php.md document, offering a clear, practical, and detailed explanation for technically inclined readers. It’s structured to be easy to follow while providing real value through actionable steps and examples.

Exit mobile version