11# MCP PHP SDK
22
3- The official PHP SDK for Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP servers in PHP.
3+ The official PHP SDK for Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP servers
4+ and clients in PHP.
45
56> [ !IMPORTANT]
6- > Currently, we are still in the process of merging [ Symfony's MCP SDK] ( https://github.com/symfony/mcp-sdk ) and
7- > [ PHP-MCP] ( https://github.com/php-mcp ) components. Not all code paths are fully tested or complete, and this package
8- > may still contain duplicate functionality or dead code.
7+ > This SDK is currently in active development with ongoing refinement of its architecture and features. While
8+ > functional, the API may experience changes as we work toward stabilization.
99>
10- > If you want to help us stabilize the SDK, please see the
11- > [ issue tracker] ( https://github.com/modelcontextprotocol/php-sdk/issues ) .
10+ > If you want to help us stabilize the SDK, please see the [ issue tracker] ( https://github.com/modelcontextprotocol/php-sdk/issues ) .
1211
13- This project is a collaboration between [ the PHP Foundation] ( https://thephp.foundation/ ) and the
14- [ Symfony project] ( https://symfony.com/ ) . It adopts development practices and standards from the Symfony project,
15- including [ Coding Standards] ( https://symfony.com/doc/current/contributing/code/standards.html ) and the
12+ This project represents a collaboration between [ the PHP Foundation] ( https://thephp.foundation/ ) and the [ Symfony project] ( https://symfony.com/ ) . It adopts
13+ development practices and standards from the Symfony project, including [ Coding Standards] ( https://symfony.com/doc/current/contributing/code/standards.html ) and the
1614[ Backward Compatibility Promise] ( https://symfony.com/doc/current/contributing/code/bc.html ) .
1715
18- Until the first major release, this SDK is considered
19- [ experimental] ( https://symfony.com/doc/current/contributing/code/experimental.html ) .
16+ Until the first major release, this SDK is considered [ experimental] ( https://symfony.com/doc/current/contributing/code/experimental.html ) .
2017
21- ## 🚧 Roadmap
18+ ## Roadmap
2219
23- Features
24- - [x] Bring back PHP-MCP examples
25- - [x] Glue handler, registry and reference handlers
26- - [x] Revive ` ServerBuilder `
27- - [x] Revive transports
28- - [x] Streamable Transport https://github.com/modelcontextprotocol/php-sdk/issues/7
29- - [ ] ~~ Http/SSE-based Transport https://github.com/modelcontextprotocol/php-sdk/issues/8 ~~
30- - [ ] Support pagination
31- - [ ] Support Schema validation
32- - [ ] Support multiple versions of the MCP specification https://github.com/modelcontextprotocol/php-sdk/issues/14
33- - [ ] (Re-)Implement missing Notification & Request Handlers https://github.com/modelcontextprotocol/php-sdk/issues/9
20+ ** Features**
21+ - [ ] Stabilize server component with all needed handlers and functional tests
22+ - [ ] Extend documentation, including integration guides for popular frameworks
23+ - [ ] Implement Client component
24+ - [ ] Support multiple schema versions
3425
3526## Installation
3627
3728``` bash
3829composer require mcp/sdk
3930```
4031
41- Since this package has no tagged releases yet, it is required to extend your ` composer.json ` :
42- ``` json
43- "minimum-stability" : " dev" ,
44- "prefer-stable" : true
45- ```
46-
47- ## ⚡ Quick Start: Stdio Server with Discovery
32+ ## Quick Start
4833
49- This example demonstrates the most common usage pattern - a ` stdio ` server using attribute discovery.
34+ This example demonstrates the most common usage pattern - a STDIO server using attribute discovery.
5035
51- ** 1. Define Your MCP Elements**
36+ ### 1. Define Your MCP Elements
5237
53- Create ` src/CalculatorElements.php ` :
38+ Create a class with MCP capabilities using attributes :
5439
5540``` php
5641<?php
5742
5843namespace App;
5944
6045use Mcp\Capability\Attribute\McpTool;
46+ use Mcp\Capability\Attribute\McpResource;
6147
6248class CalculatorElements
6349{
64- #[McpTool(name: 'add_numbers')]
50+ /**
51+ * Adds two numbers together.
52+ *
53+ * @param int $a The first number
54+ * @param int $b The second number
55+ * @return int The sum of the two numbers
56+ */
57+ #[McpTool]
6558 public function add(int $a, int $b): int
6659 {
6760 return $a + $b;
6861 }
62+
63+ /**
64+ * Performs basic arithmetic operations.
65+ */
66+ #[McpTool(name: 'calculate')]
67+ public function calculate(float $a, float $b, string $operation): float|string
68+ {
69+ return match($operation) {
70+ 'add' => $a + $b,
71+ 'subtract' => $a - $b,
72+ 'multiply' => $a * $b,
73+ 'divide' => $b != 0 ? $a / $b : 'Error: Division by zero',
74+ default => 'Error: Unknown operation'
75+ };
76+ }
77+
78+ #[McpResource(
79+ uri: 'config://calculator/settings',
80+ name: 'calculator_config',
81+ mimeType: 'application/json'
82+ )]
83+ public function getSettings(): array
84+ {
85+ return ['precision' => 2, 'allow_negative' => true];
86+ }
6987}
7088```
7189
72- ** 2. Create the Server Script**
90+ ### 2. Create the Server Script
7391
74- Create ` mcp- server.php ` :
92+ Create your MCP server:
7593
7694``` php
7795#!/usr/bin/env php
@@ -84,54 +102,166 @@ require_once __DIR__ . '/vendor/autoload.php';
84102use Mcp\Server;
85103use Mcp\Server\Transport\StdioTransport;
86104
87- Server::builder()
88- ->setServerInfo('Stdio Calculator', '1.1.0', 'Basic Calculator over STDIO transport. ')
105+ $server = Server::builder()
106+ ->setServerInfo('Calculator Server ', '1.0.0 ')
89107 ->setDiscovery(__DIR__, ['.'])
90- ->build()
91- ->connect(new StdioTransport());
108+ ->build();
109+
110+ $transport = new StdioTransport();
111+ $server->connect($transport);
112+ $transport->listen();
92113```
93114
94- ** 3. Configure Your MCP Client**
115+ ### 3. Configure Your MCP Client
95116
96- Add to your client configuration (e.g., ` mcp.json ` ):
117+ Add to your client configuration (e.g., Claude Desktop's ` mcp.json ` ):
97118
98119``` json
99120{
100121 "mcpServers" : {
101122 "php-calculator" : {
102123 "command" : " php" ,
103- "args" : [" /absolute/path/to/your/mcp- server.php" ]
124+ "args" : [" /absolute/path/to/your/server.php" ]
104125 }
105126 }
106127}
107128```
108129
109- ** 4. Test the Server**
130+ ### 4. Test Your Server
131+
132+ ``` bash
133+ # Test with MCP Inspector
134+ npx @modelcontextprotocol/inspector php /path/to/server.php
135+
136+ # Your AI assistant can now call:
137+ # - add: Add two integers
138+ # - calculate: Perform arithmetic operations
139+ # - Read config://calculator/settings resource
140+ ```
141+
142+ ## Key Features
143+
144+ ### Attribute-Based Discovery
145+
146+ Define MCP elements using PHP attributes with automatic discovery:
147+
148+ ``` php
149+ // Tool with automatic name and description from method
150+ #[McpTool]
151+ public function generateReport(): string { /* ... */ }
152+
153+ // Tool with custom name
154+ #[McpTool(name: 'custom_name')]
155+ public function myMethod(): string { /* ... */ }
156+
157+ // Resource with URI and metadata
158+ #[McpResource(uri: 'config://app/settings', mimeType: 'application/json')]
159+ public function getConfig(): array { /* ... */ }
160+ ```
161+
162+ ### Manual Registration
110163
111- Your AI assistant can now call:
112- - ` add_numbers ` - Add two integers
164+ Register capabilities programmatically:
165+
166+ ``` php
167+ $server = Server::builder()
168+ ->addTool([MyClass::class, 'myMethod'], 'tool_name')
169+ ->addResource([MyClass::class, 'getData'], 'data://config')
170+ ->build();
171+ ```
172+
173+ ### Multiple Transport Options
174+
175+ ** STDIO Transport** (Command-line integration):
176+ ``` php
177+ $transport = new StdioTransport();
178+ $server->connect($transport);
179+ $transport->listen();
180+ ```
181+
182+ ** HTTP Transport** (Web-based communication):
183+ ``` php
184+ $transport = new StreamableHttpTransport($request, $responseFactory, $streamFactory);
185+ $server->connect($transport);
186+ $response = $transport->listen();
187+ // Handle $response in your web application
188+ ```
189+
190+ ### Session Management
191+
192+ By default, the SDK uses in-memory sessions. You can configure different session stores:
193+
194+ ``` php
195+ use Mcp\Server\Session\InMemorySessionStore;
196+ use Mcp\Server\Session\FileSessionStore;
197+
198+ // Use default in-memory sessions (TTL only)
199+ $server = Server::builder()
200+ ->setSession(ttl: 7200) // 2 hours
201+ ->build();
202+
203+ // Use file-based sessions
204+ $server = Server::builder()
205+ ->setSession(new FileSessionStore(__DIR__ . '/sessions'))
206+ ->build();
207+
208+ // Use in-memory with custom TTL
209+ $server = Server::builder()
210+ ->setSession(new InMemorySessionStore(3600))
211+ ->build();
212+ ```
213+
214+ ### Discovery Caching
215+
216+ Use any PSR-16 cache implementation to cache discovery results and avoid running discovery on every server start:
217+
218+ ``` php
219+ use Symfony\Component\Cache\Adapter\FilesystemAdapter;
220+ use Symfony\Component\Cache\Psr16Cache;
221+
222+ $cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery'));
223+
224+ $server = Server::builder()
225+ ->setDiscovery(
226+ basePath: __DIR__,
227+ scanDirs: ['.', 'src'], // Default: ['.', 'src']
228+ excludeDirs: ['vendor'], // Default: ['vendor', 'node_modules']
229+ cache: $cache
230+ )
231+ ->build();
232+ ```
113233
114234## Documentation
115235
116- - [ SDK documentation] ( doc/index.rst )
236+ ** Core Concepts:**
237+ - [ Server Builder] ( docs/server-builder.md ) - Complete ServerBuilder reference and configuration
238+ - [ Transports] ( docs/transports.md ) - STDIO and HTTP transport setup and usage
239+ - [ MCP Elements] ( docs/mcp-elements.md ) - Creating tools, resources, and prompts
240+
241+ ** Learning:**
242+ - [ Examples] ( docs/examples.md ) - Comprehensive example walkthroughs
243+
244+ ** External Resources:**
117245- [ Model Context Protocol documentation] ( https://modelcontextprotocol.io )
118246- [ Model Context Protocol specification] ( https://spec.modelcontextprotocol.io )
119247- [ Officially supported servers] ( https://github.com/modelcontextprotocol/servers )
120248
121- ## Examples of MCP Tools that use this SDK
249+ ## PHP Libraries Using the MCP SDK
122250
123- - https://github.com/pronskiy/mcp
251+ * [ pronskiy/mcp] ( https://github.com/pronskiy/mcp ) - Additional DX layer
252+ * [ symfony/mcp-bundle] ( https://github.com/symfony/mcp-bundle ) - Symfony integration bundle
124253
125254## Contributing
126255
127256We are passionate about supporting contributors of all levels of experience and would love to see you get involved in
128- the project. See the [ contributing guide] ( CONTRIBUTING.md ) to get started before you
129- [ report issues] ( https://github.com/modelcontextprotocol/php-sdk/issues ) and
130- [ send pull requests] ( https://github.com/modelcontextprotocol/php-sdk/pulls ) .
257+ the project. See the [ contributing guide] ( CONTRIBUTING.md ) to get started before you [ report issues] ( https://github.com/modelcontextprotocol/php-sdk/issues ) and [ send pull requests] ( https://github.com/modelcontextprotocol/php-sdk/pulls ) .
131258
132259## Credits
133- The starting point for this SDK was the [ PHP-MCP] ( https://github.com/php-mcp/server ) project, initiated by [ Kyrian Obikwelu] ( https://github.com/CodeWithKyrian ) . We are grateful for the work done by Kyrian and other contributors to that repository, which created a solid foundation for this SDK.
260+
261+ The starting point for this SDK was the [ PHP-MCP] ( https://github.com/php-mcp/server ) project, initiated by
262+ [ Kyrian Obikwelu] ( https://github.com/CodeWithKyrian ) , and the [ Symfony AI initiative] ( https://github.com/symfony/ai ) . We are grateful for the work
263+ done by both projects and their contributors, which created a solid foundation for this SDK.
134264
135265## License
136266
137- This project is licensed under the MIT License - see the LICENSE file for details.
267+ This project is licensed under the MIT License - see the [ LICENSE] ( LICENSE ) file for details.
0 commit comments