1
---
2
name: php-mcp-server-generator
3
description: 'Generate a complete PHP Model Context Protocol server project with tools, resources, prompts, and tests using the official PHP SDK'
4
---
5
6
# PHP MCP Server Generator
7
8
You are a PHP MCP server generator. Create a complete, production-ready PHP MCP server project using the official PHP SDK.
9
10
## Project Requirements
11
12
Ask the user for:
13
1. **Project name** (e.g., "my-mcp-server")
14
2. **Server description** (e.g., "A file management MCP server")
15
3. **Transport type** (stdio, http, or both)
16
4. **Tools to include** (e.g., "file read", "file write", "list directory")
17
5. **Whether to include resources and prompts**
18
6. **PHP version** (8.2+ required)
19
20
## Project Structure
21
22
```
23
{project-name}/
24
├── composer.json
25
├── .gitignore
26
├── README.md
27
├── server.php
28
├── src/
29
│ ├── Tools/
30
│ │ └── {ToolClass}.php
31
│ ├── Resources/
32
│ │ └── {ResourceClass}.php
33
│ ├── Prompts/
34
│ │ └── {PromptClass}.php
35
│ └── Providers/
36
│ └── {CompletionProvider}.php
37
└── tests/
38
└── ToolsTest.php
39
```
40
41
## File Templates
42
43
### composer.json
44
45
```json
46
{
47
"name": "your-org/{project-name}",
48
"description": "{Server description}",
49
"type": "project",
50
"require": {
51
"php": "^8.2",
52
"mcp/sdk": "^0.1"
53
},
54
"require-dev": {
55
"phpunit/phpunit": "^10.0",
56
"symfony/cache": "^6.4"
57
},
58
"autoload": {
59
"psr-4": {
60
"App\\\\": "src/"
61
}
62
},
63
"autoload-dev": {
64
"psr-4": {
65
"Tests\\\\": "tests/"
66
}
67
},
68
"config": {
69
"optimize-autoloader": true,
70
"preferred-install": "dist",
71
"sort-packages": true
72
}
73
}
74
```
75
76
### .gitignore
77
78
```
79
/vendor
80
/cache
81
composer.lock
82
.phpunit.cache
83
phpstan.neon
84
```
85
86
### README.md
87
88
```markdown
89
# {Project Name}
90
91
{Server description}
92
93
## Requirements
94
95
- PHP 8.2 or higher
96
- Composer
97
98
## Installation
99
100
```bash
101
composer install
102
```
103
104
## Usage
105
106
### Start Server (Stdio)
107
108
```bash
109
php server.php
110
```
111
112
### Configure in Claude Desktop
113
114
```json
115
{
116
"mcpServers": {
117
"{project-name}": {
118
"command": "php",
119
"args": ["/absolute/path/to/server.php"]
120
}
121
}
122
}
123
```
124
125
## Testing
126
127
```bash
128
vendor/bin/phpunit
129
```
130
131
## Tools
132
133
- **{tool_name}**: {Tool description}
134
135
## Development
136
137
Test with MCP Inspector:
138
139
```bash
140
npx @modelcontextprotocol/inspector php server.php
141
```
142
```
143
144
### server.php
145
146
```php
147
#!/usr/bin/env php
148
<?php
149
150
declare(strict_types=1);
151
152
require_once __DIR__ . '/vendor/autoload.php';
153
154
use Mcp\Server;
155
use Mcp\Server\Transport\StdioTransport;
156
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
157
use Symfony\Component\Cache\Psr16Cache;
158
159
// Setup cache for discovery
160
$cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery', 3600, __DIR__ . '/cache'));
161
162
// Build server with discovery
163
$server = Server::builder()
164
->setServerInfo('{Project Name}', '1.0.0')
165
->setDiscovery(
166
basePath: __DIR__,
167
scanDirs: ['src'],
168
excludeDirs: ['vendor', 'tests', 'cache'],
169
cache: $cache
170
)
171
->build();
172
173
// Run with stdio transport
174
$transport = new StdioTransport();
175
176
$server->run($transport);
177
```
178
179
### src/Tools/ExampleTool.php
180
181
```php
182
<?php
183
184
declare(strict_types=1);
185
186
namespace App\Tools;
187
188
use Mcp\Capability\Attribute\McpTool;
189
use Mcp\Capability\Attribute\Schema;
190
191
class ExampleTool
192
{
193
/**
194
* Performs a greeting with the provided name.
195
*
196
* @param string $name The name to greet
197
* @return string A greeting message
198
*/
199
#[McpTool]
200
public function greet(string $name): string
201
{
202
return "Hello, {$name}!";
203
}
204
205
/**
206
* Performs arithmetic calculations.
207
*/
208
#[McpTool(name: 'calculate')]
209
public function performCalculation(
210
float $a,
211
float $b,
212
#[Schema(pattern: '^(add|subtract|multiply|divide)$')]
213
string $operation
214
): float {
215
return match($operation) {
216
'add' => $a + $b,
217
'subtract' => $a - $b,
218
'multiply' => $a * $b,
219
'divide' => $b != 0 ? $a / $b :
220
throw new \InvalidArgumentException('Division by zero'),
221
default => throw new \InvalidArgumentException('Invalid operation')
222
};
223
}
224
}
225
```
226
227
### src/Resources/ConfigResource.php
228
229
```php
230
<?php
231
232
declare(strict_types=1);
233
234
namespace App\Resources;
235
236
use Mcp\Capability\Attribute\McpResource;
237
238
class ConfigResource
239
{
240
/**
241
* Provides application configuration.
242
*/
243
#[McpResource(
244
uri: 'config://app/settings',
245
name: 'app_config',
246
mimeType: 'application/json'
247
)]
248
public function getConfiguration(): array
249
{
250
return [
251
'version' => '1.0.0',
252
'environment' => 'production',
253
'features' => [
254
'logging' => true,
255
'caching' => true
256
]
257
];
258
}
259
}
260
```
261
262
### src/Resources/DataProvider.php
263
264
```php
265
<?php
266
267
declare(strict_types=1);
268
269
namespace App\Resources;
270
271
use Mcp\Capability\Attribute\McpResourceTemplate;
272
273
class DataProvider
274
{
275
/**
276
* Provides data by category and ID.
277
*/
278
#[McpResourceTemplate(
279
uriTemplate: 'data://{category}/{id}',
280
name: 'data_resource',
281
mimeType: 'application/json'
282
)]
283
public function getData(string $category, string $id): array
284
{
285
// Example data retrieval
286
return [
287
'category' => $category,
288
'id' => $id,
289
'data' => "Sample data for {$category}/{$id}"
290
];
291
}
292
}
293
```
294
295
### src/Prompts/PromptGenerator.php
296
297
```php
298
<?php
299
300
declare(strict_types=1);
301
302
namespace App\Prompts;
303
304
use Mcp\Capability\Attribute\McpPrompt;
305
use Mcp\Capability\Attribute\CompletionProvider;
306
307
class PromptGenerator
308
{
309
/**
310
* Generates a code review prompt.
311
*/
312
#[McpPrompt(name: 'code_review')]
313
public function reviewCode(
314
#[CompletionProvider(values: ['php', 'javascript', 'python', 'go', 'rust'])]
315
string $language,
316
string $code,
317
#[CompletionProvider(values: ['performance', 'security', 'style', 'general'])]
318
string $focus = 'general'
319
): array {
320
return [
321
[
322
'role' => 'assistant',
323
'content' => 'You are an expert code reviewer specializing in best practices and optimization.'
324
],
325
[
326
'role' => 'user',
327
'content' => "Review this {$language} code with focus on {$focus}:\n\n```{$language}\n{$code}\n```"
328
]
329
];
330
}
331
332
/**
333
* Generates documentation prompt.
334
*/
335
#[McpPrompt]
336
public function generateDocs(string $code, string $style = 'detailed'): array
337
{
338
return [
339
[
340
'role' => 'user',
341
'content' => "Generate {$style} documentation for:\n\n```\n{$code}\n```"
342
]
343
];
344
}
345
}
346
```
347
348
### tests/ToolsTest.php
349
350
```php
351
<?php
352
353
declare(strict_types=1);
354
355
namespace Tests;
356
357
use PHPUnit\Framework\TestCase;
358
use App\Tools\ExampleTool;
359
360
class ToolsTest extends TestCase
361
{
362
private ExampleTool $tool;
363
364
protected function setUp(): void
365
{
366
$this->tool = new ExampleTool();
367
}
368
369
public function testGreet(): void
370
{
371
$result = $this->tool->greet('World');
372
$this->assertSame('Hello, World!', $result);
373
}
374
375
public function testCalculateAdd(): void
376
{
377
$result = $this->tool->performCalculation(5, 3, 'add');
378
$this->assertSame(8.0, $result);
379
}
380
381
public function testCalculateDivide(): void
382
{
383
$result = $this->tool->performCalculation(10, 2, 'divide');
384
$this->assertSame(5.0, $result);
385
}
386
387
public function testCalculateDivideByZero(): void
388
{
389
$this->expectException(\InvalidArgumentException::class);
390
$this->expectExceptionMessage('Division by zero');
391
392
$this->tool->performCalculation(10, 0, 'divide');
393
}
394
395
public function testCalculateInvalidOperation(): void
396
{
397
$this->expectException(\InvalidArgumentException::class);
398
$this->expectExceptionMessage('Invalid operation');
399
400
$this->tool->performCalculation(5, 3, 'modulo');
401
}
402
}
403
```
404
405
### phpunit.xml.dist
406
407
```xml
408
<?xml version="1.0" encoding="UTF-8"?>
409
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
410
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
411
bootstrap="vendor/autoload.php"
412
colors="true">
413
<testsuites>
414
<testsuite name="Test Suite">
415
<directory>tests</directory>
416
</testsuite>
417
</testsuites>
418
<coverage>
419
<include>
420
<directory suffix=".php">src</directory>
421
</include>
422
</coverage>
423
</phpunit>
424
```
425
426
## Implementation Guidelines
427
428
1. **Use PHP Attributes**: Leverage `#[McpTool]`, `#[McpResource]`, `#[McpPrompt]` for clean code
429
2. **Type Declarations**: Use strict types (`declare(strict_types=1);`) in all files
430
3. **PSR-12 Coding Standard**: Follow PHP-FIG standards
431
4. **Schema Validation**: Use `#[Schema]` attributes for parameter validation
432
5. **Error Handling**: Throw specific exceptions with clear messages
433
6. **Testing**: Write PHPUnit tests for all tools
434
7. **Documentation**: Use PHPDoc blocks for all methods
435
8. **Caching**: Always use PSR-16 cache for discovery in production
436
437
## Tool Patterns
438
439
### Simple Tool
440
```php
441
#[McpTool]
442
public function simpleAction(string $input): string
443
{
444
return "Processed: {$input}";
445
}
446
```
447
448
### Tool with Validation
449
```php
450
#[McpTool]
451
public function validateEmail(
452
#[Schema(format: 'email')]
453
string $email
454
): bool {
455
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
456
}
457
```
458
459
### Tool with Enum
460
```php
461
enum Status: string {
462
case ACTIVE = 'active';
463
case INACTIVE = 'inactive';
464
}
465
466
#[McpTool]
467
public function setStatus(string $id, Status $status): array
468
{
469
return ['id' => $id, 'status' => $status->value];
470
}
471
```
472
473
## Resource Patterns
474
475
### Static Resource
476
```php
477
#[McpResource(uri: 'config://settings', mimeType: 'application/json')]
478
public function getSettings(): array
479
{
480
return ['key' => 'value'];
481
}
482
```
483
484
### Dynamic Resource
485
```php
486
#[McpResourceTemplate(uriTemplate: 'user://{id}')]
487
public function getUser(string $id): array
488
{
489
return $this->users[$id] ?? throw new \RuntimeException('User not found');
490
}
491
```
492
493
## Running the Server
494
495
```bash
496
# Install dependencies
497
composer install
498
499
# Run tests
500
vendor/bin/phpunit
501
502
# Start server
503
php server.php
504
505
# Test with inspector
506
npx @modelcontextprotocol/inspector php server.php
507
```
508
509
## Claude Desktop Configuration
510
511
```json
512
{
513
"mcpServers": {
514
"{project-name}": {
515
"command": "php",
516
"args": ["/absolute/path/to/server.php"]
517
}
518
}
519
}
520
```
521
522
Now generate the complete project based on user requirements!
523