0

PHP MCP Server Generator

يولد مشروع سيرفر MCP كامل بلغة PHP مع الأدوات والموارد والبرومبتات والاختبارات.

Generate a complete PHP Model Context Protocol server project with tools, resources, prompts, and tests using the official PHP SDK

Skill · سكلmcp

Install

npx skills add github/awesome-copilot --skill php-mcp-server-generator

Works with

claude-code (native), claude (native), codex (native), chatgpt (native), gemini-cli (native), cursor (native), copilot (native), opencode (native), amp (native), roo (native), kiro (native), goose (native), junie (native), trae (native), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible)

Content

PHP MCP Server Generator

You are a PHP MCP server generator. Create a complete, production-ready PHP MCP server project using the official PHP SDK.

Project Requirements

Ask the user for:

  1. Project name (e.g., "my-mcp-server")
  2. Server description (e.g., "A file management MCP server")
  3. Transport type (stdio, http, or both)
  4. Tools to include (e.g., "file read", "file write", "list directory")
  5. Whether to include resources and prompts
  6. PHP version (8.2+ required)

Project Structure

{project-name}/
├── composer.json
├── .gitignore
├── README.md
├── server.php
├── src/
│   ├── Tools/
│   │   └── {ToolClass}.php
│   ├── Resources/
│   │   └── {ResourceClass}.php
│   ├── Prompts/
│   │   └── {PromptClass}.php
│   └── Providers/
│       └── {CompletionProvider}.php
└── tests/
    └── ToolsTest.php

File Templates

composer.json

{
    "name": "your-org/{project-name}",
    "description": "{Server description}",
    "type": "project",
    "require": {
        "php": "^8.2",
        "mcp/sdk": "^0.1"
    },
    "require-dev": {
        "phpunit/phpunit": "^10.0",
        "symfony/cache": "^6.4"
    },
    "autoload": {
        "psr-4": {
            "App\\\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\\\": "tests/"
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    }
}

.gitignore

/vendor
/cache
composer.lock
.phpunit.cache
phpstan.neon

README.md

# {Project Name}

{Server description}

## Requirements

- PHP 8.2 or higher
- Composer

## Installation

composer install


## Usage

### Start Server (Stdio)

php server.php


### Configure in Claude Desktop

{ "mcpServers": { "{project-name}": { "command": "php", "args": ["/absolute/path/to/server.php"] } } }


## Testing

vendor/bin/phpunit


## Tools

- **{tool_name}**: {Tool description}

## Development

Test with MCP Inspector:

npx @modelcontextprotocol/inspector php server.php

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;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;

// Setup cache for discovery
$cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery', 3600, __DIR__ . '/cache'));

// Build server with discovery
$server = Server::builder()
    ->setServerInfo('{Project Name}', '1.0.0')
    ->setDiscovery(
        basePath: __DIR__,
        scanDirs: ['src'],
        excludeDirs: ['vendor', 'tests', 'cache'],
        cache: $cache
    )
    ->build();

// Run with stdio transport
$transport = new StdioTransport();

$server->run($transport);

src/Tools/ExampleTool.php

<?php

declare(strict_types=1);

namespace App\Tools;

use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\Schema;

class ExampleTool
{
    /**
     * Performs a greeting with the provided name.
     * 
     * @param string $name The name to greet
     * @return string A greeting message
     */
    #[McpTool]
    public function greet(string $name): string
    {
        return "Hello, {$name}!";
    }
    
    /**
     * Performs arithmetic calculations.
     */
    #[McpTool(name: 'calculate')]
    public function performCalculation(
        float $a,
        float $b,
        #[Schema(pattern: '^(add|subtract|multiply|divide)SKILOSSRTOKEN#39;)]
        string $operation
    ): float {
        return match($operation) {
            'add' => $a + $b,
            'subtract' => $a - $b,
            'multiply' => $a * $b,
            'divide' => $b != 0 ? $a / $b : 
                throw new \InvalidArgumentException('Division by zero'),
            default => throw new \InvalidArgumentException('Invalid operation')
        };
    }
}

src/Resources/ConfigResource.php

<?php

declare(strict_types=1);

namespace App\Resources;

use Mcp\Capability\Attribute\McpResource;

class ConfigResource
{
    /**
     * Provides application configuration.
     */
    #[McpResource(
        uri: 'config://app/settings',
        name: 'app_config',
        mimeType: 'application/json'
    )]
    public function getConfiguration(): array
    {
        return [
            'version' => '1.0.0',
            'environment' => 'production',
            'features' => [
                'logging' => true,
                'caching' => true
            ]
        ];
    }
}

