Skip to content
Back to search

server

Core PHP implementation for the Model Context Protocol (MCP) server

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/php-mcp--server/badge.svg)](/listings/php-mcp--server)

HTML

<a href="/listings/php-mcp--server"><img src="/api/listings/php-mcp--server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

composer require php-mcp/server

> **๐Ÿ’ก Laravel Users**: Consider using [`php-mcp/laravel`](https://github.com/php-mcp/laravel) for enhanced framework integration, configuration management, and Artisan commands.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md ยท README ยท 1,504 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # PHP MCP Server SDK
  2. [![Latest Version on Packagist](https://img.shields.io/packagist/v/php-mcp/server.svg?style=flat-square)](https://packagist.org/packages/php-mcp/server)
  3. [![Total Downloads](https://img.shields.io/packagist/dt/php-mcp/server.svg?style=flat-square)](https://packagist.org/packages/php-mcp/server)
  4. [![Tests](https://img.shields.io/github/actions/workflow/status/php-mcp/server/tests.yml?branch=main&style=flat-square)](https://github.com/php-mcp/server/actions/workflows/tests.yml)
  5. [![License](https://img.shields.io/packagist/l/php-mcp/server.svg?style=flat-square)](LICENSE)
  6. **A comprehensive PHP SDK for building [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) servers. Create production-ready MCP servers in PHP with modern architecture, extensive testing, and flexible transport options.**
  7. This SDK enables you to expose your PHP application's functionality as standardized MCP **Tools**, **Resources**, and **Prompts**, allowing AI assistants (like Anthropic's Claude, Cursor IDE, OpenAI's ChatGPT, etc.) to interact with your backend using the MCP standard.
  8. ## ๐Ÿš€ Key Features
  9. - **๐Ÿ—๏ธ Modern Architecture**: Built with PHP 8.1+ features, PSR standards, and modular design
  10. - **๐Ÿ“ก Multiple Transports**: Supports `stdio`, `http+sse`, and new **streamable HTTP** with resumability
  11. - **๐ŸŽฏ Attribute-Based Definition**: Use PHP 8 Attributes (`#[McpTool]`, `#[McpResource]`, etc.) for zero-config element registration
  12. - **๐Ÿ”ง Flexible Handlers**: Support for closures, class methods, static methods, and invokable classes
  13. - **๐Ÿ“ Smart Schema Generation**: Automatic JSON schema generation from method signatures with optional `#[Schema]` attribute enhancements
  14. - **โšก Session Management**: Advanced session handling with multiple storage backends
  15. - **๐Ÿ”„ Event-Driven**: ReactPHP-based for high concurrency and non-blocking operations
  16. - **๐Ÿ“Š Batch Processing**: Full support for JSON-RPC batch requests
  17. - **๐Ÿ’พ Smart Caching**: Intelligent caching of discovered elements with manual override precedence
  18. - **๐Ÿงช Completion Providers**: Built-in support for argument completion in tools and prompts
  19. - **๐Ÿ”Œ Dependency Injection**: Full PSR-11 container support with auto-wiring
  20. - **๐Ÿ“‹ Comprehensive Testing**: Extensive test suite with integration tests for all transports
  21. This package supports the **2025-03-26** version of the Model Context Protocol with backward compatibility.
  22. ## ๐Ÿ“‹ Requirements
  23. - **PHP** >= 8.1
  24. - **Composer**
  25. - **For HTTP Transport**: An event-driven PHP environment (CLI recommended)
  26. - **Extensions**: `json`, `mbstring`, `pcre` (typically enabled by default)
  27. ## ๐Ÿ“ฆ Installation
  28. ```bash
  29. composer require php-mcp/server
  30. ```
  31. > **๐Ÿ’ก Laravel Users**: Consider using [`php-mcp/laravel`](https://github.com/php-mcp/laravel) for enhanced framework integration, configuration management, and Artisan commands.
  32. ## โšก Quick Start: Stdio Server with Discovery
  33. This example demonstrates the most common usage pattern - a `stdio` server using attribute discovery.
  34. **1. Define Your MCP Elements**
  35. Create `src/CalculatorElements.php`:
  36. ```php
  37. <?php
  38. namespace App;
  39. use PhpMcp\Server\Attributes\McpTool;
  40. use PhpMcp\Server\Attributes\Schema;
  41. class CalculatorElements
  42. {
  43. /**
  44. * Adds two numbers together.
  45. *
  46. * @param int $a The first number
  47. * @param int $b The second number
  48. * @return int The sum of the two numbers
  49. */
  50. #[McpTool(name: 'add_numbers')]
  51. public function add(int $a, int $b): int
  52. {
  53. return $a + $b;
  54. }
  55. /**
  56. * Calculates power with validation.
  57. */
  58. #[McpTool(name: 'calculate_power')]
  59. public function power(
  60. #[Schema(type: 'number', minimum: 0, maximum: 1000)]
  61. float $base,
  62. #[Schema(type: 'integer', minimum: 0, maximum: 10)]
  63. int $exponent
  64. ): float {
  65. return pow($base, $exponent);
  66. }
  67. }
  68. ```
  69. **2. Create the Server Script**
  70. Create `mcp-server.php`:
  71. ```php
  72. #!/usr/bin/env php
  73. <?php
  74. declare(strict_types=1);
  75. require_once __DIR__ . '/vendor/autoload.php';
  76. use PhpMcp\Server\Server;
  77. use PhpMcp\Server\Transports\StdioServerTransport;
  78. try {
  79. // Build server configuration
  80. $server = Server::make()
  81. ->withServerInfo('PHP Calculator Server', '1.0.0')
  82. ->build();
  83. // Discover MCP elements via attributes
  84. $server->discover(
  85. basePath: __DIR__,
  86. scanDirs: ['src']
  87. );
  88. // Start listening via stdio transport
  89. $transport = new StdioServerTransport();
  90. $server->listen($transport);
  91. } catch (\Throwable $e) {
  92. fwrite(STDERR, "[CRITICAL ERROR] " . $e->getMessage() . "\n");
  93. exit(1);
  94. }
  95. ```
  96. **3. Configure Your MCP Client**
  97. Add to your client configuration (e.g., `.cursor/mcp.json`):
  98. ```json
  99. {
  100. "mcpServers": {
  101. "php-calculator": {
  102. "command": "php",
  103. "args": ["/absolute/path/to/your/mcp-server.php"]
  104. }
  105. }
  106. }
  107. ```
  108. **4. Test the Server**
  109. Your AI assistant can now call:
  110. - `add_numbers` - Add two integers
  111. - `calculate_power` - Calculate power with validation constraints
  112. ## ๐Ÿ—๏ธ Architecture Overview
  113. The PHP MCP Server uses a modern, decoupled architecture:
  114. ```
  115. โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  116. โ”‚ MCP Client โ”‚โ—„โ”€โ”€โ–บโ”‚ Transport โ”‚โ—„โ”€โ”€โ–บโ”‚ Protocol โ”‚
  117. โ”‚ (Claude, etc.) โ”‚ โ”‚ (Stdio/HTTP/SSE) โ”‚ โ”‚ (JSON-RPC) โ”‚
  118. โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  119. โ”‚
  120. โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
  121. โ”‚ Session Manager โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
  122. โ”‚ (Multi-backend) โ”‚ โ”‚
  123. โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
  124. โ”‚
  125. โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
  126. โ”‚ Dispatcher โ”‚โ—„โ”€โ”€โ”€โ”‚ Server Core โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
  127. โ”‚ (Method Router) โ”‚ โ”‚ Configuration โ”‚ โ”‚
  128. โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
  129. โ”‚ โ”‚
  130. โ–ผ โ”‚
  131. โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
  132. โ”‚ Registry โ”‚ โ”‚ Elements โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  133. โ”‚ (Element Store)โ”‚โ—„โ”€โ”€โ–บโ”‚ (Tools/Resources โ”‚
  134. โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ Prompts/etc.) โ”‚
  135. โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  136. ```
  137. ### Core Components
  138. - **`ServerBuilder`**: Fluent configuration interface (`Server::make()->...->build()`)
  139. - **`Server`**: Central coordinator containing all configured components
  140. - **`Protocol`**: JSON-RPC 2.0 handler bridging transports and core logic
  141. - **`SessionManager`**: Multi-backend session storage (array, cache, custom)
  142. - **`Dispatcher`**: Method routing and request processing
  143. - **`Registry`**: Element storage with smart caching and precedence rules
  144. - **`Elements`**: Registered MCP components (Tools, Resources, Prompts, Templates)
  145. ### Transport Options
  146. 1. **`StdioServerTransport`**: Standard I/O for direct client launches
  147. 2. **`HttpServerTransport`**: HTTP + Server-Sent Events for web integration
  148. 3. **`StreamableHttpServerTransport`**: Enhanced HTTP with resumability and event sourcing
  149. ## โš™๏ธ Server Configuration
  150. ### Basic Configuration
  151. ```php
  152. use PhpMcp\Server\Server;
  153. use PhpMcp\Schema\ServerCapabilities;
  154. $server = Server::make()
  155. ->withServerInfo('My App Server', '2.1.0')
  156. ->withCapabilities(ServerCapabilities::make(
  157. resources: true,
  158. resourcesSubscribe: true,
  159. prompts: true,
  160. tools: true
  161. ))
  162. ->withPaginationLimit(100)
  163. ->build();
  164. ```
  165. ### Advanced Configuration with Dependencies
  166. ```php
  167. use Psr\Log\Logger;
  168. use Psr\SimpleCache\CacheInterface;
  169. use Psr\Container\ContainerInterface;
  170. $server = Server::make()
  171. ->withServerInfo('Production Server', '1.0.0')
  172. ->withLogger($myPsrLogger) // PSR-3 Logger
  173. ->withCache($myPsrCache) // PSR-16 Cache
  174. ->withContainer($myPsrContainer) // PSR-11 Container
  175. ->withSession('cache', 7200) // Cache-backed sessions, 2hr TTL
  176. ->withPaginationLimit(50) // Limit list responses
  177. ->build();
  178. ```
  179. ### Session Management Options
  180. ```php
  181. // In-memory sessions (default, not persistent)
  182. ->withSession('array', 3600)
  183. // Cache-backed sessions (persistent across restarts)
  184. ->withSession('cache', 7200)
  185. // Custom session handler (implement SessionHandlerInterface)
  186. ->withSessionHandler(new MyCustomSessionHandler(), 1800)
  187. ```
  188. ## ๐ŸŽฏ Defining MCP Elements
  189. The server provides two powerful ways to define MCP elements: **Attribute-Based Discovery** (recommended) and **Manual Registration**. Both can be combined, with manual registrations taking precedence.
  190. ### Element Types
  191. - **๐Ÿ”ง Tools**: Executable functions/actions (e.g., `calculate`, `send_email`, `query_database`)
  192. - **๐Ÿ“„ Resources**: Static content/data (e.g., `config://settings`, `file://readme.txt`)
  193. - **๐Ÿ“‹ Resource Templates**: Dynamic resources with URI patterns (e.g., `user://{id}/profile`)
  194. - **๐Ÿ’ฌ Prompts**: Conversation starters/templates (e.g., `summarize`, `translate`)
  195. ### 1. ๐Ÿท๏ธ Attribute-Based Discovery (Recommended)
  196. Use PHP 8 attributes to mark methods or invokable classes as MCP elements. The server will discover them via filesystem scanning.
  197. ```php
  198. use PhpMcp\Server\Attributes\{McpTool, McpResource, McpResourceTemplate, McpPrompt};
  199. class UserManager
  200. {
  201. /**
  202. * Creates a new user account.
  203. */
  204. #[McpTool(name: 'create_user')]
  205. public function createUser(string $email, string $password, string $role = 'user'): array
  206. {
  207. // Create user logic
  208. return ['id' => 123, 'email' => $email, 'role' => $role];
  209. }
  210. /**
  211. * Get user configuration.
  212. */
  213. #[McpResource(
  214. uri: 'config://user/settings',
  215. mimeType: 'application/json'
  216. )]
  217. public function getUserConfig(): array
  218. {
  219. return ['theme' => 'dark', 'notifications' => true];
  220. }
  221. /**
  222. * Get user profile by ID.
  223. */
  224. #[McpResourceTemplate(
  225. uriTemplate: 'user://{userId}/profile',
  226. mimeType: 'application/json'
  227. )]
  228. public function getUserProfile(string $userId): array
  229. {
  230. return ['id' => $userId, 'name' => 'John Doe'];
  231. }
  232. /**
  233. * Generate welcome message prompt.
  234. */
  235. #[McpPrompt(name: 'welcome_user')]
  236. public function welcomeUserPrompt(string $username, string $role): array
  237. {
  238. return [
  239. ['role' => 'user', 'content' => "Create a welcome message for {$username} with role {$role}"]
  240. ];
  241. }
  242. }
  243. ```
  244. **Discovery Process:**
  245. ```php
  246. // Build server first
  247. $server = Server::make()
  248. ->withServerInfo('My App Server', '1.0.0')
  249. ->build();
  250. // Then discover elements
  251. $server->discover(
  252. basePath: __DIR__,
  253. scanDirs: ['src/Handlers', 'src/Services'], // Directories to scan
  254. excludeDirs: ['src/Tests'], // Directories to skip
  255. saveToCache: true // Cache results (default: true)
  256. );
  257. ```
  258. **Available Attributes:**
  259. - **`#[McpTool]`**: Executable actions
  260. - **`#[McpResource]`**: Static content accessible via URI
  261. - **`#[McpResourceTemplate]`**: Dynamic resources with URI templates
  262. - **`#[McpPrompt]`**: Conversation templates and prompt generators
  263. ### 2. ๐Ÿ”ง Manual Registration
  264. Register elements programmatically using the `ServerBuilder` before calling `build()`. Useful for dynamic registration, closures, or when you prefer explicit control.
  265. ```php
  266. use App\Handlers\{EmailHandler, ConfigHandler, UserHandler, PromptHandler};
  267. use PhpMcp\Schema\{ToolAnnotations, Annotations};
  268. $server = Server::make()
  269. ->withServerInfo('Manual Registration Server', '1.0.0')
  270. // Register a tool with handler method
  271. ->withTool(
  272. [EmailHandler::class, 'sendEmail'], // Handler: [class, method]
  273. name: 'send_email', // Tool name (optional)
  274. description: 'Send email to user', // Description (optional)
  275. annotations: ToolAnnotations::make( // Annotations (optional)
  276. title: 'Send Email Tool'
  277. )
  278. )
  279. // Register invokable class as tool
  280. ->withTool(UserHandler::class) // Handler: Invokable class
  281. // Register a closure as tool
  282. ->withTool(
  283. function(int $a, int $b): int { // Handler: Closure
  284. return $a + $b;
  285. },
  286. name: 'add_numbers',
  287. description: 'Add two numbers together'
  288. )
  289. // Register a resource with closure
  290. ->withResource(
  291. function(): array { // Handler: Closure
  292. return ['timestamp' => time(), 'server' => 'php-mcp'];
  293. },
  294. uri: 'config://runtime/status', // URI (required)
  295. mimeType: 'application/json' // MIME type (optional)
  296. )
  297. // Register a resource template
  298. ->withResourceTemplate(
  299. [UserHandler::class, 'getUserProfile'],
  300. uriTemplate: 'user://{userId}/profile' // URI template (required)
  301. )
  302. // Register a prompt with closure
  303. ->withPrompt(
  304. function(string $topic, string $tone = 'professional'): array {
  305. return [
  306. ['role' => 'user', 'content' => "Write about {$topic} in a {$tone} tone"]
  307. ];
  308. },
  309. name: 'writing_prompt' // Prompt name (optional)
  310. )
  311. ->build();
  312. ```
  313. The server supports three flexible handler formats: `[ClassName::class, 'methodName']` for class method handlers, `InvokableClass::class` for invokable class handlers (classes with `__invoke` method), and any PHP callable including closures, static methods like `[SomeClass::class, 'staticMethod']`, or function names. Class-based handlers are resolved via the configured PSR-11 container for dependency injection. Manual registrations are never cached and take precedence over discovered elements with the same identifier.
  314. > [!IMPORTANT]
  315. > When using closures as handlers, the server generates minimal JSON schemas based only on PHP type hints since there are no docblocks or class context available. For more detailed schemas with validation constraints, descriptions, and formats, you have two options:
  316. >
  317. > - Use the [`#[Schema]` attribute](#-schema-generation-and-validation) for enhanced schema generation
  318. > - Provide a custom `$inputSchema` parameter when registering tools with `->withTool()`
  319. ### ๐Ÿ† Element Precedence & Discovery
  320. **Precedence Rules:**
  321. - Manual registrations **always** override discovered/cached elements with the same identifier
  322. - Discovered elements are cached for performance (configurable)
  323. - Cache is automatically invalidated on fresh discovery runs
  324. **Discovery Process:**
  325. ```php
  326. $server->discover(
  327. basePath: __DIR__,
  328. scanDirs: ['src/Handlers', 'src/Services'], // Scan these directories
  329. excludeDirs: ['tests', 'vendor'], // Skip these directories
  330. force: false, // Force re-scan (default: false)
  331. saveToCache: true // Save to cache (default: true)
  332. );
  333. ```
  334. **Caching Behavior:**
  335. - Only **discovered** elements are cached (never manual registrations)
  336. - Cache loaded automatically during `build()` if available
  337. - Fresh `discover()` calls clear and rebuild cache
  338. - Use `force: true` to bypass discovery-already-ran check
  339. ## ๐Ÿš€ Running the Server (Transports)
  340. The server core is transport-agnostic. Choose a transport based on your deployment needs:
  341. ### 1. ๐Ÿ“Ÿ Stdio Transport
  342. **Best for**: Direct client execution, command-line tools, simple deployments
  343. ```php
  344. use PhpMcp\Server\Transports\StdioServerTransport;
  345. $server = Server::make()
  346. ->withServerInfo('Stdio Server', '1.0.0')
  347. ->build();
  348. $server->discover(__DIR__, ['src']);
  349. // Create stdio transport (uses STDIN/STDOUT by default)
  350. $transport = new StdioServerTransport();
  351. // Start listening (blocking call)
  352. $server->listen($transport);
  353. ```
  354. **Client Configuration:**
  355. ```json
  356. {
  357. "mcpServers": {
  358. "my-php-server": {
  359. "command": "php",
  360. "args": ["/absolute/path/to/server.php"]
  361. }
  362. }
  363. }
  364. ```
  365. > โš ๏ธ **Important**: When using stdio transport, **never** write to `STDOUT` in your handlers (use `STDERR` for debugging). `STDOUT` is reserved for JSON-RPC communication.
  366. ### 2. ๐ŸŒ HTTP + Server-Sent Events Transport (Deprecated)
  367. > โš ๏ธ **Note**: This transport is deprecated in the latest MCP protocol version but remains available for backwards compatibility. For new projects, use the [StreamableHttpServerTransport](#3--streamable-http-transport-new) which provides enhanced features and better protocol compliance.
  368. **Best for**: Legacy applications requiring backwards compatibility
  369. ```php
  370. use PhpMcp\Server\Transports\HttpServerTransport;
  371. $server = Server::make()
  372. ->withServerInfo('HTTP Server', '1.0.0')
  373. ->withLogger($logger) // Recommended for HTTP
  374. ->build();
  375. $server->discover(__DIR__, ['src']);
  376. // Create HTTP transport
  377. $transport = new HttpServerTransport(
  378. host: '127.0.0.1', // MCP protocol prohibits 0.0.0.0
  379. port: 8080, // Port number
  380. mcpPathPrefix: 'mcp' // URL prefix (/mcp/sse, /mcp/message)
  381. );
  382. $server->listen($transport);
  383. ```
  384. **Client Configuration:**
  385. ```json
  386. {
  387. "mcpServers": {
  388. "my-http-server": {
  389. "url": "http://localhost:8080/mcp/sse"
  390. }
  391. }
  392. }
  393. ```
  394. **Endpoints:**
  395. - **SSE Connection**: `GET /mcp/sse`
  396. - **Message Sending**: `POST /mcp/message?clientId={clientId}`
  397. ### 3. ๐Ÿ”„ Streamable HTTP Transport (Recommended)
  398. **Best for**: Production deployments, remote MCP servers, multiple clients, resumable connections
  399. ```php
  400. use PhpMcp\Server\Transports\StreamableHttpServerTransport;
  401. $server = Server::make()
  402. ->withServerInfo('Streamable Server', '1.0.0')
  403. ->withLogger($logger)
  404. ->withCache($cache) // Required for resumability
  405. ->build();
  406. $server->discover(__DIR__, ['src']);
  407. // Create streamable transport with resumability
  408. $transport = new StreamableHttpServerTransport(
  409. host: '127.0.0.1', // MCP protocol prohibits 0.0.0.0
  410. port: 8080,
  411. mcpPathPrefix: 'mcp',
  412. enableJsonResponse: false, // Use SSE streaming (default)
  413. stateless: false // Enable stateless mode for session-less clients
  414. );
  415. $server->listen($transport);
  416. ```
  417. **JSON Response Mode:**
  418. The `enableJsonResponse` option controls how responses are delivered:
  419. - **`false` (default)**: Uses Server-Sent Events (SSE) streams for responses. Best for tools that may take time to process.
  420. - **`true`**: Returns immediate JSON responses without opening SSE streams. Use this when your tools execute quickly and don't need streaming.
  421. ```php
  422. // For fast-executing tools, enable JSON mode
  423. $transport = new StreamableHttpServerTransport(
  424. host: '127.0.0.1',
  425. port: 8080,
  426. enableJsonResponse: true // Immediate JSON responses
  427. );
  428. ```
  429. **Stateless Mode:**
  430. For clients that have issues with session management, enable stateless mode:
  431. ```php
  432. $transport = new StreamableHttpServerTransport(
  433. host: '127.0.0.1',
  434. port: 8080,
  435. stateless: true // Each request is independent
  436. );
  437. ```
  438. In stateless mode, session IDs are generated internally but not exposed to clients, and each request is treated as independent without persistent session state.
  439. **Features:**
  440. - **Resumable connections** - clients can reconnect and replay missed events
  441. - **Event sourcing** - all events are stored for replay
  442. - **JSON mode** - optional JSON-only responses for fast tools
  443. - **Enhanced session management** - persistent session state
  444. - **Multiple client support** - designed for concurrent clients
  445. - **Stateless mode** - session-less operation for simple clients
  446. ## ๐Ÿ“‹ Schema Generation and Validation
  447. The server automatically generates JSON schemas for tool parameters using a sophisticated priority system that combines PHP type hints, docblock information, and the optional `#[Schema]` attribute. These generated schemas are used both for input validation and for providing schema information to MCP clients.
  448. ### Schema Generation Priority
  449. The server follows this order of precedence when generating schemas:
  450. 1. **`#[Schema]` attribute with `definition`** - Complete schema override (highest precedence)
  451. 2. **Parameter-level `#[Schema]` attribute** - Parameter-specific schema enhancements
  452. 3. **Method-level `#[Schema]` attribute** - Method-wide schema configuration
  453. 4. **PHP type hints + docblocks** - Automatic inference from code (lowest precedence)
  454. When a `definition` is provided in the Schema attribute, all automatic inference is bypassed and the complete definition is used as-is.
  455. ### Parameter-Level Schema Attributes
  456. ```php
  457. use PhpMcp\Server\Attributes\{McpTool, Schema};
  458. #[McpTool(name: 'validate_user')]
  459. public function validateUser(
  460. #[Schema(format: 'email')] // PHP already knows it's string
  461. string $email,
  462. #[Schema(
  463. pattern: '^[A-Z][a-z]+$',
  464. description: 'Capitalized name'
  465. )]
  466. string $name,
  467. #[Schema(minimum: 18, maximum: 120)] // PHP already knows it's integer
  468. int $age
  469. ): bool {
  470. return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
  471. }
  472. ```
  473. ### Method-Level Schema
  474. ```php
  475. /**
  476. * Process user data with nested validation.
  477. */
  478. #[McpTool(name: 'create_user')]
  479. #[Schema(
  480. properties: [
  481. 'profile' => [
  482. 'type' => 'object',
  483. 'properties' => [
  484. 'name' => ['type' => 'string', 'minLength' => 2],
  485. 'age' => ['type' => 'integer', 'minimum' => 18],
  486. 'email' => ['type' => 'string', 'format' => 'email']
  487. ],
  488. 'required' => ['name', 'email']
  489. ]
  490. ],
  491. required: ['profile']
  492. )]
  493. public function createUser(array $userData): array
  494. {
  495. // PHP type hint provides base 'array' type
  496. // Method-level Schema adds object structure validation
  497. return ['id' => 123, 'status' => 'created'];
  498. }
  499. ```
  500. ### Complete Schema Override (Method-Level Only)
  501. ```php
  502. #[McpTool(name: 'process_api_request')]
  503. #[Schema(definition: [
  504. 'type' => 'object',
  505. 'properties' => [
  506. 'endpoint' => ['type' => 'string', 'format' => 'uri'],
  507. 'method' => ['type' => 'string', 'enum' => ['GET', 'POST', 'PUT', 'DELETE']],
  508. 'headers' => [
  509. 'type' => 'object',
  510. 'patternProperties' => [
  511. '^[A-Za-z0-9-]+$' => ['type' => 'string']
  512. ]
  513. ]
  514. ],
  515. 'required' => ['endpoint', 'method']
  516. ])]
  517. public function processApiRequest(string $endpoint, string $method, array $headers): array
  518. {
  519. // PHP type hints are completely ignored when definition is provided
  520. // The schema definition above takes full precedence
  521. return ['status' => 'processed', 'endpoint' => $endpoint];
  522. }
  523. ```
  524. > โš ๏ธ **Important**: Complete schema definition override should rarely be used. It bypasses all automatic schema inference and requires you to define the entire JSON schema manually. Only use this if you're well-versed with JSON Schema specification and have complex validation requirements that cannot be achieved through the priority system. In most cases, parameter-level and method-level `#[Schema]` attributes provide sufficient flexibility.
  525. ## ๐ŸŽจ Return Value Formatting
  526. The server automatically formats return values from your handlers into appropriate MCP content types:
  527. ### Automatic Formatting
  528. ```php
  529. // Simple values are auto-wrapped in TextContent
  530. public function getString(): string { return "Hello World"; } // โ†’ TextContent
  531. public function getNumber(): int { return 42; } // โ†’ TextContent
  532. public function getBool(): bool { return true; } // โ†’ TextContent
  533. public function getArray(): array { return ['key' => 'value']; } // โ†’ TextContent (JSON)
  534. // Null handling
  535. public function getNull(): ?string { return null; } // โ†’ TextContent("(null)")
  536. public function returnVoid(): void { /* no return */ } // โ†’ Empty content
  537. ```
  538. ### Advanced Content Types
  539. ```php
  540. use PhpMcp\Schema\Content\{TextContent, ImageContent, AudioContent, ResourceContent};
  541. public function getFormattedCode(): TextContent
  542. {
  543. return TextContent::code('<?php echo "Hello";', 'php');
  544. }
  545. public function getMarkdown(): TextContent
  546. {
  547. return TextContent::make('# Title\n\nContent here');
  548. }
  549. public function getImage(): ImageContent
  550. {
  551. return ImageContent::make(
  552. data: base64_encode(file_get_contents('image.png')),
  553. mimeType: 'image/png'
  554. );
  555. }
  556. public function getAudio(): AudioContent
  557. {
  558. return AudioContent::make(
  559. data: base64_encode(file_get_contents('audio.mp3')),
  560. mimeType: 'audio/mpeg'
  561. );
  562. }
  563. ```
  564. ### File and Stream Handling
  565. ```php
  566. // File objects are automatically read and formatted
  567. public function getFileContent(): \SplFileInfo
  568. {
  569. return new \SplFileInfo('/path/to/file.txt'); // Auto-detects MIME type
  570. }
  571. // Stream resources are read completely
  572. public function getStreamContent()
  573. {
  574. $stream = fopen('/path/to/data.json', 'r');
  575. return $stream; // Will be read and closed automatically
  576. }
  577. // Structured resource responses
  578. public function getStructuredResource(): array
  579. {
  580. return [
  581. 'text' => 'File content here',
  582. 'mimeType' => 'text/plain'
  583. ];
  584. // Or for binary data:
  585. // return [
  586. // 'blob' => base64_encode($binaryData),
  587. // 'mimeType' => 'application/octet-stream'
  588. // ];
  589. }
  590. ```
  591. ## ๐Ÿ”„ Batch Processing
  592. The server automatically handles JSON-RPC batch requests:
  593. ```php
  594. // Client can send multiple requests in a single HTTP call:
  595. [
  596. {"jsonrpc": "2.0", "id": "1", "method": "tools/call", "params": {...}},
  597. {"jsonrpc": "2.0", "method": "notifications/ping"}, // notification
  598. {"jsonrpc": "2.0", "id": "2", "method": "tools/call", "params": {...}}
  599. ]
  600. // Server returns batch response (excluding notifications):
  601. [
  602. {"jsonrpc": "2.0", "id": "1", "result": {...}},
  603. {"jsonrpc": "2.0", "id": "2", "result": {...}}
  604. ]
  605. ```
  606. ## ๐Ÿ”ง Advanced Features
  607. ### Completion Providers
  608. Completion providers enable MCP clients to offer auto-completion suggestions in their user interfaces. They are specifically designed for **Resource Templates** and **Prompts** to help users discover available options for dynamic parts like template variables or prompt arguments.
  609. > **Note**: Tools and resources can be discovered via standard MCP commands (`tools/list`, `resources/list`), so completion providers are not needed for them. Completion providers are used only for resource templates (URI variables) and prompt arguments.
  610. The `#[CompletionProvider]` attribute supports three types of completion sources:
  611. #### 1. Custom Provider Classes
  612. For complex completion logic, implement the `CompletionProviderInterface`:
  613. ```php
  614. use PhpMcp\Server\Contracts\CompletionProviderInterface;
  615. use PhpMcp\Server\Contracts\SessionInterface;
  616. use PhpMcp\Server\Attributes\{McpResourceTemplate, CompletionProvider};
  617. class UserIdCompletionProvider implements CompletionProviderInterface
  618. {
  619. public function __construct(private DatabaseService $db) {}
  620. public function getCompletions(string $currentValue, SessionInterface $session): array
  621. {
  622. // Dynamic completion from database
  623. return $this->db->searchUsers($currentValue);
  624. }
  625. }
  626. class UserService
  627. {
  628. #[McpResourceTemplate(uriTemplate: 'user://{userId}/profile')]
  629. public function getUserProfile(
  630. #[CompletionProvider(provider: UserIdCompletionProvider::class)] // Class string - resolved from container
  631. string $userId
  632. ): array {
  633. return ['id' => $userId, 'name' => 'John Doe'];
  634. }
  635. }
  636. ```
  637. You can also pass pre-configured provider instances:
  638. ```php
  639. class DocumentService
  640. {
  641. #[McpPrompt(name: 'document_prompt')]
  642. public function generatePrompt(
  643. #[CompletionProvider(provider: new UserIdCompletionProvider($database))] // Pre-configured instance
  644. string $userId,
  645. #[CompletionProvider(provider: $this->categoryProvider)] // Instance from property
  646. string $category
  647. ): array {
  648. return [['role' => 'user', 'content' => "Generate document for user {$userId} in {$category}"]];
  649. }
  650. }
  651. ```
  652. #### 2. Simple List Completions
  653. For static completion lists, use the `values` parameter:
  654. ```php
  655. use PhpMcp\Server\Attributes\{McpPrompt, CompletionProvider};
  656. class ContentService
  657. {
  658. #[McpPrompt(name: 'content_generator')]
  659. public function generateContent(
  660. #[CompletionProvider(values: ['blog', 'article', 'tutorial', 'guide', 'documentation'])]
  661. string $contentType,
  662. #[CompletionProvider(values: ['beginner', 'intermediate', 'advanced', 'expert'])]
  663. string $difficulty
  664. ): array {
  665. return [['role' => 'user', 'content' => "Create a {$difficulty} level {$contentType}"]];
  666. }
  667. }
  668. ```
  669. #### 3. Enum-Based Completions
  670. For enum classes, use the `enum` parameter:
  671. ```php
  672. enum Priority: string
  673. {
  674. case LOW = 'low';
  675. case MEDIUM = 'medium';
  676. case HIGH = 'high';
  677. case CRITICAL = 'critical';
  678. }
  679. enum Status // Unit enum (no backing values)
  680. {
  681. case DRAFT;
  682. case PUBLISHED;
  683. case ARCHIVED;
  684. }
  685. class TaskService
  686. {
  687. #[McpTool(name: 'create_task')]
  688. public function createTask(
  689. string $title,
  690. #[CompletionProvider(enum: Priority::class)] // String-backed enum uses values
  691. string $priority,
  692. #[CompletionProvider(enum: Status::class)] // Unit enum uses case names
  693. string $status
  694. ): array {
  695. return ['id' => 123, 'title' => $title, 'priority' => $priority, 'status' => $status];
  696. }
  697. }
  698. ```
  699. #### Manual Registration with Completion Providers
  700. ```php
  701. $server = Server::make()
  702. ->withServerInfo('Completion Demo', '1.0.0')
  703. // Using provider class (resolved from container)
  704. ->withPrompt(
  705. [DocumentHandler::class, 'generateReport'],
  706. name: 'document_report'
  707. // Completion providers are auto-discovered from method attributes
  708. )
  709. // Using closure with inline completion providers
  710. ->withPrompt(
  711. function(
  712. #[CompletionProvider(values: ['json', 'xml', 'csv', 'yaml'])]
  713. string $format,
  714. #[CompletionProvider(enum: Priority::class)]
  715. string $priority
  716. ): array {
  717. return [['role' => 'user', 'content' => "Export data in {$format} format with {$priority} priority"]];
  718. },
  719. name: 'export_data'
  720. )
  721. ->build();
  722. ```
  723. #### Completion Provider Resolution
  724. The server automatically handles provider resolution:
  725. - **Class strings** (`MyProvider::class`) โ†’ Resolved from PSR-11 container with dependency injection
  726. - **Instances** (`new MyProvider()`) โ†’ Used directly as-is
  727. - **Values arrays** (`['a', 'b', 'c']`) โ†’ Automatically wrapped in `ListCompletionProvider`
  728. - **Enum classes** (`MyEnum::class`) โ†’ Automatically wrapped in `EnumCompletionProvider`
  729. > **Important**: Completion providers only offer suggestions to users in the MCP client interface. Users can still input any value, so always validate parameters in your handlers regardless of completion provider constraints.
  730. ### Custom Dependency Injection
  731. Your MCP element handlers can use constructor dependency injection to access services like databases, APIs, or other business logic. When handlers have constructor dependencies, you must provide a pre-configured PSR-11 container that contains those dependencies.
  732. By default, the server uses a `BasicContainer` - a simple implementation that attempts to auto-wire dependencies by instantiating classes with parameterless constructors. For dependencies that require configuration (like database connections), you can either manually add them to the BasicContainer or use a more advanced PSR-11 container like PHP-DI or Laravel's container.
  733. ```php
  734. use Psr\Container\ContainerInterface;
  735. class DatabaseService
  736. {
  737. public function __construct(private \PDO $pdo) {}
  738. #[McpTool(name: 'query_users')]
  739. public function queryUsers(): array
  740. {
  741. $stmt = $this->pdo->query('SELECT * FROM users');
  742. return $stmt->fetchAll();
  743. }
  744. }
  745. // Option 1: Use the basic container and manually add dependencies
  746. $basicContainer = new \PhpMcp\Server\Defaults\BasicContainer();
  747. $basicContainer->set(\PDO::class, new \PDO('sqlite::memory:'));
  748. // Option 2: Use any PSR-11 compatible container (PHP-DI, Laravel, etc.)
  749. $container = new \DI\Container();
  750. $container->set(\PDO::class, new \PDO('mysql:host=localhost;dbname=app', $user, $pass));
  751. $server = Server::make()
  752. ->withContainer($basicContainer) // Handlers get dependencies auto-injected
  753. ->build();
  754. ```
  755. ### Resource Subscriptions
  756. ```php
  757. use PhpMcp\Schema\ServerCapabilities;
  758. $server = Server::make()
  759. ->withCapabilities(ServerCapabilities::make(
  760. resourcesSubscribe: true, // Enable resource subscriptions
  761. prompts: true,
  762. tools: true
  763. ))
  764. ->build();
  765. // In your resource handler, you can notify clients of changes:
  766. #[McpResource(uri: 'file://config.json')]
  767. public function getConfig(): array
  768. {
  769. // When config changes, notify subscribers
  770. $this->notifyResourceChange('file://config.json');
  771. return ['setting' => 'value'];
  772. }
  773. ```
  774. ### Resumability and Event Store
  775. For production deployments using `StreamableHttpServerTransport`, you can implement resumability with event sourcing by providing a custom event store:
  776. ```php
  777. use PhpMcp\Server\Contracts\EventStoreInterface;
  778. use PhpMcp\Server\Defaults\InMemoryEventStore;
  779. use PhpMcp\Server\Transports\StreamableHttpServerTransport;
  780. // Use the built-in in-memory event store (for development/testing)
  781. $eventStore = new InMemoryEventStore();
  782. // Or implement your own persistent event store
  783. class DatabaseEventStore implements EventStoreInterface
  784. {
  785. public function storeEvent(string $streamId, string $message): string
  786. {
  787. // Store event in database and return unique event ID
  788. return $this->database->insert('events', [
  789. 'stream_id' => $streamId,
  790. 'message' => $message,
  791. 'created_at' => now()
  792. ]);
  793. }
  794. public function replayEventsAfter(string $lastEventId, callable $sendCallback): void
  795. {
  796. // Replay events for resumability
  797. $events = $this->database->getEventsAfter($lastEventId);
  798. foreach ($events as $event) {
  799. $sendCallback($event['id'], $event['message']);
  800. }
  801. }
  802. }
  803. // Configure transport with event store
  804. $transport = new StreamableHttpServerTransport(
  805. host: '127.0.0.1',
  806. port: 8080,
  807. eventStore: new DatabaseEventStore() // Enable resumability
  808. );
  809. ```
  810. ### Custom Session Handlers
  811. Implement custom session storage by creating a class that implements `SessionHandlerInterface`:
  812. ```php
  813. use PhpMcp\Server\Contracts\SessionHandlerInterface;
  814. class DatabaseSessionHandler implements SessionHandlerInterface
  815. {
  816. public function __construct(private \PDO $db) {}
  817. public function read(string $id): string|false
  818. {
  819. $stmt = $this->db->prepare('SELECT data FROM sessions WHERE id = ?');
  820. $stmt->execute([$id]);
  821. $session = $stmt->fetch(\PDO::FETCH_ASSOC);
  822. return $session ? $session['data'] : false;
  823. }
  824. public function write(string $id, string $data): bool
  825. {
  826. $stmt = $this->db->prepare(
  827. 'INSERT OR REPLACE INTO sessions (id, data, updated_at) VALUES (?, ?, ?)'
  828. );
  829. return $stmt->execute([$id, $data, time()]);
  830. }
  831. public function destroy(string $id): bool
  832. {
  833. $stmt = $this->db->prepare('DELETE FROM sessions WHERE id = ?');
  834. return $stmt->execute([$id]);
  835. }
  836. public function gc(int $maxLifetime): array
  837. {
  838. $cutoff = time() - $maxLifetime;
  839. $stmt = $this->db->prepare('DELETE FROM sessions WHERE updated_at < ?');
  840. $stmt->execute([$cutoff]);
  841. return []; // Return array of cleaned session IDs if needed
  842. }
  843. }
  844. // Use custom session handler
  845. $server = Server::make()
  846. ->withSessionHandler(new DatabaseSessionHandler(), 3600)
  847. ->build();
  848. ```
  849. ### Middleware Support
  850. Both `HttpServerTransport` and `StreamableHttpServerTransport` support PSR-7 compatible middleware for intercepting and modifying HTTP requests and responses. Middleware allows you to extract common functionality like authentication, logging, CORS handling, and request validation into reusable components.
  851. Middleware must be a valid PHP callable that accepts a PSR-7 `ServerRequestInterface` as the first argument and a `callable` as the second argument.
  852. ```php
  853. use Psr\Http\Message\ServerRequestInterface;
  854. use Psr\Http\Message\ResponseInterface;
  855. use React\Promise\PromiseInterface;
  856. class AuthMiddleware
  857. {
  858. public function __invoke(ServerRequestInterface $request, callable $next)
  859. {
  860. $apiKey = $request->getHeaderLine('Authorization');
  861. if (empty($apiKey)) {
  862. return new Response(401, [], 'Authorization required');
  863. }
  864. $request = $request->withAttribute('user_id', $this->validateApiKey($apiKey));
  865. $result = $next($request);
  866. return match (true) {
  867. $result instanceof PromiseInterface => $result->then(fn($response) => $this->handle($response)),
  868. $result instanceof ResponseInterface => $this->handle($result),
  869. default => $result
  870. };
  871. }
  872. private function handle($response)
  873. {
  874. return $response instanceof ResponseInterface
  875. ? $response->withHeader('X-Auth-Provider', 'mcp-server')
  876. : $response;
  877. }
  878. }
  879. $middlewares = [
  880. new AuthMiddleware(),
  881. new LoggingMiddleware(),
  882. function(ServerRequestInterface $request, callable $next) {
  883. $result = $next($request);
  884. return match (true) {
  885. $result instanceof PromiseInterface => $result->then(function($response) {
  886. return $response instanceof ResponseInterface
  887. ? $response->withHeader('Access-Control-Allow-Origin', '*')
  888. : $response;
  889. }),
  890. $result instanceof ResponseInterface => $result->withHeader('Access-Control-Allow-Origin', '*'),
  891. default => $result
  892. };
  893. }
  894. ];
  895. $transport = new StreamableHttpServerTransport(
  896. host: '127.0.0.1',
  897. port: 8080,
  898. middlewares: $middlewares
  899. );
  900. ```
  901. **Important Considerations:**
  902. - **Response Handling**: Middleware must handle both synchronous `ResponseInterface` and asynchronous `PromiseInterface` returns from `$next($request)`, since ReactPHP operates asynchronously
  903. - **Invokable Pattern**: The recommended pattern is to use invokable classes with a separate `handle()` method to process responses, making the async logic reusable
  904. - **Execution Order**: Middleware executes in the order provided, with the last middleware being closest to your MCP handlers
  905. ### SSL Context Configuration
  906. For HTTPS deployments of `StreamableHttpServerTransport`, configure SSL context options:
  907. ```php
  908. $sslContext = [
  909. 'ssl' => [
  910. 'local_cert' => '/path/to/certificate.pem',
  911. 'local_pk' => '/path/to/private-key.pem',
  912. 'verify_peer' => false,
  913. 'allow_self_signed' => true,
  914. ]
  915. ];
  916. $transport = new StreamableHttpServerTransport(
  917. host: '0.0.0.0',
  918. port: 8443,
  919. sslContext: $sslContext
  920. );
  921. ```
  922. > **SSL Context Reference**: For complete SSL context options, see the [PHP SSL Context Options documentation](https://www.php.net/manual/en/context.ssl.php).
  923. ## ๐Ÿ” Error Handling & Debugging
  924. The server provides comprehensive error handling and debugging capabilities:
  925. ### Exception Handling
  926. Tool handlers can throw any PHP exception when errors occur. The server automatically converts these exceptions into proper JSON-RPC error responses for MCP clients.
  927. ```php
  928. #[McpTool(name: 'divide_numbers')]
  929. public function divideNumbers(float $dividend, float $divisor): float
  930. {
  931. if ($divisor === 0.0) {
  932. // Any exception with descriptive message will be sent to client
  933. throw new \InvalidArgumentException('Division by zero is not allowed');
  934. }
  935. return $dividend / $divisor;
  936. }
  937. #[McpTool(name: 'calculate_factorial')]
  938. public function calculateFactorial(int $number): int
  939. {
  940. if ($number < 0) {
  941. throw new \InvalidArgumentException('Factorial is not defined for negative numbers');
  942. }
  943. if ($number > 20) {
  944. throw new \OverflowException('Number too large, factorial would cause overflow');
  945. }
  946. // Implementation continues...
  947. return $this->factorial($number);
  948. }
  949. ```
  950. The server will convert these exceptions into appropriate JSON-RPC error responses that MCP clients can understand and display to users.
  951. ### Logging and Debugging
  952. ```php
  953. use Psr\Log\LoggerInterface;
  954. class DebugAwareHandler
  955. {
  956. public function __construct(private LoggerInterface $logger) {}
  957. #[McpTool(name: 'debug_tool')]
  958. public function debugTool(string $data): array
  959. {
  960. $this->logger->info('Processing debug tool', ['input' => $data]);
  961. // For stdio transport, use STDERR for debug output
  962. fwrite(STDERR, "Debug: Processing data length: " . strlen($data) . "\n");
  963. return ['processed' => true];
  964. }
  965. }
  966. ```
  967. ## ๐Ÿš€ Production Deployment
  968. Since `$server->listen()` runs a persistent process, you can deploy it using any strategy that suits your infrastructure needs. The server can be deployed on VPS, cloud instances, containers, or any environment that supports long-running processes.
  969. Here are two popular deployment approaches to consider:
  970. ### Option 1: VPS with Supervisor + Nginx (Recommended)
  971. **Best for**: Most production deployments, cost-effective, full control
  972. ```bash
  973. # 1. Install your application on VPS
  974. git clone https://github.com/yourorg/your-mcp-server.git /var/www/mcp-server
  975. cd /var/www/mcp-server
  976. composer install --no-dev --optimize-autoloader
  977. # 2. Install Supervisor
  978. sudo apt-get install supervisor
  979. # 3. Create Supervisor configuration
  980. sudo nano /etc/supervisor/conf.d/mcp-server.conf
  981. ```
  982. **Supervisor Configuration:**
  983. ```ini
  984. [program:mcp-server]
  985. process_name=%(program_name)s_%(process_num)02d
  986. command=php /var/www/mcp-server/server.php --transport=http --host=127.0.0.1 --port=8080
  987. autostart=true
  988. autorestart=true
  989. stopasgroup=true
  990. killasgroup=true
  991. user=www-data
  992. numprocs=1
  993. redirect_stderr=true
  994. stdout_logfile=/var/log/mcp-server.log
  995. stdout_logfile_maxbytes=10MB
  996. stdout_logfile_backups=3
  997. ```
  998. **Nginx Configuration with SSL:**
  999. ```nginx
  1000. # /etc/nginx/sites-available/mcp-server
  1001. server {
  1002. listen 443 ssl http2;
  1003. listen [::]:443 ssl http2;
  1004. server_name mcp.yourdomain.com;
  1005. # SSL configuration
  1006. ssl_certificate /etc/letsencrypt/live/mcp.yourdomain.com/fullchain.pem;
  1007. ssl_certificate_key /etc/letsencrypt/live/mcp.yourdomain.com/privkey.pem;
  1008. # Security headers
  1009. add_header X-Frame-Options "SAMEORIGIN" always;
  1010. add_header X-Content-Type-Options "nosniff" always;
  1011. add_header X-XSS-Protection "1; mode=block" always;
  1012. # MCP Server proxy
  1013. location / {
  1014. proxy_http_version 1.1;
  1015. proxy_set_header Host $http_host;
  1016. proxy_set_header X-Real-IP $remote_addr;
  1017. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  1018. proxy_set_header X-Forwarded-Proto $scheme;
  1019. proxy_set_header Upgrade $http_upgrade;
  1020. proxy_set_header Connection "upgrade";
  1021. # Important for SSE connections
  1022. proxy_buffering off;
  1023. proxy_cache off;
  1024. proxy_pass http://127.0.0.1:8080/;
  1025. }
  1026. }
  1027. # Redirect HTTP to HTTPS
  1028. server {
  1029. listen 80;
  1030. listen [::]:80;
  1031. server_name mcp.yourdomain.com;
  1032. return 301 https://$server_name$request_uri;
  1033. }
  1034. ```
  1035. **Start Services:**
  1036. ```bash
  1037. # Enable and start supervisor
  1038. sudo supervisorctl reread
  1039. sudo supervisorctl update
  1040. sudo supervisorctl start mcp-server:*
  1041. # Enable and start nginx
  1042. sudo systemctl enable nginx
  1043. sudo systemctl restart nginx
  1044. # Check status
  1045. sudo supervisorctl status
  1046. ```
  1047. **Client Configuration:**
  1048. ```json
  1049. {
  1050. "mcpServers": {
  1051. "my-server": {
  1052. "url": "https://mcp.yourdomain.com/mcp"
  1053. }
  1054. }
  1055. }
  1056. ```
  1057. ### Option 2: Docker Deployment
  1058. **Best for**: Containerized environments, Kubernetes, cloud platforms
  1059. **Production Dockerfile:**
  1060. ```dockerfile
  1061. FROM php:8.3-fpm-alpine
  1062. # Install system dependencies
  1063. RUN apk --no-cache add \
  1064. nginx \
  1065. supervisor \
  1066. && docker-php-ext-enable opcache
  1067. # Install PHP extensions for MCP
  1068. RUN docker-php-ext-install pdo_mysql pdo_sqlite opcache
  1069. # Create application directory
  1070. WORKDIR /var/www/mcp
  1071. # Copy application code
  1072. COPY . /var/www/mcp
  1073. COPY docker/nginx.conf /etc/nginx/nginx.conf
  1074. COPY docker/supervisord.conf /etc/supervisord.conf
  1075. COPY docker/php.ini /usr/local/etc/php/conf.d/production.ini
  1076. # Install Composer dependencies
  1077. RUN composer install --no-dev --optimize-autoloader --no-interaction
  1078. # Set permissions
  1079. RUN chown -R www-data:www-data /var/www/mcp
  1080. # Expose port
  1081. EXPOSE 80
  1082. # Start supervisor
  1083. CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
  1084. ```
  1085. **docker-compose.yml:**
  1086. ```yaml
  1087. services:
  1088. mcp-server:
  1089. build: .
  1090. ports:
  1091. - "8080:80"
  1092. environment:
  1093. - MCP_ENV=production
  1094. - MCP_LOG_LEVEL=info
  1095. volumes:
  1096. - ./storage:/var/www/mcp/storage
  1097. restart: unless-stopped
  1098. healthcheck:
  1099. test: ["CMD", "curl", "-f", "http://localhost/health"]
  1100. interval: 30s
  1101. timeout: 10s
  1102. retries: 3
  1103. # Optional: Add database if needed
  1104. database:
  1105. image: mysql:8.0
  1106. environment:
  1107. MYSQL_ROOT_PASSWORD: secure_password
  1108. MYSQL_DATABASE: mcp_server
  1109. volumes:
  1110. - mysql_data:/var/lib/mysql
  1111. restart: unless-stopped
  1112. volumes:
  1113. mysql_data:
  1114. ```
  1115. ### Security Best Practices
  1116. 1. **Firewall Configuration:**
  1117. ```bash
  1118. # Only allow necessary ports
  1119. sudo ufw allow ssh
  1120. sudo ufw allow 80
  1121. sudo ufw allow 443
  1122. sudo ufw deny 8080 # MCP port should not be publicly accessible
  1123. sudo ufw enable
  1124. ```
  1125. 2. **SSL/TLS Setup:**
  1126. ```bash
  1127. # Install Certbot for Let's Encrypt
  1128. sudo apt install certbot python3-certbot-nginx
  1129. # Generate SSL certificate
  1130. sudo certbot --nginx -d mcp.yourdomain.com
  1131. ```
  1132. ## ๐Ÿ“š Examples & Use Cases
  1133. Explore comprehensive examples in the [`examples/`](./examples/) directory:
  1134. ### Available Examples
  1135. - **`01-discovery-stdio-calculator/`** - Basic stdio calculator with attribute discovery
  1136. - **`02-discovery-http-userprofile/`** - HTTP server with user profile management
  1137. - **`03-manual-registration-stdio/`** - Manual element registration patterns
  1138. - **`04-combined-registration-http/`** - Combining manual and discovered elements
  1139. - **`05-stdio-env-variables/`** - Environment variable handling
  1140. - **`06-custom-dependencies-stdio/`** - Dependency injection with task management
  1141. - **`07-complex-tool-schema-http/`** - Advanced schema validation examples
  1142. - **`08-schema-showcase-streamable/`** - Comprehensive schema feature showcase
  1143. ### Running Examples
  1144. ```bash
  1145. # Navigate to an example directory
  1146. cd examples/01-discovery-stdio-calculator/
  1147. # Make the server executable
  1148. chmod +x server.php
  1149. # Run the server (or configure it in your MCP client)
  1150. ./server.php
  1151. ```
  1152. ## ๐Ÿšง Migration from v2.x
  1153. If migrating from version 2.x, note these key changes:
  1154. ### Schema Updates
  1155. - Uses `php-mcp/schema` package for DTOs instead of internal classes
  1156. - Content types moved to `PhpMcp\Schema\Content\*` namespace
  1157. - Updated method signatures for better type safety
  1158. ### Session Management
  1159. - New session management with multiple backends
  1160. - Use `->withSession()` or `->withSessionHandler()` for configuration
  1161. - Sessions are now persistent across reconnections (with cache backend)
  1162. ### Transport Changes
  1163. - New `StreamableHttpServerTransport` with resumability
  1164. - Enhanced error handling and event sourcing
  1165. - Better batch request processing
  1166. ## ๐Ÿงช Testing
  1167. ```bash
  1168. # Install development dependencies
  1169. composer install --dev
  1170. # Run the test suite
  1171. composer test
  1172. # Run tests with coverage (requires Xdebug)
  1173. composer test:coverage
  1174. # Run code style checks
  1175. composer lint
  1176. ```
  1177. ## ๐Ÿค Contributing
  1178. We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
  1179. ## ๐Ÿ“„ License
  1180. The MIT License (MIT). See [LICENSE](LICENSE) for details.
  1181. ## ๐Ÿ™ Acknowledgments
  1182. - Built on the [Model Context Protocol](https://modelcontextprotocol.io/) specification
  1183. - Powered by [ReactPHP](https://reactphp.org/) for async operations
  1184. - Uses [PSR standards](https://www.php-fig.org/) for maximum interoperability

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If itโ€™s helped, pass it on.