PHP code example of politsin / mcp

1. Go to this page and download the library: Download politsin/mcp 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/ */

    

politsin / mcp example snippets




namespace App\Controller;

use Politsin\Mcp\Contract\McpClientInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class McpController extends AbstractController
{
    public function __construct(
        private readonly McpClientInterface $mcpClient,
    ) {}

    #[Route('/api/mcp/tools', methods: ['GET'])]
    public function listTools(): JsonResponse
    {
        $response = $this->mcpClient->listTools();

        if ($response->isSuccess()) {
            return $this->json($response->getResult());
        }

        return $this->json([
            'error' => $response->getError(),
        ], 400);
    }

    #[Route('/api/mcp/call', methods: ['POST'])]
    public function callTool(Request $request): JsonResponse
    {
        $data = json_decode($request->getContent(), true);
        $toolName = $data['tool'] ?? '';
        $arguments = $data['arguments'] ?? [];

        $response = $this->mcpClient->callTool($toolName, $arguments);

        if ($response->isSuccess()) {
            return $this->json($response->getResult());
        }

        return $this->json([
            'error' => $response->getError(),
        ], 400);
    }
}



use Politsin\Mcp\Client\McpClientFactory;
use Politsin\Mcp\Exception\McpException;

$client = McpClientFactory::createHttpClient('https://your-mcp-server.com');

try {
    $response = $client->callTool('unknown_tool');

    if (!$response->isSuccess()) {
        echo "Ошибка: " . $response->getErrorMessage() . "\n";
        echo "Код: " . $response->getErrorCode() . "\n";
    }
} catch (McpException $e) {
    echo "Исключение: " . $e->getMessage() . "\n";
    echo "Код: " . $e->getErrorCode() . "\n";
}

interface ToolInterface {
  public function getName(): string;
  public function getDescription(): string;
  public function getInputSchema(): array; // JSON Schema object
  public function execute(array $arguments): mixed;
}