Skip to content

Commit cae1aad

Browse files
committed
refactor: transport agnostic examples
1 parent fb3c1e6 commit cae1aad

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+157
-289
lines changed

composer.json

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,17 +52,17 @@
5252
},
5353
"autoload-dev": {
5454
"psr-4": {
55-
"Mcp\\Example\\HttpCombinedRegistration\\": "examples/http-combined-registration/",
56-
"Mcp\\Example\\HttpComplexToolSchema\\": "examples/http-complex-tool-schema/",
57-
"Mcp\\Example\\HttpDiscoveryUserProfile\\": "examples/http-discovery-userprofile/",
58-
"Mcp\\Example\\HttpSchemaShowcase\\": "examples/http-schema-showcase/",
59-
"Mcp\\Example\\StdioCachedDiscovery\\": "examples/stdio-cached-discovery/",
60-
"Mcp\\Example\\StdioClientCommunication\\": "examples/stdio-client-communication/",
61-
"Mcp\\Example\\StdioCustomDependencies\\": "examples/stdio-custom-dependencies/",
62-
"Mcp\\Example\\StdioDiscoveryCalculator\\": "examples/stdio-discovery-calculator/",
63-
"Mcp\\Example\\StdioEnvVariables\\": "examples/stdio-env-variables/",
64-
"Mcp\\Example\\StdioExplicitRegistration\\": "examples/stdio-explicit-registration/",
55+
"Mcp\\Example\\CachedDiscovery\\": "examples/cached-discovery/",
56+
"Mcp\\Example\\ClientCommunication\\": "examples/client-communication/",
57+
"Mcp\\Example\\CombinedRegistration\\": "examples/combined-registration/",
58+
"Mcp\\Example\\ComplexToolSchema\\": "examples/complex-tool-schema/",
59+
"Mcp\\Example\\CustomDependencies\\": "examples/custom-dependencies/",
6560
"Mcp\\Example\\CustomMethodHandlers\\": "examples/custom-method-handlers/",
61+
"Mcp\\Example\\DiscoveryCalculator\\": "examples/discovery-calculator/",
62+
"Mcp\\Example\\DiscoveryUserProfile\\": "examples/discovery-userprofile/",
63+
"Mcp\\Example\\EnvVariables\\": "examples/env-variables/",
64+
"Mcp\\Example\\ExplicitRegistration\\": "examples/explicit-registration/",
65+
"Mcp\\Example\\SchemaShowcase\\": "examples/schema-showcase/",
6666
"Mcp\\Tests\\": "tests/"
6767
}
6868
},

docs/examples.md

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,7 @@ specific features and can be run independently to understand how the SDK works.
77

