Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 5 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,16 @@ Until the first major release, this SDK is considered

Features
- [x] Bring back PHP-MCP examples
- [ ] Glue handler, registry and reference handlers
- [ ] Revive `ServerBuilder`
- [ ] Revive transports
- [ ] Streamable Transport https://github.com/modelcontextprotocol/php-sdk/issues/7
- [ ] Http/SSE-based Transport https://github.com/modelcontextprotocol/php-sdk/issues/8
- [x] Glue handler, registry and reference handlers
- [x] Revive `ServerBuilder`
- [x] Revive transports
- [x] Streamable Transport https://github.com/modelcontextprotocol/php-sdk/issues/7
- [ ] ~~Http/SSE-based Transport https://github.com/modelcontextprotocol/php-sdk/issues/8~~
- [ ] Support pagination
- [ ] Support Schema validation
- [ ] Support multiple versions of the MCP specification https://github.com/modelcontextprotocol/php-sdk/issues/14
- [ ] (Re-)Implement missing Notification & Request Handlers https://github.com/modelcontextprotocol/php-sdk/issues/9

---

Examples working
- [x] 01-discovery-stdio-calculator
- [ ] 02-discovery-http-userprofile
- [x] 03-manual-registration-stdio
- [ ] 04-combined-registration-http
- [ ] 05-stdio-env-variables
- [ ] 06-custom-dependencies-stdio
- [ ] 07-complex-tool-schema-http
- [ ] 08-schema-showcase-streamable
- [ ] 09-standalone-cli

## Installation

