PHP code example of swisnl / mcp-client

1. Go to this page and download the library: Download swisnl/mcp-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

swisnl / mcp-client example snippets


use Swis\McpClient\Client;

// Create client with SSE transporter
$endpoint = 'https://your-mcp-server.com/sse';
$client = Client::withSse($endpoint);

// Connect to the server
$client->connect(function($initResponse) {
    echo "Connected to server: " . json_encode($initResponse['serverInfo']) . "\n";
});

// List available tools
$tools = $client->listTools();
foreach ($tools->getTools() as $tool) {
    echo "- {$tool->getName()}: {$tool->getDescription()}\n";
    
    // Access tool annotations if available
    if ($annotations = $tool->getAnnotations()) {
        echo "  * Read-only: " . ($annotations->getReadOnlyHint() ? 'Yes' : 'No') . "\n";
        echo "  * Title: " . ($annotations->getTitle() ?? 'N/A') . "\n";
    }
}

// Call a tool
$result = $client->callTool('echo', ['message' => 'Hello World!']);
echo $result->getResult() . "\n";

use Swis\McpClient\Client;

// Create client with a process transporter
[$client, $process] = Client::withProcess('/path/to/mcp-server/binary');

// Connect to the server
$client->connect();

// Use the client...

// Disconnect when done
$client->disconnect();

use Swis\McpClient\Client;

// Create client with StreamableHttp transporter
$endpoint = 'https://your-mcp-server.com/';
$client = Client::withStreamableHttp($endpoint);

// Connect to the server
$client->connect();

// The transporter will automatically manage session IDs from the Mcp-Session-Id header

// Use the client...

// Disconnect when done
$client->disconnect();

use Swis\Agents\Agent;
use Swis\Agents\Mcp\McpConnection;
use Swis\McpClient\Client;
use Swis\Agents\Orchestrator;

$agent = new Agent(
    name: 'Calculator Agent',
    description: 'This Agent can perform arithmetic operations.',
    mcpConnections: [
        new MathMcpConnection(),
    ]
);

$orchestrator = new Orchestrator($agent);
echo $orchestrator
        ->withUserInstruction('What\'s 5 + 5?')
        ->run($agent)

class MathMcpConnection extends McpConnection
{
    public function __construct()
    {
        [$client, $process] = Client::withProcess(
            command: 'node ' . realpath(__DIR__ . '/node_modules/math-mcp/build/index.js'),
        );

        parent::__construct(
            client: $client,
            name: 'Math MCP',
        );
    }
}

use Swis\McpClient\TransporterInterface;
use Swis\McpClient\EventDispatcher;

class CustomTransporter implements TransporterInterface
{
    // Implement t($transporter, $eventDispatcher);

$client->sendRequest(new ListToolsRequest())->then(...);