88
- [Getting Started](#getting-started)
99
- [Running Examples](#running-examples)
10-
- [STDIO Examples](#stdio-examples)
11-
- [HTTP Examples](#http-examples)
12-
- [Advanced Patterns](#advanced-patterns)
13-
- [Testing and Debugging](#testing-and-debugging)
10+
- [Examples](#examples)
1411

1512
## Getting Started
1613

@@ -26,28 +23,30 @@ composer install
2623

2724
## Running Examples
2825

29-
### STDIO Examples
26+
The bootstrapping of the example will choose the used transport based on the SAPI you use.
3027

31-
STDIO examples use standard input/output for communication:
28+
### STDIO Transport
29+
30+
The STDIO transport will use standard input/output for communication:
3231

3332
```bash
3433
# Interactive testing with MCP Inspector
35-
npx @modelcontextprotocol/inspector php examples/stdio-discovery-calculator/server.php
34+
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php
3635

3736
# Run with debugging enabled
38-
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/stdio-discovery-calculator/server.php
37+
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/discovery-calculator/server.php
3938

4039
# Or configure the script path in your MCP client
41-
# Path: php examples/stdio-discovery-calculator/server.php
40+
# Path: php examples/discovery-calculator/server.php
4241
```
4342

44-
### HTTP Examples
43+
### HTTP Transport
4544

46-
HTTP examples run as web servers:
45+
The Streamable HTTP transport will be chosen if running examples with a web servers:
4746

4847
```bash
4948
# Start the server
50-
php -S localhost:8000 examples/http-discovery-userprofile/server.php
49+
php -S localhost:8000 examples/discovery-userprofile/server.php
5150

5251
# Test with MCP Inspector
5352
npx @modelcontextprotocol/inspector http://localhost:8000
@@ -59,11 +58,11 @@ curl -X POST http://localhost:8000 \
5958
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"test","version":"1.0.0"},"capabilities":{}}}'
6059
```
6160

62-
## STDIO Examples
61+
## Examples
6362

6463
### Discovery Calculator
6564

66-
**File**: `examples/stdio-discovery-calculator/`
65+
**File**: `examples/discovery-calculator/`
6766

6867
**What it demonstrates:**
6968
- Attribute-based discovery using `#[McpTool]` and `#[McpResource]`
@@ -87,14 +86,14 @@ public function getConfiguration(): array
8786
**Usage:**
8887
```bash
8988
# Interactive testing
90-
npx @modelcontextprotocol/inspector php examples/stdio-discovery-calculator/server.php
89+
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php
9190

92-
# Or configure in MCP client: php examples/stdio-discovery-calculator/server.php
91+
# Or configure in MCP client: php examples/discovery-calculator/server.php
9392
```
9493

9594
### Explicit Registration
9695

97-
**File**: `examples/stdio-explicit-registration/`
96+
**File**: `examples/explicit-registration/`
9897

9998
**What it demonstrates:**
10099
- Manual registration of tools, resources, and prompts
@@ -111,7 +110,7 @@ $server = Server::builder()
111110

112111
### Environment Variables
113112

114-
**File**: `examples/stdio-env-variables/`
113+
**File**: `examples/env-variables/`
115114

116115
**What it demonstrates:**
117116
- Environment variable integration
@@ -125,7 +124,7 @@ $server = Server::builder()
125124

126125
### Custom Dependencies
127126

128-
**File**: `examples/stdio-custom-dependencies/`
127+
**File**: `examples/custom-dependencies/`
129128

130129
**What it demonstrates:**
131130
- Dependency injection with PSR-11 containers
@@ -145,7 +144,7 @@ $server = Server::builder()
145144

146145
### Cached Discovery
147146

148-
**File**: `examples/stdio-cached-discovery/`
147+
**File**: `examples/cached-discovery/`
149148

150149
**What it demonstrates:**
151150
- Discovery caching for improved performance
@@ -165,19 +164,17 @@ $server = Server::builder()
165164

166165
### Client Communication
167166

168-
**File**: `examples/stdio-client-communication/`
167+
**File**: `examples/client-communication/`
169168

170169
**What it demostrates:**
171170
- Server initiated communcation back to the client
172171
- Logging, sampling, progress and notifications
173172
- Using `ClientGateway` in service class via `ClientAwareInterface` and corresponding trait
174173
- Using `ClientGateway` in tool method via method argument injection
175174

176-
## HTTP Examples
177-
178175
### Discovery User Profile
179176

180-
**File**: `examples/http-discovery-userprofile/`
177+
**File**: `examples/discovery-userprofile/`
181178

182179
**What it demonstrates:**
183180
- HTTP transport with StreamableHttpTransport
@@ -205,7 +202,7 @@ public function generateBio(string $userId, string $tone = 'professional'): arra
205202
**Usage:**
206203
```bash
207204
# Start the HTTP server
208-
php -S localhost:8000 examples/http-discovery-userprofile/server.php
205+
php -S localhost:8000 examples/discovery-userprofile/server.php
209206

210207
# Test with MCP Inspector
211208
npx @modelcontextprotocol/inspector http://localhost:8000
@@ -215,7 +212,7 @@ npx @modelcontextprotocol/inspector http://localhost:8000
215212

216213
### Combined Registration
217214

218-
**File**: `examples/http-combined-registration/`
215+
**File**: `examples/combined-registration/`
219216

220217
**What it demonstrates:**
221218
- Mixing attribute discovery with manual registration
@@ -232,7 +229,7 @@ $server = Server::builder()
232229

233230
### Complex Tool Schema
234231

235-
**File**: `examples/http-complex-tool-schema/`
232+
**File**: `examples/complex-tool-schema/`
236233

237234
**What it demonstrates:**
238235
- Advanced JSON schema definitions
@@ -255,7 +252,7 @@ public function scheduleEvent(array $eventData): array
255252

256253
### Schema Showcase
257254

258-
**File**: `examples/http-schema-showcase/`
255+
**File**: `examples/schema-showcase/`
259256

260257
**What it demonstrates:**
261258
- Comprehensive JSON schema features

examples/README.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,23 @@
33
This directory contains various examples of how to use the PHP MCP SDK.
44

55
You can run the examples with the dependencies already installed in the root directory of the SDK.
6+
The bootstrapping of the example will choose the used transport based on the SAPI you use.
67

78
For running an example, you execute the `server.php` like this:
89
```bash
9-
# For examples using STDIO transport
10-
php examples/stdio-discovery-calculator/server.php
10+
# For using the STDIO transport:
11+
php examples/discovery-calculator/server.php
1112

12-
# For examples using Streamable HTTP transport
13-
php -S localhost:8000 examples/http-discovery-userprofile/server.php
13+
# For using the Streamable HTTP transport:
14+
php -S localhost:8000 examples/discovery-userprofile/server.php
1415
```
1516

1617
You will see debug outputs to help you understand what is happening.
1718

1819
Run with Inspector:
1920

2021
```bash
21-
npx @modelcontextprotocol/inspector php examples/stdio-discovery-calculator/server.php
22+
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php
2223
```
2324

2425
## Debugging
@@ -29,5 +30,5 @@ directory.
2930

3031
With the Inspector you can set the environment variables like this:
3132
```bash
32-
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/stdio-discovery-calculator/server.php
33+
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/discovery-calculator/server.php
3334
```

examples/bootstrap.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,13 @@
99
* file that was distributed with this source code.
1010
*/
1111

12+
use Http\Discovery\Psr17Factory;
13+
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
1214
use Mcp\Capability\Registry\Container;
15+
use Mcp\Server\Transport\StdioTransport;
16+
use Mcp\Server\Transport\StreamableHttpTransport;
17+
use Mcp\Server\Transport\TransportInterface;
18+
use Psr\Http\Message\ResponseInterface;
1319
use Psr\Log\AbstractLogger;
1420
use Psr\Log\LoggerInterface;
1521

@@ -21,6 +27,31 @@
2127
exit(1);
2228
});
2329

30+
/**
31+
* @return TransportInterface<int>|TransportInterface<ResponseInterface>
32+
*/
33+
function transport(): TransportInterface
34+
{
35+
if ('cli' === \PHP_SAPI) {
36+
return new StdioTransport(logger: logger());
37+
}
38+
39+
return new StreamableHttpTransport(
40+
(new Psr17Factory())->createServerRequestFromGlobals(),
41+
logger: logger(),
42+
);
43+
}
44+
45+
function shutdown(ResponseInterface|int $result): never
46+
{
47+
if ('cli' === \PHP_SAPI) {
48+
exit($result);
49+
}
50+
51+
(new SapiEmitter())->emit($result);
52+
exit(0);
53+
}
54+
2455
function logger(): LoggerInterface
2556
{
2657
return new class extends AbstractLogger {

examples/stdio-cached-discovery/CachedCalculatorElements.php renamed to examples/cached-discovery/CachedCalculatorElements.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
* file that was distributed with this source code.
1212
*/
1313

14-
namespace Mcp\Example\StdioCachedDiscovery;
14+
namespace Mcp\Example\CachedDiscovery;
1515

1616
use Mcp\Capability\Attribute\McpTool;
1717
use Mcp\Exception\ToolCallException;

examples/stdio-cached-discovery/server.php renamed to examples/cached-discovery/server.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
chdir(__DIR__);
1717

1818
use Mcp\Server;
19-
use Mcp\Server\Transport\StdioTransport;
19+
use Mcp\Server\Session\FileSessionStore;
2020
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
2121
use Symfony\Component\Cache\Psr16Cache;
2222

@@ -25,14 +25,13 @@
2525
$server = Server::builder()
2626
->setServerInfo('Cached Discovery Calculator', '1.0.0', 'Calculator with cached discovery for better performance.')
2727
->setContainer(container())
28+
->setSession(new FileSessionStore(__DIR__.'/sessions'))
2829
->setLogger(logger())
2930
->setDiscovery(__DIR__, cache: new Psr16Cache(new PhpFilesAdapter(directory: __DIR__.'/cache')))
3031
->build();
3132

32-
$transport = new StdioTransport(logger: logger());
33-
34-
$result = $server->run($transport);
33+
$result = $server->run(transport());
3534

3635
logger()->info('Server listener stopped gracefully.', ['result' => $result]);
3736

38-
exit($result);
37+
shutdown($result);

examples/stdio-client-communication/ClientAwareService.php renamed to examples/client-communication/ClientAwareService.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
* file that was distributed with this source code.
1010
*/
1111

12-
namespace Mcp\Example\StdioClientCommunication;
12+
namespace Mcp\Example\ClientCommunication;
1313

1414
use Mcp\Capability\Attribute\McpTool;
1515
use Mcp\Schema\Content\TextContent;

examples/stdio-client-communication/server.php renamed to examples/client-communication/server.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,13 @@
1717
use Mcp\Schema\ServerCapabilities;
1818
use Mcp\Server;
1919
use Mcp\Server\ClientGateway;
20-
use Mcp\Server\Transport\StdioTransport;
20+
use Mcp\Server\Session\FileSessionStore;
2121

2222
$server = Server::builder()
23-
->setServerInfo('STDIO Client Communication Demo', '1.0.0')
23+
->setServerInfo('Client Communication Demo', '1.0.0')
2424
->setLogger(logger())
2525
->setContainer(container())
26+
->setSession(new FileSessionStore(__DIR__.'/sessions'))
2627
->setCapabilities(new ServerCapabilities(logging: true, tools: true))
2728
->setDiscovery(__DIR__)
2829
->addTool(
@@ -56,8 +57,6 @@ function (string $dataset, ClientGateway $client): array {
5657
)
5758
->build();
5859

59-
$transport = new StdioTransport();
60+
$result = $server->run(transport());
6061

61-
$status = $server->run($transport);
62-
63-
exit($status);
62+
shutdown($result);

examples/http-combined-registration/DiscoveredElements.php renamed to examples/combined-registration/DiscoveredElements.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
* file that was distributed with this source code.
1010
*/
1111

12-
namespace Mcp\Example\HttpCombinedRegistration;
12+
namespace Mcp\Example\CombinedRegistration;
1313

1414
use Mcp\Capability\Attribute\McpResource;
1515
use Mcp\Capability\Attribute\McpTool;

examples/http-combined-registration/ManualHandlers.php renamed to examples/combined-registration/ManualHandlers.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
* file that was distributed with this source code.
1010
*/
1111

12-
namespace Mcp\Example\HttpCombinedRegistration;
12+
namespace Mcp\Example\CombinedRegistration;
1313

1414
use Psr\Log\LoggerInterface;
1515

0 commit comments

Comments
 (0)