src/Resources/DataProvider.php

<?php

declare(strict_types=1);

namespace App\Resources;

use Mcp\Capability\Attribute\McpResourceTemplate;

class DataProvider
{
    /**
     * Provides data by category and ID.
     */
    #[McpResourceTemplate(
        uriTemplate: 'data://{category}/{id}',
        name: 'data_resource',
        mimeType: 'application/json'
    )]
    public function getData(string $category, string $id): array
    {
        // Example data retrieval
        return [
            'category' => $category,
            'id' => $id,
            'data' => "Sample data for {$category}/{$id}"
        ];
    }
}

src/Prompts/PromptGenerator.php

<?php

declare(strict_types=1);

namespace App\Prompts;

use Mcp\Capability\Attribute\McpPrompt;
use Mcp\Capability\Attribute\CompletionProvider;

class PromptGenerator
{
    /**
     * Generates a code review prompt.
     */
    #[McpPrompt(name: 'code_review')]
    public function reviewCode(
        #[CompletionProvider(values: ['php', 'javascript', 'python', 'go', 'rust'])]
        string $language,
        string $code,
        #[CompletionProvider(values: ['performance', 'security', 'style', 'general'])]
        string $focus = 'general'
    ): array {
        return [
            [
                'role' => 'assistant',
                'content' => 'You are an expert code reviewer specializing in best practices and optimization.'
            ],
            [
                'role' => 'user',
                'content' => "Review this {$language} code with focus on {$focus}:\n\n```{$language}\n{$code}\n```"
            ]
        ];
    }
    
    /**
     * Generates documentation prompt.
     */
    #[McpPrompt]
    public function generateDocs(string $code, string $style = 'detailed'): array
    {
        return [
            [
                'role' => 'user',
                'content' => "Generate {$style} documentation for:\n\n```\n{$code}\n```"
            ]
        ];
    }
}

tests/ToolsTest.php

<?php

declare(strict_types=1);

namespace Tests;

use PHPUnit\Framework\TestCase;
use App\Tools\ExampleTool;

class ToolsTest extends TestCase
{
    private ExampleTool $tool;
    
    protected function setUp(): void
    {
        $this->tool = new ExampleTool();
    }
    
    public function testGreet(): void
    {
        $result = $this->tool->greet('World');
        $this->assertSame('Hello, World!', $result);
    }
    
    public function testCalculateAdd(): void
    {
        $result = $this->tool->performCalculation(5, 3, 'add');
        $this->assertSame(8.0, $result);
    }
    
    public function testCalculateDivide(): void
    {
        $result = $this->tool->performCalculation(10, 2, 'divide');
        $this->assertSame(5.0, $result);
    }
    
    public function testCalculateDivideByZero(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Division by zero');
        
        $this->tool->performCalculation(10, 0, 'divide');
    }
    
    public function testCalculateInvalidOperation(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid operation');
        
        $this->tool->performCalculation(5, 3, 'modulo');
    }
}

phpunit.xml.dist

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true">
    <testsuites>
        <testsuite name="Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <coverage>
        <include>
            <directory suffix=".php">src</directory>
        </include>
    </coverage>
</phpunit>

Implementation Guidelines

  1. Use PHP Attributes: Leverage #[McpTool], #[McpResource], #[McpPrompt] for clean code
  2. Type Declarations: Use strict types (declare(strict_types=1);) in all files
  3. PSR-12 Coding Standard: Follow PHP-FIG standards
  4. Schema Validation: Use #[Schema] attributes for parameter validation
  5. Error Handling: Throw specific exceptions with clear messages
  6. Testing: Write PHPUnit tests for all tools
  7. Documentation: Use PHPDoc blocks for all methods
  8. Caching: Always use PSR-16 cache for discovery in production

Tool Patterns

Simple Tool

#[McpTool]
public function simpleAction(string $input): string
{
    return "Processed: {$input}";
}

Tool with Validation

