Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,17 @@
},
"autoload-dev": {
"psr-4": {
"Mcp\\Example\\HttpCombinedRegistration\\": "examples/http-combined-registration/",
"Mcp\\Example\\HttpComplexToolSchema\\": "examples/http-complex-tool-schema/",
"Mcp\\Example\\HttpDiscoveryUserProfile\\": "examples/http-discovery-userprofile/",
"Mcp\\Example\\HttpSchemaShowcase\\": "examples/http-schema-showcase/",
"Mcp\\Example\\StdioCachedDiscovery\\": "examples/stdio-cached-discovery/",
"Mcp\\Example\\StdioClientCommunication\\": "examples/stdio-client-communication/",
"Mcp\\Example\\StdioCustomDependencies\\": "examples/stdio-custom-dependencies/",
"Mcp\\Example\\StdioDiscoveryCalculator\\": "examples/stdio-discovery-calculator/",
"Mcp\\Example\\StdioEnvVariables\\": "examples/stdio-env-variables/",
"Mcp\\Example\\StdioExplicitRegistration\\": "examples/stdio-explicit-registration/",
"Mcp\\Example\\CachedDiscovery\\": "examples/cached-discovery/",
"Mcp\\Example\\ClientCommunication\\": "examples/client-communication/",
"Mcp\\Example\\CombinedRegistration\\": "examples/combined-registration/",
"Mcp\\Example\\ComplexToolSchema\\": "examples/complex-tool-schema/",
"Mcp\\Example\\CustomDependencies\\": "examples/custom-dependencies/",
"Mcp\\Example\\CustomMethodHandlers\\": "examples/custom-method-handlers/",
"Mcp\\Example\\DiscoveryCalculator\\": "examples/discovery-calculator/",
"Mcp\\Example\\DiscoveryUserProfile\\": "examples/discovery-userprofile/",
"Mcp\\Example\\EnvVariables\\": "examples/env-variables/",
"Mcp\\Example\\ExplicitRegistration\\": "examples/explicit-registration/",
"Mcp\\Example\\SchemaShowcase\\": "examples/schema-showcase/",
"Mcp\\Tests\\": "tests/"
}
},
Expand Down
53 changes: 25 additions & 28 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ specific features and can be run independently to understand how the SDK works.

