### Quick Start: Create an MCP Server with Tools and Resources Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/README.md This example demonstrates how to create an MCP server, register an addition tool, a dynamic resource, and a prompt. It then starts the server using stdio transport. Ensure you have the necessary autoloader included. ```php registerTool('add', [ 'properties' => [ 'a' => ['type' => 'number'], 'b' => ['type' => 'number'] ], 'required' => ['a', 'b'] ], function(array $params) { $a = $params['a']; $b = $params['b']; return [ 'content' => [ [ 'type' => 'text', 'text' => (string)($a + $b) ] ] ]; }); // Add a dynamic greeting resource $template = new ResourceTemplate('greeting://{name}'); $server->registerResourceTemplate('personalized-greeting', $template, function($uri, $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; }); // Add a prompt for generating introductions $server->registerPrompt('introduction', [ 'properties' => [ 'name' => ['type' => 'string'], 'profession' => ['type' => 'string'] ], 'required' => ['name', 'profession'] ], function(array $params) { return [ 'messages' => [ [ 'role' => 'user', 'content' => [ 'type' => 'text', 'text' => "Please introduce {$params['name']}, who works as a {$params['profession']}." ] ] ] ]; }); // Start the server using stdio transport $transport = new StdioTransport(); $server->connect($transport); ``` -------------------------------- ### Complete MCP Server Example in PHP Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/server-implementation.md This snippet shows a full server setup. Use this as a starting point for your own MCP server implementations. It requires the MCP PHP SDK to be installed via Composer. ```php true, 'listChanged' => true ], tools: [ 'list' => true, 'listChanged' => true ], prompts: [ 'list' => true ] ); // Create an MCP server with capabilities $server = new McpServer( name: 'Example Server', version: '1.0.0', capabilities: $capabilities, instructions: 'This server provides example resources and tools.', logger: $logger ); // Add resources $server->registerResource('greeting', 'greeting://hello', [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ]); $greetingTemplate = new ResourceTemplate('greeting://{name}'); $server->registerResourceTemplate('personalized-greeting', $greetingTemplate, function($uri, $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; }); // Add tools $server->registerTool('add', [ 'properties' => [ 'a' => ['type' => 'number'], 'b' => ['type' => 'number'] ], 'required' => ['a', 'b'], 'description' => 'Adds two numbers together' ], function($params) { $result = $params['a'] + $params['b']; return [ 'content' => [ [ 'type' => 'text', 'text' => (string)$result ] ] ]; }); // Add prompts $server->registerPrompt('introduction', [ 'properties' => [ 'name' => ['type' => 'string'], 'profession' => ['type' => 'string'] ], 'required' => ['name', 'profession'], 'description' => 'Creates an introduction message' ], function($params) { return [ 'messages' => [ [ 'role' => 'user', 'content' => [ 'type' => 'text', 'text' => "Please introduce {$params['name']}, who works as a {$params['profession']}.." ] ] ] ]; }); // Connect to stdio transport $transport = new StdioTransport(); $server->connect($transport); // The server is now running and will process messages from stdin ``` -------------------------------- ### Complete MCP Client Example in PHP Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/client-implementation.md This example demonstrates the full lifecycle of an MCP client, from initialization to interacting with server resources, tools, and prompts. Ensure the SDK is installed via Composer and the server endpoint is correctly configured. ```php true ], tools: [ 'list' => true ], prompts: [ 'list' => true ] ); // Create a client $client = new McpClient( name: 'Example Client', version: '1.0.0', logger: $logger ); try { // Connect to an MCP server $transport = new HttpTransport('https://example.com/mcp'); $client->connect($transport); // Initialize the connection $result = $client->initialize($capabilities); // Check server capabilities echo "Connected to server: {$result->server->name} v{$result->server->version}\n"; echo "Protocol version: {$result->protocolVersion}\n"; // Work with resources $resources = $client->listResources(); echo "Available resources: " . count($resources) . "\n"; $content = $client->getResource('greeting://hello'); echo "Greeting: {$content->text}\n"; // Work with tools $tools = $client->listTools(); echo "Available tools: " . count($tools) . "\n"; $addResult = $client->callTool('add', ['a' => 10, 'b' => 5]); echo "10 + 5 = {$addResult->content[0]->text}\n"; // Work with prompts $prompts = $client->listPrompts(); echo "Available prompts: " . count($prompts) . "\n"; $promptResult = $client->getPrompt('introduction', [ 'name' => 'Jane Smith', 'profession' => 'data scientist' ]); echo "Introduction prompt: {$promptResult->messages[0]->content[0]->text}\n"; } catch (Exception $e) { echo "Error: {$e->getMessage()}\n"; } finally { // Clean up if (isset($client)) { $client->shutdown(); } } ``` -------------------------------- ### Basic MCP Client Setup in PHP Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/client-implementation.md Demonstrates the essential steps for creating an MCP client, connecting to a server via HTTP, initializing the connection with capabilities, and processing the server's response. Ensure you have the SDK installed via Composer. ```php true ], tools: [ 'list' => true ], prompts: [ 'list' => true ] ); // Create a client $client = new McpClient( name: 'Example Client', version: '1.0.0', logger: $logger ); // Connect to an MCP server $transport = new HttpTransport('https://example.com/mcp'); $client->connect($transport); // Initialize the connection $result = $client->initialize($capabilities); // Check if initialization was successful if ($result->success) { echo "Connected to server: {$result->server->name} v{$result->server->version}\n"; echo "Protocol version: {$result->protocolVersion}\n"; // Access server capabilities $serverCapabilities = $result->capabilities; echo "Server supports resources: " . json_encode($serverCapabilities->resources) . "\n"; echo "Server supports tools: " . json_encode($serverCapabilities->tools) . "\n"; echo "Server supports prompts: " . json_encode($serverCapabilities->prompts) . "\n"; } else { echo "Failed to initialize connection\n"; } // Clean up when done $client->shutdown(); ``` -------------------------------- ### Basic Server Setup Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/server-implementation.md Sets up a new MCP server with specified name, version, capabilities, and instructions. It then connects the server to a standard input/output transport. Ensure the MCP SDK is installed via Composer. ```php true, 'listChanged' => true ], tools: [ 'list' => true, 'listChanged' => true ], prompts: [ 'list' => true ] ); // Create an MCP server with capabilities $server = new McpServer( name: 'Example Server', version: '1.0.0', capabilities: $capabilities, instructions: 'This server provides example resources and tools.', logger: $logger ); // Connect to stdio transport $transport = new StdioTransport(); $server->connect($transport); // The server is now running and will process messages from stdin ``` -------------------------------- ### Install Xdebug using PECL Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/troubleshooting/debugging-techniques.md Use PECL to install the Xdebug extension. This is the first step in setting up Xdebug for PHP. ```bash pecl install xdebug ``` -------------------------------- ### Install Dependencies Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Install project dependencies using Composer. ```bash # Install dependencies composer install ``` -------------------------------- ### Install MCP PHP SDK using Composer Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/README.md Use this command to install the SDK. Requires PHP 8.1 or higher. ```bash composer require eduardocruz/mcp-php-sdk ``` -------------------------------- ### Register Simple Tool with Parameters Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/README.md Register a tool that allows LLMs to perform actions. This example defines a tool to calculate BMI, requiring 'weightKg' and 'heightM' as parameters. ```php $server->registerTool( 'calculate-bmi', [ 'properties' => [ 'weightKg' => ['type' => 'number'], 'heightM' => ['type' => 'number'] ], 'required' => ['weightKg', 'heightM'] ], function(array $params) { $weightKg = $params['weightKg']; $heightM = $params['heightM']; $bmi = $weightKg / ($heightM * $heightM); return [ 'content' => [ [ 'type' => 'text', 'text' => (string)$bmi ] ] ]; } ); ``` -------------------------------- ### List and Get Prompts Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/client-implementation.md Demonstrates how to list available prompts and then retrieve a specific prompt with its associated parameters. The prompt name and parameters must be valid. ```php // List available prompts $prompts = $client->listPrompts(); echo "Available prompts:\n"; foreach ($prompts as $prompt) { echo "- {$prompt->name}: {$prompt->description}\n"; } // Get a prompt $promptParams = [ 'name' => 'John Doe', 'profession' => 'software engineer' ]; $promptResult = $client->getPrompt('introduction', $promptParams); echo "Prompt message: {$promptResult->messages[0]->content[0]->text}\n"; ``` -------------------------------- ### Create a Basic MCP Server Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/getting-started.md This snippet shows how to initialize an MCP server, register static and dynamic resources, and a tool. It then connects to a StdioTransport to start processing messages. ```php registerResourceCapabilities(); // Register a static resource $server->registerResource('greeting', 'greeting://hello', [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ]); // Register a dynamic resource with a template $greetingTemplate = new ResourceTemplate('greeting://{name}'); $server->registerResourceTemplate('personalized-greeting', $greetingTemplate, function($uri, $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; }); // Register a simple tool $server->registerTool('add', [ 'properties' => [ 'a' => ['type' => 'number'], 'b' => ['type' => 'number'] ], 'required' => ['a', 'b'] ], function($params) { $result = $params['a'] + $params['b']; return [ 'content' => [ [ 'type' => 'text', 'text' => (string)$result ] ] ]; }); // Connect to stdio transport $transport = new StdioTransport(); $server->connect($transport); // The server is now running and will process messages from stdin // This is a blocking call ``` -------------------------------- ### Check PHP Code Quality (Cursor Example) Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/examples/README.md Example command to request code quality checks on PHP code through an LLM. This helps identify style issues and potential code smells. ```php function processData($data, $option1, $option2, $option3, $option4, $option5, $option6) { // Function with too many parameters return $data; } ``` -------------------------------- ### Verify PHP MCP SDK Installation Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/installation.md A simple PHP script to verify that the SDK has been installed correctly. Run this script using `php test-mcp.php`. ```php [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ] ]; ``` -------------------------------- ### Analyze PHP Function for Errors (Cursor Example) Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/examples/README.md Example command to ask an LLM connected via MCP to analyze a PHP function for errors using PHPStan. This demonstrates a practical use case for static analysis integration. ```php function add($a, $b) { return $a + $c; // Undefined variable $c } ``` -------------------------------- ### Register Prompt Template Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/README.md Register a reusable prompt template that helps LLMs formulate requests. This example defines a prompt for introducing a person, requiring 'name' and 'profession' as parameters. ```php $server->registerPrompt( 'introduction', [ 'properties' => [ 'name' => ['type' => 'string'], 'profession' => ['type' => 'string'] ], 'required' => ['name', 'profession'] ], function(array $params) { return [ 'messages' => [ [ 'role' => 'user', 'content' => [ 'type' => 'text', 'text' => "Please introduce {$params['name']}, who works as a {$params['profession']}." ] ] ] ]; } ); ``` -------------------------------- ### PHP Unit Test Structure Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Demonstrates a typical unit test class structure using PHPUnit, including setup, test methods following the Arrange-Act-Assert pattern, and exception testing. ```php instance = new YourClassUnderTest(); } public function testMethodBehavior(): void { // Arrange $input = 'test input'; // Act $result = $this->instance->method($input); // Assert $this->assertEquals('expected', $result); } public function testErrorHandling(): void { $this->expectException(SomeException::class); $this->expectExceptionMessage('Expected error message'); $this->instance->methodThatThrows(); } } ``` -------------------------------- ### Register Static Resource Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/README.md Register a static resource to expose simple, unchanging data to LLMs. This is akin to a GET endpoint that provides information without side effects. ```php $server->registerResource('greeting', 'greeting://hello', [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ]); ``` -------------------------------- ### List and Call Tools Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/client-implementation.md Shows how to list available tools and then call a tool with simple or complex parameters. Ensure the tool names and parameters match the available tool definitions. ```php // List available tools $tools = $client->listTools(); echo "Available tools:\n"; foreach ($tools as $tool) { echo "- {$tool->name}: {$tool->description}\n"; } // Call a tool $params = [ 'a' => 5, 'b' => 3 ]; $result = $client->callTool('add', $params); echo "Tool result: {$result->content[0]->text}\n"; // Call a more complex tool $weatherParams = [ 'location' => 'New York', 'units' => 'metric' ]; $weatherResult = $client->callTool('fetchWeather', $weatherParams); echo "Weather data: " . json_encode($weatherResult->content[0]->data) . "\n"; ``` -------------------------------- ### List and Read Resources Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/client-implementation.md Demonstrates how to list all available resources and then read the content of a specific resource or a dynamic resource. ```php // List available resources $resources = $client->listResources(); echo "Available resources:\n"; foreach ($resources as $resource) { echo "- {$resource->name}: {$resource->uri}\n"; } // Read a resource $resourceUri = 'greeting://hello'; $content = $client->getResource($resourceUri); echo "Resource content: {$content->text}\n"; // Read a dynamic resource $dynamicUri = 'greeting://John'; $content = $client->getResource($dynamicUri); echo "Dynamic resource content: {$content->text}\n"; ``` -------------------------------- ### Registering Resource Capabilities and Static Resources Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Shows how to initialize resource capabilities and register a static resource with a defined URI and content. ```php // Register resource capabilities $server->registerResourceCapabilities(); // Register a static resource $server->registerResource('greeting', 'greeting://hello', [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ]); ``` -------------------------------- ### Create a Basic MCP Client Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/getting-started.md This snippet demonstrates how to initialize an MCP client, configure its capabilities, and connect to an HTTP transport. It shows how to initialize the connection, list resources, and call a tool. ```php true], tools: ['list' => true] ); // Connect to an MCP server $transport = new HttpTransport('https://example.com/mcp'); $client->connect($transport, $capabilities); // Initialize the connection $result = $client->initialize(); // Get resources $resources = $client->listResources(); // Call a tool $toolResult = $client->callTool('add', ['a' => 5, 'b' => 3]); echo "Result: " . $toolResult['content'][0]['text'] . "\n"; // Clean up $client->shutdown(); ``` -------------------------------- ### Access Private/Protected Properties Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Get or set the value of private or protected properties of an object using reflection. Requires the base TestCase class. ```php // Access private/protected properties $value = $this->getPropertyValue($object, 'propertyName'); $this->setPropertyValue($object, 'propertyName', $value); ``` -------------------------------- ### Get ToolResponse Content Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/api-reference/tools.md Use the `getContent` method to retrieve the raw content array from a ToolResponse instance. This is useful for accessing the underlying data. ```php public function getContent(): array; ``` -------------------------------- ### Register a New Tool Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/api-reference/tools.md Demonstrates how to register a new tool with a name, schema definition, and a handler function. The schema defines expected parameters, and the handler performs the tool's logic. ```php $toolManager->register('add', [ 'properties' => [ 'a' => ['type' => 'number'], 'b' => ['type' => 'number'] ], 'required' => ['a', 'b'] ], function($params) { return $params['a'] + $params['b']; }); ``` -------------------------------- ### Create and Use ResourceTemplate Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Demonstrates creating a ResourceTemplate, checking URI matches, extracting parameters, and expanding the template with parameters. Useful for defining patterns for resource URIs. ```php use MCP\Protocol\Resources\ResourceTemplate; // Create a resource template $template = new ResourceTemplate( 'greeting://{name}', // URI template [ 'list' => [ 'examples' => ['John', 'Jane', 'Bob'] ] ] ); // Check if a URI matches this template $matches = $template->matches('greeting://John'); // true // Extract parameters from a URI $params = $template->extract('greeting://John'); // ['name' => 'John'] // Expand template with parameters $uri = $template->expand(['name' => 'John']); // 'greeting://John' // Get list options $options = $template->getListOptions(); ``` -------------------------------- ### Registering Dynamic Resources with Templates Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Demonstrates registering a dynamic resource using a template URI and a callback function to generate content based on parameters. ```php // Register a dynamic resource with a template $template = new ResourceTemplate('greeting://{name}'); $server->registerResourceTemplate('personalized-greeting', $template, function($uri, $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; }); ``` -------------------------------- ### Registering a Tool with McpServer Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/api-reference/tools.md Shows how to register a new tool with the McpServer, including its schema definition and the callback function to execute. ```php // Register a tool $server->registerTool('add', [ 'properties' => [ 'a' => ['type' => 'number'], 'b' => ['type' => 'number'] ], 'required' => ['a', 'b'] ], function($params) { return $params['a'] + $params['b']; }); // Unregister a tool $server->unregisterTool('add'); // Access the tool manager $toolManager = $server->getToolManager(); ``` -------------------------------- ### Running the Client Script Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/client-implementation.md Save the client code to a file and execute it using the PHP command-line interpreter. ```bash php client.php ``` -------------------------------- ### Registering a Prompt Template Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/server-implementation.md Use `registerPrompt` to define a prompt template for generating introductions. This prompt requires a name and profession and formats them into a user message. ```php // Add a prompt template $server->registerPrompt('introduction', [ 'properties' => [ 'name' => ['type' => 'string'], 'profession' => ['type' => 'string'] ], 'required' => ['name', 'profession'], 'description' => 'Creates an introduction message' ], function($params) { return [ 'messages' => [ [ 'role' => 'user', 'content' => [ 'type' => 'text', 'text' => "Please introduce {$params['name']}, who works as a {$params['profession']}." ] ] ] ]; }); ``` -------------------------------- ### Adding Resources to MCP Server Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/server-implementation.md Demonstrates how to register different types of resources with the MCP server: a static resource with predefined content, a dynamic resource using a template that accepts parameters, and a file resource that reads content from a local file. ```php // Add a static resource $server->registerResource('greeting', 'greeting://hello', [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ]); // Add a dynamic resource with a template $greetingTemplate = new MCP\Protocol\Resources\ResourceTemplate('greeting://{name}'); $server->registerResourceTemplate('personalized-greeting', $greetingTemplate, function($uri, $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; }); // Add a file resource $server->registerResource('readme', 'file://readme.md', [ [ 'type' => 'text', 'text' => file_get_contents('README.md') ] ]); ``` -------------------------------- ### Standardized Error Response JSON Structure Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/EDU-102-COMPLETION-SUMMARY.md Example of a standardized error response structure, including error code, message, and detailed data with context information like operation, user ID, timestamp, and exception details. ```json { "error": { "code": -32603, "message": "Internal server error", "data": { "details": { "original_data": "..." }, "context": { "operation": "tool_execution", "user_id": "user123", "timestamp": "2025-06-20T03:47:11+00:00", "exception": "RuntimeException", "file": "/path/to/file.php", "line": 42, "trace": "..." } } } } ``` -------------------------------- ### Initialize McpServer Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/README.md Instantiate the main McpServer class to manage connections, protocol compliance, and message routing for your application. ```php $server = new ModelContextProtocol\Server\McpServer('My App', '1.0.0'); ``` -------------------------------- ### Registering a Complex Weather Fetch Tool Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/server-implementation.md Implement a more complex tool like `fetchWeather` using `registerTool`. This tool takes a location and optional units (metric/imperial) and simulates fetching weather data. ```php // Add a more complex tool $server->registerTool('fetchWeather', [ 'properties' => [ 'location' => ['type' => 'string'], 'units' => [ 'type' => 'string', 'enum' => ['metric', 'imperial'], 'default' => 'metric' ] ], 'required' => ['location'], 'description' => 'Fetches weather information for a location' ], function($params) { $location = $params['location']; $units = $params['units'] ?? 'metric'; // In a real implementation, this would call a weather API $weatherData = [ 'location' => $location, 'temperature' => ($units === 'metric') ? 22 : 72, 'conditions' => 'Sunny', 'units' => $units ]; return [ 'content' => [ [ 'type' => 'application/json', 'data' => $weatherData ] ] ]; }); ``` -------------------------------- ### Run All Quality Checks Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Execute all configured code quality checks using Composer. ```bash # Run all quality checks composer quality ``` -------------------------------- ### Handling Different Resource Content Types Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Demonstrates how to structure content for different types: plain text, JSON, images (as base64 encoded strings), and mixed content arrays. ```php // Text content $textContent = [ 'content' => [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ] ]; // JSON content $jsonContent = [ 'content' => [ [ 'type' => 'application/json', 'data' => [ 'greeting' => 'Hello', 'target' => 'world' ] ] ] ]; // Image content $imageContent = [ 'content' => [ [ 'type' => 'image/png', 'data' => 'base64,iVBORw0KGgoAAAANSUhEUgA...' ] ] ]; // Mixed content $mixedContent = [ 'content' => [ [ 'type' => 'text', 'text' => 'Hello, world!' ], [ 'type' => 'application/json', 'data' => ['greeting' => 'Hello'] ] ] ]; ``` -------------------------------- ### List Resources with ResourceManager Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Shows how to list all registered resources using the ResourceManager. This can be used for discovery or auditing purposes. ```php use MCP\Protocol\Resources\ResourceManager; use MCP\Protocol\Resources\StaticResource; use MCP\Protocol\Resources\ResourceTemplate; // Create a resource manager $manager = new ResourceManager(); // ... (resource registration code here) ... // List all listable resources $resources = $manager->list(); ``` -------------------------------- ### Run MCP Server with PHP Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/server-implementation.md Save the provided server code to `server.php` and execute it using the PHP CLI. The server will then listen for MCP messages on standard input and output. ```bash php server.php ``` -------------------------------- ### Create a Dynamic Resource Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Instantiate a DynamicResource with a name, template, and a handler function that generates content based on URI parameters. ```php use MCP\Protocol\Resources\ResourceTemplate; use MCP\Protocol\Resources\DynamicResource; // Create a resource template $template = new ResourceTemplate('greeting://{name}'); // Create a dynamic resource $resource = new DynamicResource( 'personalized-greeting', // Resource name $template, // Resource template function($uri, $params) { // Handler function return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; } ); ``` -------------------------------- ### Register Dynamic Resource with Parameters Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/README.md Register a dynamic resource using a template that accepts parameters from the LLM's request. The provided callback function generates the resource content based on these parameters. ```php $template = new ModelContextProtocol\Protocol\Resources\ResourceTemplate('greeting://{name}'); $server->registerResourceTemplate('personalized-greeting', $template, function(string $uri, array $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; }); ``` -------------------------------- ### Create Temporary Test File Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Create a temporary file with specified content for testing. The file is automatically cleaned up after the test. Requires the base TestCase class. ```php // Create temporary test files $tempFile = $this->createTempFile('content'); // Files are automatically cleaned up after test ``` -------------------------------- ### Run All Tests Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Execute all tests in the project using Composer. ```bash # Run all tests composer test ``` -------------------------------- ### Register a Tool Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/getting-started.md This code registers a tool with its properties and a callback function to execute when the tool is called. ```php // Register a tool $server->registerTool('add', [ 'properties' => [ 'a' => ['type' => 'number'], 'b' => ['type' => 'number'] ], 'required' => ['a', 'b'] ], function($params) { return $params['a'] + $params['b']; }); ``` -------------------------------- ### Create a Static Resource Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Instantiate a StaticResource object with a name, URI, and content. The content is an array of associative arrays, each defining a 'type' and its corresponding data. ```php use MCP\Protocol\Resources\StaticResource; // Create a static resource $resource = new StaticResource( 'greeting', // Resource name 'greeting://hello', // Resource URI [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ] ); ``` -------------------------------- ### View Coverage Report Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Open the generated coverage report in a web browser. ```bash # View coverage report open coverage-report/index.html ``` -------------------------------- ### Create Text ToolResponse Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/api-reference/tools.md Use the static `text` method to create a ToolResponse instance for plain text content. Ensure the content is provided as a string. ```php public static function text(string $text): self; ``` -------------------------------- ### Register Static Resource with ResourceManager Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Shows how to register a static resource using ResourceManager. This is suitable for resources with fixed content. ```php use MCP\Protocol\Resources\ResourceManager; use MCP\Protocol\Resources\StaticResource; use MCP\Protocol\Resources\ResourceTemplate; // Create a resource manager $manager = new ResourceManager(); // Register a static resource $staticResource = $manager->registerStatic( 'greeting', // Resource name 'greeting://hello', // Resource URI [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ] ); ``` -------------------------------- ### Create Mock Request and Tool Schema Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Generates a mock request object with parameters and defines a standard tool schema for testing purposes. ```php // Standard test request $request = $this->createMockRequest('test/method', [ 'param1' => 'value1', 'param2' => 'value2' ]); // Standard tool schema $toolSchema = [ 'properties' => [ 'input' => ['type' => 'string', 'description' => 'Input parameter'] ], 'required' => ['input'], 'description' => 'Test tool description' ]; ``` -------------------------------- ### Run Individual Quality Tools Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Execute specific code quality tools like PHPStan, CS (CodeSniffer), and PHPMD. ```bash # Individual quality tools composer phpstan # Static analysis composer cs-check # Code style check composer phpmd # Mess detection ``` -------------------------------- ### Registering a Simple Addition Tool Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/examples/server-implementation.md Use `registerTool` to add a tool that performs a simple addition. This tool expects two numeric parameters, 'a' and 'b', and returns their sum as text. ```php // Add a simple addition tool $server->registerTool('add', [ 'properties' => [ 'a' => ['type' => 'number'], 'b' => ['type' => 'number'] ], 'required' => ['a', 'b'], 'description' => 'Adds two numbers together' ], function($params) { $result = $params['a'] + $params['b']; return [ 'content' => [ [ 'type' => 'text', 'text' => (string)$result ] ] ]; }); ``` -------------------------------- ### Register a Static Resource with McpServer Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Register a static resource directly with the McpServer. This method takes the resource name, URI, and content as arguments. ```php // Register a static resource with McpServer $server->registerResource('greeting', 'greeting://hello', [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ]); ``` -------------------------------- ### Work with URI Templates Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Utilize the UriTemplate class to create, validate, extract variables from, expand, and match URIs against templates. ```php use MCP\Protocol\Resources\UriTemplate; // Create a URI template $template = new UriTemplate('greeting://{name}'); // Check if a string is a template $isTemplate = UriTemplate::isTemplate('greeting://{name}'); // true // Get variable names from a template $variables = $template->getVariableNames(); // ['name'] // Expand a template with values $uri = $template->expand(['name' => 'John']); // 'greeting://John' // Match a URI against a template $values = $template->match('greeting://John'); // ['name' => 'John'] ``` -------------------------------- ### Include SDK Autoloader Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/installation.md Manually include the SDK's autoloader file in your project after cloning the repository. ```php require_once 'path/to/mcp-php-sdk/autoload.php'; ``` -------------------------------- ### Testing Results Summary Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/EDU-101-COMPLETION-SUMMARY.md A list of successful test cases indicating the completion of various components and functionalities within the MCP PHP SDK. ```text ✅ PromptManager class implemented ✅ prompts/list returns registered prompts ✅ prompts/get executes prompt handlers ✅ Argument validation against schemas ✅ Change notifications when prompts updated ✅ Working examples with real prompts ✅ Comprehensive error handling ✅ Direct PromptManager access ✅ PromptSchema object support ✅ Integration with McpServer ``` -------------------------------- ### Register Dynamic Resource with ResourceManager Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Illustrates registering a dynamic resource with ResourceManager, where content is generated based on a template and a callback function. This is useful for resources whose content varies based on parameters. ```php use MCP\Protocol\Resources\ResourceManager; use MCP\Protocol\Resources\StaticResource; use MCP\Protocol\Resources\ResourceTemplate; // Create a resource manager $manager = new ResourceManager(); // Create a template and register a dynamic resource $template = new ResourceTemplate('greeting://{name}'); $dynamicResource = $manager->registerDynamic( 'personalized-greeting', // Resource name $template, // Resource template function($uri, $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; } ); ``` -------------------------------- ### Generate HTML Coverage Report Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Generate an HTML coverage report for the project using Composer. ```bash # Generate HTML coverage report composer test-coverage ``` -------------------------------- ### Create Mock JSON-RPC Request Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Create a mock JSON-RPC request object for testing purposes. Requires the base TestCase class. ```php // Create mock JSON-RPC request $request = $this->createMockRequest('test/method', ['param' => 'value']); ``` -------------------------------- ### Set Up Global Exception Handler Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/troubleshooting/debugging-techniques.md Configure a global exception handler using set_exception_handler to catch and log all uncaught exceptions, including their messages and stack traces. This ensures that critical errors are not missed. ```php set_exception_handler(function($exception) use ($logger) { $logger->error("Uncaught exception: " . $exception->getMessage()); $logger->error("Stack trace: " . $exception->getTraceAsString()); }); ``` -------------------------------- ### Resolve Resource URI with ResourceManager Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Demonstrates how to resolve a resource URI using ResourceManager and handle the returned resource. This is the primary method for accessing registered resources. ```php use MCP\Protocol\Resources\ResourceManager; use MCP\Protocol\Resources\StaticResource; use MCP\Protocol\Resources\ResourceTemplate; // Create a resource manager $manager = new ResourceManager(); // ... (resource registration code here) ... // Resolve a URI to a resource $result = $manager->resolve('greeting://John'); if ($result !== null) { $name = $result['name']; // Resource name $resource = $result['resource']; // Resource object $params = $result['params']; // Extracted parameters // Handle the resource $content = $resource->handle($uri, $params); } ``` -------------------------------- ### Register a Static Resource Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/getting-started.md This code registers a static resource with a given name and URI, providing fixed content. ```php // Register a static resource $server->registerResource('greeting', 'greeting://hello', [ [ 'type' => 'text', 'text' => 'Hello, world!' ] ]); ``` -------------------------------- ### Test Directory Structure Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Illustrates the organization of the test suite within the project. ```tree tests/ ├── TestCase.php # Base test case with common utilities ├── Unit/ # Unit tests for individual components │ ├── Protocol/ # Protocol layer tests │ ├── Server/ # Server components tests │ ├── Transport/ # Transport layer tests │ └── Utilities/ # Utility classes tests ├── Integration/ # End-to-end integration tests └── Protocol/ # MCP protocol compliance tests ``` -------------------------------- ### Create Mock JSON-RPC Response Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Create a mock JSON-RPC response object for testing purposes. Requires the base TestCase class. ```php // Create mock JSON-RPC response $response = $this->createMockResponse(['result' => 'success']); ``` -------------------------------- ### Create Tool Not Found Error Response Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/EDU-102-COMPLETION-SUMMARY.md A convenience method for generating a specific error response when a requested tool is not found. ```php ErrorResponseBuilder::toolNotFound($request, $toolName) ``` -------------------------------- ### Register a Dynamic Resource with McpServer Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/resource-development.md Register a dynamic resource template and its handler function with the McpServer for handling incoming requests. ```php // Create a resource template $template = new ResourceTemplate('greeting://{name}'); // Register a dynamic resource with McpServer $server->registerResourceTemplate('personalized-greeting', $template, function($uri, $params) { return [ 'content' => [ [ 'type' => 'text', 'text' => "Hello, {$params['name']}!" ] ] ]; }); ``` -------------------------------- ### Clone SDK Repository Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/guides/installation.md Manually clone the PHP MCP SDK repository from GitHub if you prefer not to use Composer. ```bash git clone https://github.com/eduardocruz/mcp-php-sdk.git ``` -------------------------------- ### Configure Xdebug in php.ini Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/troubleshooting/debugging-techniques.md Add these settings to your php.ini file to enable Xdebug's debugging mode. Ensure Xdebug is enabled and configured to connect to your IDE. ```ini [xdebug] zend_extension=xdebug.so xdebug.mode=debug xdebug.client_host=127.0.0.1 xdebug.client_port=9003 xdebug.start_with_request=yes ``` -------------------------------- ### Set up SSH Tunnel for Remote Debugging Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/troubleshooting/debugging-techniques.md Create an SSH tunnel to forward the Xdebug port from the remote server to your local machine. This is essential for establishing a connection when debugging remotely. ```bash ssh -R 9003:localhost:9003 user@remote-server ``` -------------------------------- ### Run Tests with Verbose Output Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Execute tests with verbose output using the --testdox flag for better readability. ```bash # Run with verbose output ./vendor/bin/phpunit --testdox ``` -------------------------------- ### Trace Method Calls with Logging Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/docs/troubleshooting/debugging-techniques.md Add debug and error logging within your handler execution logic to trace method calls, log parameters, results, and exceptions. This helps in understanding the execution flow and identifying issues. ```php private function executeHandler($requestId, $methodName, $params) { $this->logger->debug("Executing handler for method: $methodName"); $this->logger->debug("Parameters: " . json_encode($params)); try { $result = $this->handlers[$methodName]($params); $this->logger->debug("Handler result: " . json_encode($result)); return $result; } catch (Exception $e) { $this->logger->error("Handler exception: " . $e->getMessage()); throw $e; } } ``` -------------------------------- ### Run Specific Test File Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Execute tests from a particular test file using PHPUnit. ```bash # Run specific test file ./vendor/bin/phpunit tests/Unit/Protocol/JsonRpcMessageTest.php ``` -------------------------------- ### Run Specific Test Suite Source: https://github.com/eduardocruz/mcp-php-sdk/blob/main/tests/README.md Execute tests belonging to a specific suite (Unit, Integration, Protocol) using PHPUnit. ```bash # Run specific test suite ./vendor/bin/phpunit --testsuite=Unit ./vendor/bin/phpunit --testsuite=Integration ./vendor/bin/phpunit --testsuite=Protocol ```