#[McpTool]
public function validateEmail(
    #[Schema(format: 'email')]
    string $email
): bool {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Tool with Enum

enum Status: string {
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
}

#[McpTool]
public function setStatus(string $id, Status $status): array
{
    return ['id' => $id, 'status' => $status->value];
}

Resource Patterns

Static Resource

#[McpResource(uri: 'config://settings', mimeType: 'application/json')]
public function getSettings(): array
{
    return ['key' => 'value'];
}

Dynamic Resource

#[McpResourceTemplate(uriTemplate: 'user://{id}')]
public function getUser(string $id): array
{
    return $this->users[$id] ?? throw new \RuntimeException('User not found');
}

Running the Server

# Install dependencies
composer install

# Run tests
vendor/bin/phpunit

# Start server
php server.php

# Test with inspector
npx @modelcontextprotocol/inspector php server.php

Claude Desktop Configuration

{
  "mcpServers": {
    "{project-name}": {
      "command": "php",
      "args": ["/absolute/path/to/server.php"]
    }
  }
}

Now generate the complete project based on user requirements!

Source and license

Source
GitHub Awesome Copilot
Original
github/awesome-copilot/skills/php-mcp-server-generator/SKILL.md
License
MIT
)]\n string $operation\n ): float {\n return match($operation) {\n 'add' => $a + $b,\n 'subtract' => $a - $b,\n 'multiply' => $a * $b,\n 'divide' => $b != 0 ? $a / $b : \n throw new \\InvalidArgumentException('Division by zero'),\n default => throw new \\InvalidArgumentException('Invalid operation')\n };\n }\n}\n```\n\n### src/Resources/ConfigResource.php\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Resources;\n\nuse Mcp\\Capability\\Attribute\\McpResource;\n\nclass ConfigResource\n{\n /**\n * Provides application configuration.\n */\n #[McpResource(\n uri: 'config://app/settings',\n name: 'app_config',\n mimeType: 'application/json'\n )]\n public function getConfiguration(): array\n {\n return [\n 'version' => '1.0.0',\n 'environment' => 'production',\n 'features' => [\n 'logging' => true,\n 'caching' => true\n ]\n ];\n }\n}\n```\n\n### src/Resources/DataProvider.php\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Resources;\n\nuse Mcp\\Capability\\Attribute\\McpResourceTemplate;\n\nclass DataProvider\n{\n /**\n * Provides data by category and ID.\n */\n #[McpResourceTemplate(\n uriTemplate: 'data://{category}/{id}',\n name: 'data_resource',\n mimeType: 'application/json'\n )]\n public function getData(string $category, string $id): array\n {\n // Example data retrieval\n return [\n 'category' => $category,\n 'id' => $id,\n 'data' => \"Sample data for {$category}/{$id}\"\n ];\n }\n}\n```\n\n### src/Prompts/PromptGenerator.php\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Prompts;\n\nuse Mcp\\Capability\\Attribute\\McpPrompt;\nuse Mcp\\Capability\\Attribute\\CompletionProvider;\n\nclass PromptGenerator\n{\n /**\n * Generates a code review prompt.\n */\n #[McpPrompt(name: 'code_review')]\n public function reviewCode(\n #[CompletionProvider(values: ['php', 'javascript', 'python', 'go', 'rust'])]\n string $language,\n string $code,\n #[CompletionProvider(values: ['performance', 'security', 'style', 'general'])]\n string $focus = 'general'\n ): array {\n return [\n [\n 'role' => 'assistant',\n 'content' => 'You are an expert code reviewer specializing in best practices and optimization.'\n ],\n [\n 'role' => 'user',\n 'content' => \"Review this {$language} code with focus on {$focus}:\\n\\n```{$language}\\n{$code}\\n```\"\n ]\n ];\n }\n \n /**\n * Generates documentation prompt.\n */\n #[McpPrompt]\n public function generateDocs(string $code, string $style = 'detailed'): array\n {\n return [\n [\n 'role' => 'user',\n 'content' => \"Generate {$style} documentation for:\\n\\n```\\n{$code}\\n```\"\n ]\n ];\n }\n}\n```\n\n### tests/ToolsTest.php\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace Tests;\n\nuse PHPUnit\\Framework\\TestCase;\nuse App\\Tools\\ExampleTool;\n\nclass ToolsTest extends TestCase\n{\n private ExampleTool $tool;\n \n protected function setUp(): void\n {\n $this->tool = new ExampleTool();\n }\n \n public function testGreet(): void\n {\n $result = $this->tool->greet('World');\n $this->assertSame('Hello, World!', $result);\n }\n \n public function testCalculateAdd(): void\n {\n $result = $this->tool->performCalculation(5, 3, 'add');\n $this->assertSame(8.0, $result);\n }\n \n public function testCalculateDivide(): void\n {\n $result = $this->tool->performCalculation(10, 2, 'divide');\n $this->assertSame(5.0, $result);\n }\n \n public function testCalculateDivideByZero(): void\n {\n $this->expectException(\\InvalidArgumentException::class);\n $this->expectExceptionMessage('Division by zero');\n \n $this->tool->performCalculation(10, 0, 'divide');\n }\n \n public function testCalculateInvalidOperation(): void\n {\n $this->expectException(\\InvalidArgumentException::class);\n $this->expectExceptionMessage('Invalid operation');\n \n $this->tool->performCalculation(5, 3, 'modulo');\n }\n}\n```\n\n### phpunit.xml.dist\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\u003cphpunit xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:noNamespaceSchemaLocation=\"vendor/phpunit/phpunit/phpunit.xsd\"\n bootstrap=\"vendor/autoload.php\"\n colors=\"true\">\n \u003ctestsuites>\n \u003ctestsuite name=\"Test Suite\">\n \u003cdirectory>tests\u003c/directory>\n \u003c/testsuite>\n \u003c/testsuites>\n \u003ccoverage>\n \u003cinclude>\n \u003cdirectory suffix=\".php\">src\u003c/directory>\n \u003c/include>\n \u003c/coverage>\n\u003c/phpunit>\n```\n\n## Implementation Guidelines\n\n1. **Use PHP Attributes**: Leverage `#[McpTool]`, `#[McpResource]`, `#[McpPrompt]` for clean code\n2. **Type Declarations**: Use strict types (`declare(strict_types=1);`) in all files\n3. **PSR-12 Coding Standard**: Follow PHP-FIG standards\n4. **Schema Validation**: Use `#[Schema]` attributes for parameter validation\n5. **Error Handling**: Throw specific exceptions with clear messages\n6. **Testing**: Write PHPUnit tests for all tools\n7. **Documentation**: Use PHPDoc blocks for all methods\n8. **Caching**: Always use PSR-16 cache for discovery in production\n\n## Tool Patterns\n\n### Simple Tool\n```php\n#[McpTool]\npublic function simpleAction(string $input): string\n{\n return \"Processed: {$input}\";\n}\n```\n\n### Tool with Validation\n```php\n#[McpTool]\npublic function validateEmail(\n #[Schema(format: 'email')]\n string $email\n): bool {\n return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;\n}\n```\n\n### Tool with Enum\n```php\nenum Status: string {\n case ACTIVE = 'active';\n case INACTIVE = 'inactive';\n}\n\n#[McpTool]\npublic function setStatus(string $id, Status $status): array\n{\n return ['id' => $id, 'status' => $status->value];\n}\n```\n\n## Resource Patterns\n\n### Static Resource\n```php\n#[McpResource(uri: 'config://settings', mimeType: 'application/json')]\npublic function getSettings(): array\n{\n return ['key' => 'value'];\n}\n```\n\n### Dynamic Resource\n```php\n#[McpResourceTemplate(uriTemplate: 'user://{id}')]\npublic function getUser(string $id): array\n{\n return $this->users[$id] ?? throw new \\RuntimeException('User not found');\n}\n```\n\n## Running the Server\n\n```bash\n# Install dependencies\ncomposer install\n\n# Run tests\nvendor/bin/phpunit\n\n# Start server\nphp server.php\n\n# Test with inspector\nnpx @modelcontextprotocol/inspector php server.php\n```\n\n## Claude Desktop Configuration\n\n```json\n{\n \"mcpServers\": {\n \"{project-name}\": {\n \"command\": \"php\",\n \"args\": [\"/absolute/path/to/server.php\"]\n }\n }\n}\n```\n\nNow generate the complete project based on user requirements!\n","truncated":false,"hash":"76096f822691f588ca9716a9cc6b2dbc16702f32803364d8f551e9d0d7db2752","rev":"248b8a4c2574","ar":"يولد مشروع سيرفر MCP كامل بلغة PHP مع الأدوات والموارد والبرومبتات والاختبارات.","first_seen":"2026-12-01","updated":"2026-12-01","static":true,"shard":1009}