php-sdk
Официальныйот modelcontextprotocol
The official PHP SDK for Model Context Protocol servers and clients. Maintained in collaboration with The PHP Foundation.
Установка
# Test with MCP InspectorОписание
# MCP PHP SDK The official PHP SDK for Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP servers and clients in PHP. > [!IMPORTANT] > This SDK is currently in active development with ongoing refinement of its architecture and features. While > functional, the API may experience changes as we work toward stabilization. > > If you want to help us stabilize the SDK, please see the [issue tracker](https://github.com/modelcontextprotocol/php-sdk/issues). This project represents a collaboration between [the PHP Foundation](https://thephp.foundation/) and the [Symfony project](https://symfony.com/). It adopts development practices and standards from the Symfony project, including [Coding Standards](https://symfony.com/doc/current/contributing/code/standards.html) and the [Backward Compatibility Promise](https://symfony.com/doc/current/contributing/code/bc.html). Until the first major release, this SDK is considered [experimental](https://symfony.com/doc/current/contributing/code/experimental.html). ## Roadmap **Features** - [ ] Stabilize server component with all needed handlers and functional tests - [ ] Extend documentation, including integration guides for popular frameworks - [ ] Implement Client component - [ ] Support multiple schema versions ## Installation ```bash composer require mcp/sdk ``` ## Quick Start This example demonstrates the most common usage pattern - a STDIO server using attribute discovery. ### 1. Define Your MCP Elements Create a class with MCP capabilities using attributes: ```php <?php namespace App; use Mcp\Capability\Attribute\McpTool; use Mcp\Capability\Attribute\McpResource; class CalculatorElements { /** * Adds two numbers together. * * @param int $a The first number * @param int $b The second number * @return int The sum of the two numbers */ #[McpTool] public function add(int $a, int $b): int { return $a + $b; } /** * Performs basic arithmetic operations. */ #[McpTool(name: 'calculate')] public function calculate(float $a, float $b, string $operation): float|string { return match($operation) { 'add' => $a + $b, 'subtract' => $a - $b, 'multiply' => $a * $b, 'divide' => $b != 0 ? $a / $b : 'Error: Division by zero', default => 'Error: Unknown operation' }; } #[McpResource( uri: 'config://calculator/settings', name: 'calculator_config', mimeType: 'application/json' )] public function getSettings(): array { return ['precision' => 2, 'allow_negative' => true]; } } ``` ### 2. Create the Server Script Create your MCP server: ```php #!/usr/bin/env php <?php declare(strict_types=1); require_once __DIR__ . '/vendor/autoload.php'; use Mcp\Server; use Mcp\Server\Transport\StdioTransport; $server = Server::builder() ->setServerInfo('Calculator Server', '1.0.0') ->setDiscovery(__DIR__, ['.']) ->build(); $transport = new StdioTransport(); $server->run($transport); ``` ### 3. Configure Your MCP Client Add to your client configuration (e.g., Claude Desktop's `mcp.json`): ```json { "mcpServers": { "php-calculator": { "command": "php", "args": ["/absolute/path/to/your/server.php"] } } } ``` ### 4. Test Your Server ```bash # Test with MCP Inspector npx @modelcontextprotocol/inspector php /path/to/server.php # Your AI assistant can now call: # - add: Add two integers # - calculate: Perform arithmetic operations # - Read config://calculator/settings resource ``` ## Key Features ### Attribute-Based Discovery Define MCP elements using PHP attributes with automatic discovery: ```php // Tool with automatic name and description from method #[McpTool] public function generateReport(): string { /* ... */ } // Tool with custom name #[McpTool(name: 'custom_name')] public function myMethod(): string { /* ... */ } // Resource with URI and metadata #[McpResource(uri: 'config://app/settings', mimeType: 'application/json')] public function getConfig(): array { /* ... */ } ``` ### Manual Registration Register capabilities programmatically: ```php $server = Server::builder() ->addTool([MyClass::class, 'myMethod'], 'tool_name') ->addResource([MyClass::class, 'getData'], 'data://config') ->build(); ``` ### Multiple Transport Options **STDIO Transport** (Command-line integration): ```php $transport = new StdioTransport(); $server->run($transport); ``` **HTTP Transport** (Web-based communication): ```php $transport = new StreamableHttpTransport($request, $responseFactory, $streamFactory); $response = $server->run($transport); // Handle $response in your web application ``` ### Session Management By default, the SDK uses in-memory sessions. You can configure different session stores: ```php use Mcp\Server\Session\FileSessionStore; use Mcp\Server\Session\I
Отзывы (0)
Пока нет отзывов. Будьте первым!
Статистика
Информация
Технологии
Похожие серверы
GitHub MCP
Полная интеграция с GitHub API: репозитории, issues, pull requests, actions и многое другое.
Filesystem MCP
Безопасный доступ к файловой системе для чтения, записи и управления файлами с настраиваемыми разрешениями.
Context7 MCP
Доступ к актуальной документации библиотек и фреймворков.
Serena MCP
Мощный MCP сервер для семантической навигации по коду и рефакторинга.