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
4- and clients in PHP.
3+ The official PHP SDK for Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP servers and clients in PHP.
54
65> [ !IMPORTANT]
7- > Currently, the SDK is still in active development and not all components of the MCP specification are implemented .
6+ > This SDK is currently in active development with ongoing refinement of its architecture and features. While functional, the API may experience changes as we work toward stabilization .
87>
9- > If you want to help us stabilize the SDK, please see the
10- > [ issue tracker] ( https://github.com/modelcontextprotocol/php-sdk/issues ) .
8+ > If you want to help us stabilize the SDK, please see the [ issue tracker] ( https://github.com/modelcontextprotocol/php-sdk/issues ) .
119
12- This project is a collaboration between [ the PHP Foundation] ( https://thephp.foundation/ ) and the
13- [ Symfony project] ( https://symfony.com/ ) . It adopts development practices and standards from the Symfony project,
14- including [ Coding Standards] ( https://symfony.com/doc/current/contributing/code/standards.html ) and the
15- [ Backward Compatibility Promise] ( https://symfony.com/doc/current/contributing/code/bc.html ) .
10+ This project represents a collaboration between [ the PHP Foundation] ( https://thephp.foundation/ ) and the [ Symfony project] ( https://symfony.com/ ) . It adopts development practices and standards from the Symfony project, including [ Coding Standards] ( https://symfony.com/doc/current/contributing/code/standards.html ) and the [ Backward Compatibility Promise] ( https://symfony.com/doc/current/contributing/code/bc.html ) .
1611
17- Until the first major release, this SDK is considered
18- [ experimental] ( https://symfony.com/doc/current/contributing/code/experimental.html ) .
12+ Until the first major release, this SDK is considered [ experimental] ( https://symfony.com/doc/current/contributing/code/experimental.html ) .
1913
20- ## 🚧 Roadmap
14+ ## Roadmap
2115
22- Features
16+ ** Features**
2317- [ ] Stabilize server component with all needed handlers and functional tests
24- - [ ] Extend documentation, including integration pointer for popular frameworks
18+ - [ ] Extend documentation, including integration guides for popular frameworks
2519- [ ] Implement Client component
2620- [ ] Support multiple schema versions
2721
@@ -31,34 +25,67 @@ Features
3125composer require mcp/sdk
3226```
3327
34- ## ⚡ Quick Start: Stdio Server with Discovery
28+ ## Quick Start
3529
36- This example demonstrates the most common usage pattern - a ` stdio ` server using attribute discovery.
30+ This example demonstrates the most common usage pattern - a STDIO server using attribute discovery.
3731
38- ** 1. Define Your MCP Elements**
32+ ### 1. Define Your MCP Elements
3933
40- Create ` src/CalculatorElements.php ` :
34+ Create a class with MCP capabilities using attributes :
4135
4236``` php
4337<?php
4438
4539namespace App;
4640
4741use Mcp\Capability\Attribute\McpTool;
42+ use Mcp\Capability\Attribute\McpResource;
4843
4944class CalculatorElements
5045{
51- #[McpTool(name: 'add_numbers')]
46+ /**
47+ * Adds two numbers together.
48+ *
49+ * @param int $a The first number
50+ * @param int $b The second number
51+ * @return int The sum of the two numbers
52+ */
53+ #[McpTool]
5254 public function add(int $a, int $b): int
5355 {
5456 return $a + $b;
5557 }
58+
59+ /**
60+ * Performs basic arithmetic operations.
61+ */
62+ #[McpTool(name: 'calculate')]
63+ public function calculate(float $a, float $b, string $operation): float|string
64+ {
65+ return match($operation) {
66+ 'add' => $a + $b,
67+ 'subtract' => $a - $b,
68+ 'multiply' => $a * $b,
69+ 'divide' => $b != 0 ? $a / $b : 'Error: Division by zero',
70+ default => 'Error: Unknown operation'
71+ };
72+ }
73+
74+ #[McpResource(
75+ uri: 'config://calculator/settings',
76+ name: 'calculator_config',
77+ mimeType: 'application/json'
78+ )]
79+ public function getSettings(): array
80+ {
81+ return ['precision' => 2, 'allow_negative' => true];
82+ }
5683}
5784```
5885
59- ** 2. Create the Server Script**
86+ ### 2. Create the Server Script
6087
61- Create ` mcp- server.php ` :
88+ Create your MCP server:
6289
6390``` php
6491#!/usr/bin/env php
@@ -71,59 +98,163 @@ require_once __DIR__ . '/vendor/autoload.php';
7198use Mcp\Server;
7299use Mcp\Server\Transport\StdioTransport;
73100
74- Server::builder()
75- ->setServerInfo('Stdio Calculator', '1.1.0', 'Basic Calculator over STDIO transport. ')
101+ $server = Server::builder()
102+ ->setServerInfo('Calculator Server ', '1.0.0 ')
76103 ->setDiscovery(__DIR__, ['.'])
77- ->build()
78- ->connect(new StdioTransport());
104+ ->build();
105+
106+ $transport = new StdioTransport();
107+ $server->connect($transport);
108+ $transport->listen();
79109```
80110
81- ** 3. Configure Your MCP Client**
111+ ### 3. Configure Your MCP Client
82112
83- Add to your client configuration (e.g., ` mcp.json ` ):
113+ Add to your client configuration (e.g., Claude Desktop's ` mcp.json ` ):
84114
85115``` json
86116{
87117 "mcpServers" : {
88118 "php-calculator" : {
89119 "command" : " php" ,
90- "args" : [" /absolute/path/to/your/mcp- server.php" ]
120+ "args" : [" /absolute/path/to/your/server.php" ]
91121 }
92122 }
93123}
94124```
95125
96- ** 4. Test the Server**
126+ ### 4. Test Your Server
127+
128+ ``` bash
129+ # Test with MCP Inspector
130+ npx @modelcontextprotocol/inspector php /path/to/server.php
131+
132+ # Your AI assistant can now call:
133+ # - add: Add two integers
134+ # - calculate: Perform arithmetic operations
135+ # - Read config://calculator/settings resource
136+ ```
137+
138+ ## Key Features
139+
140+ ### Attribute-Based Discovery
141+
142+ Define MCP elements using PHP attributes with automatic discovery:
143+
144+ ``` php
145+ // Tool with automatic name and description from method
146+ #[McpTool]
147+ public function generateReport(): string { /* ... */ }
148+
149+ // Tool with custom name
150+ #[McpTool(name: 'custom_name')]
151+ public function myMethod(): string { /* ... */ }
152+
153+ // Resource with URI and metadata
154+ #[McpResource(uri: 'config://app/settings', mimeType: 'application/json')]
155+ public function getConfig(): array { /* ... */ }
156+ ```
157+
158+ ### Manual Registration
159+
160+ Register capabilities programmatically:
161+
162+ ``` php
163+ $server = Server::builder()
164+ ->addTool([MyClass::class, 'myMethod'], 'tool_name')
165+ ->addResource([MyClass::class, 'getData'], 'data://config')
166+ ->build();
167+ ```
168+
169+ ### Multiple Transport Options
97170
98- Your AI assistant can now call:
99- - ` add_numbers ` - Add two integers
171+ ** STDIO Transport** (Command-line integration):
172+ ``` php
173+ $transport = new StdioTransport();
174+ $server->connect($transport);
175+ $transport->listen();
176+ ```
100177
101- For more examples, see the [ examples directory] ( examples ) .
178+ ** HTTP Transport** (Web-based communication):
179+ ``` php
180+ $transport = new StreamableHttpTransport($request, $responseFactory, $streamFactory);
181+ $server->connect($transport);
182+ $response = $transport->listen();
183+ // Handle $response in your web application
184+ ```
185+
186+ ### Session Management
102187
103- ## Documentation
188+ By default, the SDK uses in-memory sessions. You can configure different session stores:
104189
105- - [ SDK documentation] ( docs/index.md )
190+ ``` php
191+ use Mcp\Server\Session\InMemorySessionStore;
192+ use Mcp\Server\Session\FileSessionStore;
193+
194+ // Use default in-memory sessions (TTL only)
195+ $server = Server::builder()
196+ ->setSession(ttl: 7200) // 2 hours
197+ ->build();
198+
199+ // Use file-based sessions
200+ $server = Server::builder()
201+ ->setSession(new FileSessionStore(__DIR__ . '/sessions'))
202+ ->build();
203+
204+ // Use in-memory with custom TTL
205+ $server = Server::builder()
206+ ->setSession(new InMemorySessionStore(3600))
207+ ->build();
208+ ```
209+
210+ ### Discovery Caching
211+
212+ Use any PSR-16 cache implementation to cache discovery results and avoid running discovery on every server start:
213+
214+ ``` php
215+ use Symfony\Component\Cache\Adapter\FilesystemAdapter;
216+ use Symfony\Component\Cache\Psr16Cache;
217+
218+ $cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery'));
219+
220+ $server = Server::builder()
221+ ->setDiscovery(
222+ basePath: __DIR__,
223+ scanDirs: ['.', 'src'], // Default: ['.', 'src']
224+ excludeDirs: ['vendor'], // Default: ['vendor', 'node_modules']
225+ cache: $cache
226+ )
227+ ->build();
228+ ```
229+
230+ ## 📚 Documentation
231+
232+ ** Core Concepts:**
233+ - [ Server Builder] ( docs/server-builder.md ) - Complete ServerBuilder reference and configuration
234+ - [ Transports] ( docs/transports.md ) - STDIO and HTTP transport setup and usage
235+ - [ MCP Elements] ( docs/mcp-elements.md ) - Creating tools, resources, and prompts
236+
237+ ** Learning:**
238+ - [ Examples] ( docs/examples.md ) - Comprehensive example walkthroughs
239+
240+ ** External Resources:**
106241- [ Model Context Protocol documentation] ( https://modelcontextprotocol.io )
107242- [ Model Context Protocol specification] ( https://spec.modelcontextprotocol.io )
108243- [ Officially supported servers] ( https://github.com/modelcontextprotocol/servers )
109244
110- ## PHP libraries using the MCP SDK
245+ ## PHP Libraries Using the MCP SDK
111246
112- * https://github.com/pronskiy/mcp - additional DX layer
113- * https://github.com/symfony/mcp-bundle - Symfony integration bundle
247+ * [ pronskiy/mcp ] ( https://github.com/pronskiy/mcp ) - Additional DX layer
248+ * [ symfony/mcp-bundle ] ( https://github.com/symfony/mcp-bundle ) - Symfony integration bundle
114249
115250## Contributing
116251
117- We are passionate about supporting contributors of all levels of experience and would love to see you get involved in
118- the project. See the [ contributing guide] ( CONTRIBUTING.md ) to get started before you
119- [ report issues] ( https://github.com/modelcontextprotocol/php-sdk/issues ) and
120- [ send pull requests] ( https://github.com/modelcontextprotocol/php-sdk/pulls ) .
252+ We are passionate about supporting contributors of all levels of experience and would love to see you get involved in 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 ) .
121253
122254## Credits
123- Starting point for this SDK was the [ PHP-MCP] ( https://github.com/php-mcp/server ) project, initiated by
124- [ Kyrian Obikwelu] ( https://github.com/CodeWithKyrian ) , and the [ Symfony AI initiative] ( https://github.com/symfony/ai ) .
125- We are grateful for the work done by both projects and their contributors, which created a solid foundation for this SDK.
255+
256+ 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 ) , and the [ Symfony AI initiative] ( https://github.com/symfony/ai ) . We are grateful for the work done by both projects and their contributors, which created a solid foundation for this SDK.
126257
127258## License
128259
129- This project is licensed under the MIT License - see the LICENSE file for details.
260+ This project is licensed under the MIT License - see the [ LICENSE] ( LICENSE ) file for details.
0 commit comments