```bash
Expand Down
2 changes: 1 addition & 1 deletion examples/01-discovery-stdio-calculator/McpElements.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
/**
* @phpstan-type Config array{precision: int, allow_negative: bool}
*/
class McpElements
final class McpElements
{
/**
* @var Config
Expand Down
24 changes: 17 additions & 7 deletions examples/02-discovery-http-userprofile/McpElements.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,24 @@
use Mcp\Capability\Attribute\McpTool;
use Psr\Log\LoggerInterface;

class McpElements
/**
* @phpstan-type User array{name: string, email: string, role: string}
*/
final class McpElements
{
// Simulate a simple user database
/**
* Simulate a simple user database.
*
* @var array<int, User>
*/
private array $users = [
'101' => ['name' => 'Alice', 'email' => '[email protected]', 'role' => 'admin'],
'102' => ['name' => 'Bob', 'email' => '[email protected]', 'role' => 'user'],
'103' => ['name' => 'Charlie', 'email' => '[email protected]', 'role' => 'user'],
];

public function __construct(
private LoggerInterface $logger,
private readonly LoggerInterface $logger,
) {
$this->logger->debug('HttpUserProfileExample McpElements instantiated.');
}
Expand All @@ -38,7 +45,7 @@ public function __construct(
*
* @param string $userId the ID of the user (from URI)
*
* @return array user profile data
* @return User user profile data
*
* @throws McpServerException if the user is not found
*/
Expand All @@ -64,7 +71,7 @@ public function getUserProfile(
/**
* Retrieves a list of all known user IDs.
*
* @return array list of user IDs
* @return int[] list of user IDs
*/
#[McpResource(
uri: 'user://list/ids',
Expand All @@ -86,7 +93,7 @@ public function listUserIds(): array
* @param string $userId the ID of the user to message
* @param string|null $customMessage an optional custom message part
*
* @return array status of the operation
* @return array<string, bool|string> status of the operation
*/
#[McpTool(name: 'send_welcome')]
public function sendWelcomeMessage(string $userId, ?string $customMessage = null): array
Expand All @@ -106,6 +113,9 @@ public function sendWelcomeMessage(string $userId, ?string $customMessage = null
return ['success' => true, 'message_sent' => $message];
}

/**
* @return array<string, bool|string>
*/
#[McpTool(name: 'test_tool_without_params')]
public function testToolWithoutParams(): array
{
Expand All @@ -118,7 +128,7 @@ public function testToolWithoutParams(): array
* @param string $userId the user ID to generate the bio for
* @param string $tone Desired tone (e.g., 'formal', 'casual').
*
* @return array prompt messages
* @return array<string, string>[] prompt messages
*
* @throws McpServerException if user not found
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@

use Mcp\Capability\Prompt\Completion\ProviderInterface;

class UserIdCompletionProvider implements ProviderInterface
final class UserIdCompletionProvider implements ProviderInterface
{
private const AVAILABLE_USER_IDS = ['101', '102', '103'];

public function getCompletions(string $currentValue): array
{
$availableUserIds = ['101', '102', '103'];

return array_filter($availableUserIds, fn (string $userId) => str_contains($userId, $currentValue));
return array_filter(self::AVAILABLE_USER_IDS, fn (string $userId) => str_contains($userId, $currentValue));
}
}
2 changes: 1 addition & 1 deletion examples/02-discovery-http-userprofile/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function (float $a, float $b, string $operation = 'add'): array {
function (): array {
$memoryUsage = memory_get_usage(true);
$memoryPeak = memory_get_peak_usage(true);
$uptime = time() - $_SERVER['REQUEST_TIME_FLOAT'] ?? time();
$uptime = time() - ($_SERVER['REQUEST_TIME_FLOAT'] ?? time());
$serverSoftware = $_SERVER['SERVER_SOFTWARE'] ?? 'CLI';

return [
Expand Down
6 changes: 3 additions & 3 deletions examples/03-manual-registration-stdio/SimpleHandlers.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

use Psr\Log\LoggerInterface;

class SimpleHandlers
final class SimpleHandlers
{
private string $appVersion = '1.0-manual';

Expand Down Expand Up @@ -54,7 +54,7 @@ public function getAppVersion(): string
*
* @param string $userName the name of the user
*
* @return array the prompt messages
* @return array<string, string>[] the prompt messages
*/
public function greetingPrompt(string $userName): array
{
Expand All @@ -70,7 +70,7 @@ public function greetingPrompt(string $userName): array
*
* @param string $itemId the ID of the item
*
* @return array item details
* @return array<string, string> item details
*/
public function getItemDetails(string $itemId): array
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool;

class DiscoveredElements
final class DiscoveredElements
{
/**
* A tool discovered via attributes.
Expand Down
4 changes: 2 additions & 2 deletions examples/04-combined-registration-http/ManualHandlers.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@

use Psr\Log\LoggerInterface;

class ManualHandlers
final class ManualHandlers
{
public function __construct(
private LoggerInterface $logger,
private readonly LoggerInterface $logger,
) {
}

Expand Down
2 changes: 1 addition & 1 deletion examples/04-combined-registration-http/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
chdir(__DIR__);

use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Mcp\CombinedHttpExample\Manual\ManualHandlers;
use Mcp\Example\CombinedHttpExample\ManualHandlers;
use Mcp\Server;
use Mcp\Server\Session\FileSessionStore;
use Mcp\Server\Transport\StreamableHttpTransport;
Expand Down
4 changes: 2 additions & 2 deletions examples/05-stdio-env-variables/EnvToolHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@

use Mcp\Capability\Attribute\McpTool;

class EnvToolHandler
final class EnvToolHandler
{
/**
* Performs an action that can be modified by an environment variable.
* The MCP client should set 'APP_MODE' in its 'env' config for this server.
*
* @param string $input some input data
*
* @return array the result, varying by APP_MODE
* @return array<string, string|int> the result, varying by APP_MODE
*/
#[McpTool(name: 'process_data_by_mode')]
public function processData(string $input): array
Expand Down
23 changes: 13 additions & 10 deletions examples/06-custom-dependencies-stdio/McpTaskHandlers.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,19 @@

use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool;
use Mcp\DependenciesStdioExample\Services\StatsServiceInterface;
use Mcp\DependenciesStdioExample\Services\TaskRepositoryInterface;
use Mcp\Example\DependenciesStdioExample\Service\StatsServiceInterface;
use Mcp\Example\DependenciesStdioExample\Service\TaskRepositoryInterface;
use Psr\Log\LoggerInterface;

class McpTaskHandlers
/**
* @phpstan-import-type Task from TaskRepositoryInterface
*/
final class McpTaskHandlers
{
public function __construct(
private TaskRepositoryInterface $taskRepo,
private StatsServiceInterface $statsService,
private LoggerInterface $logger,
private readonly TaskRepositoryInterface $taskRepo,
private readonly StatsServiceInterface $statsService,
private readonly LoggerInterface $logger,
) {
$this->logger->info('McpTaskHandlers instantiated with dependencies.');
}
Expand All @@ -33,7 +36,7 @@ public function __construct(
* @param string $userId the ID of the user
* @param string $description the task description
*
* @return array the created task details
* @return Task the created task details
*/
#[McpTool(name: 'add_task')]
public function addTask(string $userId, string $description): array
Expand All @@ -48,7 +51,7 @@ public function addTask(string $userId, string $description): array
*
* @param string $userId the ID of the user
*
* @return array a list of tasks
* @return Task[] a list of tasks
*/
#[McpTool(name: 'list_user_tasks')]
public function listUserTasks(string $userId): array
Expand All @@ -63,7 +66,7 @@ public function listUserTasks(string $userId): array
*
* @param int $taskId the ID of the task to complete
*
* @return array status of the operation
* @return array<string, mixed> status of the operation
*/
#[McpTool(name: 'complete_task')]
public function completeTask(int $taskId): array
Expand All @@ -77,7 +80,7 @@ public function completeTask(int $taskId): array
/**
* Provides current system statistics.
*
* @return array system statistics
* @return array<string, int> system statistics
*/
#[McpResource(uri: 'stats://system/overview', name: 'system_stats', mimeType: 'application/json')]
public function getSystemStatistics(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@

use Psr\Log\LoggerInterface;

class InMemoryTaskRepository implements TaskRepositoryInterface
/**
* @phpstan-import-type Task from TaskRepositoryInterface
*/
final class InMemoryTaskRepository implements TaskRepositoryInterface
{
/**
* @var array<int, Task>
*/
private array $tasks = [];

private int $nextTaskId = 1;

private LoggerInterface $logger;

public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
public function __construct(
private readonly LoggerInterface $logger,
) {
// Add some initial tasks
$this->addTask('user1', 'Buy groceries');
$this->addTask('user1', 'Write MCP example');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,8 @@

interface StatsServiceInterface
{
/**
* @return array<string, int>
*/
public function getSystemStats(): array;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@

namespace Mcp\Example\DependenciesStdioExample\Service;

class SystemStatsService implements StatsServiceInterface
final class SystemStatsService implements StatsServiceInterface
{
private TaskRepositoryInterface $taskRepository;

public function __construct(TaskRepositoryInterface $taskRepository)
{
$this->taskRepository = $taskRepository;
public function __construct(
private readonly TaskRepositoryInterface $taskRepository,
) {
}

public function getSystemStats(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,24 @@

namespace Mcp\Example\DependenciesStdioExample\Service;

/**
* @phpstan-type Task array{id: int, userId: string, description: string, completed: bool, createdAt: string}
*/
interface TaskRepositoryInterface
{
/**
* @return Task
*/
public function addTask(string $userId, string $description): array;

/**
* @return Task[]
*/
public function getTasksForUser(string $userId): array;

/**
* @return Task[]
*/
public function getAllTasks(): array;

public function completeTask(int $taskId): bool;
Expand Down
13 changes: 8 additions & 5 deletions examples/06-custom-dependencies-stdio/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,22 @@
require_once dirname(__DIR__).'/bootstrap.php';
chdir(__DIR__);

use Mcp\DependenciesStdioExample\Services;
use Mcp\Example\DependenciesStdioExample\Service\InMemoryTaskRepository;
use Mcp\Example\DependenciesStdioExample\Service\StatsServiceInterface;
use Mcp\Example\DependenciesStdioExample\Service\SystemStatsService;
use Mcp\Example\DependenciesStdioExample\Service\TaskRepositoryInterface;
use Mcp\Server;
use Mcp\Server\Transport\StdioTransport;

logger()->info('Starting MCP Custom Dependencies (Stdio) Server...');

$container = container();

$taskRepo = new Services\InMemoryTaskRepository(logger());
$container->set(Services\TaskRepositoryInterface::class, $taskRepo);
$taskRepo = new InMemoryTaskRepository(logger());
$container->set(TaskRepositoryInterface::class, $taskRepo);

$statsService = new Services\SystemStatsService($taskRepo);
$container->set(Services\StatsServiceInterface::class, $statsService);
$statsService = new SystemStatsService($taskRepo);
$container->set(StatsServiceInterface::class, $statsService);

$server = Server::make()
->setServerInfo('Task Manager Server', '1.0.0')
Expand Down
Loading