- [Getting Started](#getting-started)
- [Running Examples](#running-examples)
- [STDIO Examples](#stdio-examples)
- [HTTP Examples](#http-examples)
- [Advanced Patterns](#advanced-patterns)
- [Testing and Debugging](#testing-and-debugging)
- [Examples](#examples)

## Getting Started

Expand All @@ -26,28 +23,30 @@ composer install

## Running Examples

### STDIO Examples
The bootstrapping of the example will choose the used transport based on the SAPI you use.

STDIO examples use standard input/output for communication:
### STDIO Transport

The STDIO transport will use standard input/output for communication:

```bash
# Interactive testing with MCP Inspector
npx @modelcontextprotocol/inspector php examples/stdio-discovery-calculator/server.php
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php

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

# Or configure the script path in your MCP client
# Path: php examples/stdio-discovery-calculator/server.php
# Path: php examples/discovery-calculator/server.php
```

### HTTP Examples
### HTTP Transport

HTTP examples run as web servers:
The Streamable HTTP transport will be chosen if running examples with a web servers:

```bash
# Start the server
php -S localhost:8000 examples/http-discovery-userprofile/server.php
php -S localhost:8000 examples/discovery-userprofile/server.php

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

## STDIO Examples
## Examples

### Discovery Calculator

**File**: `examples/stdio-discovery-calculator/`
**File**: `examples/discovery-calculator/`

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

# Or configure in MCP client: php examples/stdio-discovery-calculator/server.php
# Or configure in MCP client: php examples/discovery-calculator/server.php
```

### Explicit Registration

**File**: `examples/stdio-explicit-registration/`
**File**: `examples/explicit-registration/`

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

### Environment Variables

**File**: `examples/stdio-env-variables/`
**File**: `examples/env-variables/`

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

### Custom Dependencies

**File**: `examples/stdio-custom-dependencies/`
**File**: `examples/custom-dependencies/`

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

### Cached Discovery

**File**: `examples/stdio-cached-discovery/`
**File**: `examples/cached-discovery/`

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

### Client Communication

**File**: `examples/stdio-client-communication/`
**File**: `examples/client-communication/`

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

## HTTP Examples

### Discovery User Profile

**File**: `examples/http-discovery-userprofile/`
**File**: `examples/discovery-userprofile/`

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

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

### Combined Registration

**File**: `examples/http-combined-registration/`
**File**: `examples/combined-registration/`

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

### Complex Tool Schema

**File**: `examples/http-complex-tool-schema/`
**File**: `examples/complex-tool-schema/`

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

### Schema Showcase

**File**: `examples/http-schema-showcase/`
**File**: `examples/schema-showcase/`

**What it demonstrates:**
- Comprehensive JSON schema features
Expand Down
13 changes: 7 additions & 6 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,23 @@
This directory contains various examples of how to use the PHP MCP SDK.

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

For running an example, you execute the `server.php` like this:
```bash
# For examples using STDIO transport
php examples/stdio-discovery-calculator/server.php
# For using the STDIO transport:
php examples/discovery-calculator/server.php

# For examples using Streamable HTTP transport
php -S localhost:8000 examples/http-discovery-userprofile/server.php
# For using the Streamable HTTP transport:
php -S localhost:8000 examples/discovery-userprofile/server.php
```

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

Run with Inspector:

```bash
npx @modelcontextprotocol/inspector php examples/stdio-discovery-calculator/server.php
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php
```

## Debugging
Expand All @@ -29,5 +30,5 @@ directory.

With the Inspector you can set the environment variables like this:
```bash
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/stdio-discovery-calculator/server.php
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/discovery-calculator/server.php
```
31 changes: 31 additions & 0 deletions examples/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@
* file that was distributed with this source code.
*/

use Http\Discovery\Psr17Factory;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Mcp\Capability\Registry\Container;
use Mcp\Server\Transport\StdioTransport;
use Mcp\Server\Transport\StreamableHttpTransport;
use Mcp\Server\Transport\TransportInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

Expand All @@ -21,6 +27,31 @@
exit(1);
});

/**
* @return TransportInterface<int>|TransportInterface<ResponseInterface>
*/
function transport(): TransportInterface
{
if ('cli' === \PHP_SAPI) {
return new StdioTransport(logger: logger());
}

return new StreamableHttpTransport(
(new Psr17Factory())->createServerRequestFromGlobals(),
logger: logger(),
);
}

function shutdown(ResponseInterface|int $result): never
{
if ('cli' === \PHP_SAPI) {
exit($result);
}

(new SapiEmitter())->emit($result);
exit(0);
}

function logger(): LoggerInterface
{
return new class extends AbstractLogger {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* file that was distributed with this source code.
*/

namespace Mcp\Example\StdioCachedDiscovery;
namespace Mcp\Example\CachedDiscovery;

use Mcp\Capability\Attribute\McpTool;
use Mcp\Exception\ToolCallException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
chdir(__DIR__);

use Mcp\Server;
use Mcp\Server\Transport\StdioTransport;
use Mcp\Server\Session\FileSessionStore;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
use Symfony\Component\Cache\Psr16Cache;

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

$transport = new StdioTransport(logger: logger());

$result = $server->run($transport);
$result = $server->run(transport());

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

exit($result);
shutdown($result);
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/

namespace Mcp\Example\StdioClientCommunication;
namespace Mcp\Example\ClientCommunication;

use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Content\TextContent;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@
use Mcp\Schema\ServerCapabilities;
use Mcp\Server;
use Mcp\Server\ClientGateway;
use Mcp\Server\Transport\StdioTransport;
use Mcp\Server\Session\FileSessionStore;

$server = Server::builder()
->setServerInfo('STDIO Client Communication Demo', '1.0.0')
->setServerInfo('Client Communication Demo', '1.0.0')
->setLogger(logger())
->setContainer(container())
->setSession(new FileSessionStore(__DIR__.'/sessions'))
->setCapabilities(new ServerCapabilities(logging: true, tools: true))
->setDiscovery(__DIR__)
->addTool(
Expand Down Expand Up @@ -56,8 +57,6 @@ function (string $dataset, ClientGateway $client): array {
)
->build();

$transport = new StdioTransport();
$result = $server->run(transport());

$status = $server->run($transport);

exit($status);
shutdown($result);
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/

namespace Mcp\Example\HttpCombinedRegistration;
namespace Mcp\Example\CombinedRegistration;

use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/

namespace Mcp\Example\HttpCombinedRegistration;
namespace Mcp\Example\CombinedRegistration;

use Psr\Log\LoggerInterface;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,9 @@
require_once dirname(__DIR__).'/bootstrap.php';
chdir(__DIR__);

use Http\Discovery\Psr17Factory;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Mcp\Example\HttpCombinedRegistration\ManualHandlers;
use Mcp\Example\CombinedRegistration\ManualHandlers;
use Mcp\Server;
use Mcp\Server\Session\FileSessionStore;
use Mcp\Server\Transport\StreamableHttpTransport;

$psr17Factory = new Psr17Factory();
$request = $psr17Factory->createServerRequestFromGlobals();

$server = Server::builder()
->setServerInfo('Combined HTTP Server', '1.0.0')
Expand All @@ -37,8 +31,6 @@
)
->build();

$transport = new StreamableHttpTransport($request);

$response = $server->run($transport);
$response = $server->run(transport());

(new SapiEmitter())->emit($response);
shutdown($response);
Loading