PHPackages                             mcp/sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mcp/sdk

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mcp/sdk
=======

Model Context Protocol SDK for Client and Server applications in PHP

v0.4.0(2mo ago)1.4k423.9k↑81.5%126[21 issues](https://github.com/modelcontextprotocol/php-sdk/issues)[9 PRs](https://github.com/modelcontextprotocol/php-sdk/pulls)20Apache-2.0PHPPHP ^8.1CI passing

Since Nov 20Pushed 1mo ago28 watchersCompare

[ Source](https://github.com/modelcontextprotocol/php-sdk)[ Packagist](https://packagist.org/packages/mcp/sdk)[ RSS](/packages/mcp-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (25)Versions (15)Used By (20)

MCP PHP SDK
===========

[](#mcp-php-sdk)

The official PHP SDK for Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP servers and clients in PHP.

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).

Until the first major release, this SDK is considered [experimental](https://symfony.com/doc/current/contributing/code/experimental.html), please see the [roadmap](./ROADMAP.md) for planned next steps and features.

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Overview](#overview)
- [Server SDK](#server-sdk)
- [Client SDK](#client-sdk)
- [Documentation](#documentation)
- [External Resources](#external-resources)
- [PHP Libraries Using the MCP SDK](#php-libraries-using-the-mcp-sdk)
- [Contributing](#contributing)
- [Credits](#credits)
- [License](#license)

Installation
------------

[](#installation)

```
composer require mcp/sdk
```

Overview
--------

[](#overview)

The MCP PHP SDK provides both **server** and **client** implementations for the Model Context Protocol, enabling you to:

- **Build MCP Servers**: Expose your PHP application's functionality (tools, resources, prompts) to AI agents
- **Build MCP Clients**: Connect to and interact with MCP servers from your PHP applications

Server SDK
----------

[](#server-sdk)

Build MCP servers to expose your PHP application's capabilities to AI agents like Claude, Codex, and others.

### Quick Start

[](#quick-start)

```
use Mcp\Server;
use Mcp\Server\Transport\StdioTransport;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\McpResource;

// Define capabilities using PHP attributes
class CalculatorCapabilities
{
    #[McpTool]
    public function add(int $a, int $b): int
    {
        return $a + $b;
    }

    #[McpResource(uri: 'config://calculator/settings')]
    public function getSettings(): array
    {
        return ['precision' => 2];
    }
}

// Build and run the server
$server = Server::builder()
    ->setServerInfo('Calculator Server', '1.0.0')
    ->setDiscovery(__DIR__, ['.'])  // Auto-discover attributes
    ->build();

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

### Server Capabilities

[](#server-capabilities)

- **Tools**: Executable functions that AI agents can call
- **Resources**: Data sources that can be read (files, configs, databases)
- **Resource Templates**: Dynamic resources with URI parameters
- **Prompts**: Pre-defined templates for AI interactions
- **Server-Initiated Communication**: Elicitations, sampling, logging, progress notifications

### Registration Methods

[](#registration-methods)

There are multiple ways to register your MCP capabilities—choose the approach that best fits your application's architecture:

**1. Attribute-Based Discovery** — Define capabilities using PHP attributes for automatic discovery:

```
#[McpTool]
public function generateReport(): string { /* ... */ }

#[McpResource(uri: 'config://app/settings')]
public function getConfig(): array { /* ... */ }
```

**2. Manual Registration** — Register capabilities programmatically without attributes:

```
$server = Server::builder()
    ->addTool([Calculator::class, 'add'], 'add_numbers')
    ->addResource([Config::class, 'get'], 'config://app')
    ->build();
```

**3. Hybrid Approach** — Combine both methods for maximum flexibility:

```
$server = Server::builder()
    ->setDiscovery(__DIR__, ['.'])
    ->addTool([ExternalService::class, 'process'], 'external')
    ->build();
```

### Transports

[](#transports)

Choose the transport that matches your deployment environment:

**1. STDIO Transport** — For command-line integration and local processes:

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

**2. HTTP Transport** — For web-based servers and distributed systems:

```
$transport = new StreamableHttpTransport($request, $responseFactory, $streamFactory);
$response = $server->run($transport);
```

### Session Management

[](#session-management)

Configure session storage to maintain state between requests. Choose the backend that fits your infrastructure:

**In-Memory** (default, suitable for STDIO):

```
$server = Server::builder()
    ->setSession(ttl: 7200) // 2 hours
    ->build();
```

**File-Based** (suitable for single-server HTTP deployments):

```
$server = Server::builder()
    ->setSession(new FileSessionStore(__DIR__ . '/sessions'))
    ->build();
```

**PSR-16 Cache** (for example with Redis for scaled deployments):

```
$server = Server::builder()
    ->setSession(new Psr16SessionStore(
        cache: new Psr16Cache($redisAdapter),
        prefix: 'mcp-',
        ttl: 3600
    ))
    ->build();
```

[→ Server Documentation](docs/server-builder.md)

Client SDK
----------

[](#client-sdk)

Connect to MCP servers from your PHP applications to access their tools, resources, and prompts.

### Quick Start

[](#quick-start-1)

```
use Mcp\Client;
use Mcp\Client\Transport\StdioTransport;

// Build the client
$client = Client::builder()
    ->setClientInfo('My Application', '1.0.0')
    ->setInitTimeout(30)
    ->setRequestTimeout(120)
    ->build();

// Connect to a server
$transport = new StdioTransport(
    command: 'php',
    args: ['/path/to/server.php'],
);

$client->connect($transport);

// Discover and use capabilities
$tools = $client->listTools();
$result = $client->callTool('add', ['a' => 5, 'b' => 3]);

$resources = $client->listResources();
$content = $client->readResource('config://calculator/settings');

$client->disconnect();
```

### Client Capabilities

[](#client-capabilities)

- **Tool Calling**: List and execute tools from any MCP server
- **Resource Access**: Read static and dynamic resources
- **Prompt Management**: List and retrieve prompt templates
- **Completion Support**: Request argument completion suggestions

### Advanced Features

[](#advanced-features)

- **Progress Tracking**: Real-time progress during long operations

```
$result = $client->callTool(
    name: 'process_data',
    arguments: ['dataset' => 'large_file.csv'],
    onProgress: function (float $progress, ?float $total, ?string $message) {
        echo "Progress: {$progress}/{$total} - {$message}\n";
    }
);
```

- **Sampling Support**: Handle server LLM sampling requests

```
$samplingHandler = new SamplingRequestHandler($myCallback);
$client = Client::builder()
    ->setCapabilities(new ClientCapabilities(sampling: true))
    ->addRequestHandler($samplingHandler)
    ->build();
```

- **Logging Notifications**: Receive server log messages

```
$loggingHandler = new LoggingNotificationHandler($myCallback);
$client = Client::builder()
    ->addNotificationHandler($loggingHandler)
    ->build();
```

### Transports

[](#transports-1)

Connect to MCP servers using the transport that matches your setup:

**1. STDIO Transport** — Connect to local server processes:

```
$transport = new StdioTransport(
    command: 'php',
    args: ['/path/to/server.php'],
);

$client->connect($transport);
```

**2. HTTP Transport** — Connect to remote or web-based servers:

```
$transport = new HttpTransport('http://localhost:8000');

$client->connect($transport);
```

[→ Client Documentation](docs/client.md)

Documentation
-------------

[](#documentation)

### Core Concepts

[](#core-concepts)

- **[Server Builder](docs/server-builder.md)** — Complete ServerBuilder reference and configuration
- **[Client](docs/client.md)** — Client SDK for connecting to and communicating with MCP servers
- **[Transports](docs/transports.md)** — STDIO and HTTP transport setup and usage
- **[MCP Elements](docs/mcp-elements.md)** — Creating tools, resources, prompts, and templates
- **[Server-Client Communication](docs/server-client-communication.md)** — Sampling, logging, progress, and notifications
- **[Events](docs/events.md)** — Hooking into server lifecycle with events

### Learning &amp; Examples

[](#learning--examples)

- **[Examples](docs/examples.md)** — Comprehensive example walkthroughs for servers and clients
- **[ROADMAP.md](ROADMAP.md)** — Planned features and development roadmap

External Resources
------------------

[](#external-resources)

- **[Model Context Protocol Documentation](https://modelcontextprotocol.io)** — Official MCP documentation
- **[Model Context Protocol Specification](https://spec.modelcontextprotocol.io)** — Protocol specification
- **[Officially Supported Servers](https://github.com/modelcontextprotocol/servers)** — Reference server implementations

PHP Libraries Using the MCP SDK
-------------------------------

[](#php-libraries-using-the-mcp-sdk)

- [pronskiy/mcp](https://github.com/pronskiy/mcp) — Additional developer experience layer
- [symfony/mcp-bundle](https://github.com/symfony/mcp-bundle) — Symfony integration bundle
- [josbeir/cakephp-synapse](https://github.com/josbeir/cakephp-synapse) — CakePHP integration plugin

Contributing
------------

[](#contributing)

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).

Credits
-------

[](#credits)

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.

License
-------

[](#license)

This project is licensed under the Apache License, Version 2.0 for new contributions, with existing code under the MIT License — see the [LICENSE](LICENSE) file for details.

###  Health Score

60

—

FairBetter than 99% of packages

Maintenance87

Actively maintained with recent releases

Popularity64

Solid adoption and visibility

Community48

Growing community involvement

Maturity41

Maturing project, gaining track record

 Bus Factor3

3 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Total

6

Last Release

84d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/47313?v=4)[Fabien Potencier](/maintainers/fabpot)[@fabpot](https://github.com/fabpot)

![](https://www.gravatar.com/avatar/ce180087f0c7ee6786102330114e44703cd4e2e905312c387bf0f2688085c251?d=identicon)[pronskiy](/maintainers/pronskiy)

![](https://www.gravatar.com/avatar/be7afcf8457f148619196060145a451e8e27e5353aacecfa18b69284768515b2?d=identicon)[dsp](/maintainers/dsp)

![](https://www.gravatar.com/avatar/e644c6c1e90b7d997edd1c25da41c48a76d89b7449fb5788214b341e2cd1a019?d=identicon)[chr-hertel](/maintainers/chr-hertel)

---

Top Contributors

[![chr-hertel](https://avatars.githubusercontent.com/u/2852185?v=4)](https://github.com/chr-hertel "chr-hertel (51 commits)")[![CodeWithKyrian](https://avatars.githubusercontent.com/u/48791154?v=4)](https://github.com/CodeWithKyrian "CodeWithKyrian (22 commits)")[![Nyholm](https://avatars.githubusercontent.com/u/1275206?v=4)](https://github.com/Nyholm "Nyholm (20 commits)")[![OskarStark](https://avatars.githubusercontent.com/u/995707?v=4)](https://github.com/OskarStark "OskarStark (11 commits)")[![soyuka](https://avatars.githubusercontent.com/u/1321971?v=4)](https://github.com/soyuka "soyuka (7 commits)")[![luoyue712](https://avatars.githubusercontent.com/u/102944161?v=4)](https://github.com/luoyue712 "luoyue712 (7 commits)")[![bigdevlarry](https://avatars.githubusercontent.com/u/29729601?v=4)](https://github.com/bigdevlarry "bigdevlarry (6 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")[![bb-c24](https://avatars.githubusercontent.com/u/182124730?v=4)](https://github.com/bb-c24 "bb-c24 (4 commits)")[![ineersa](https://avatars.githubusercontent.com/u/4228843?v=4)](https://github.com/ineersa "ineersa (4 commits)")[![sveneld](https://avatars.githubusercontent.com/u/4028769?v=4)](https://github.com/sveneld "sveneld (3 commits)")[![Adebayo120](https://avatars.githubusercontent.com/u/54323098?v=4)](https://github.com/Adebayo120 "Adebayo120 (2 commits)")[![alexislefebvre](https://avatars.githubusercontent.com/u/2071331?v=4)](https://github.com/alexislefebvre "alexislefebvre (2 commits)")[![EdouardCourty](https://avatars.githubusercontent.com/u/37371516?v=4)](https://github.com/EdouardCourty "EdouardCourty (2 commits)")[![xentixar](https://avatars.githubusercontent.com/u/152050438?v=4)](https://github.com/xentixar "xentixar (2 commits)")[![jonathanhefner](https://avatars.githubusercontent.com/u/771968?v=4)](https://github.com/jonathanhefner "jonathanhefner (1 commits)")[![kaipiyann](https://avatars.githubusercontent.com/u/821197?v=4)](https://github.com/kaipiyann "kaipiyann (1 commits)")[![e0ipso](https://avatars.githubusercontent.com/u/1140906?v=4)](https://github.com/e0ipso "e0ipso (1 commits)")[![markinigor](https://avatars.githubusercontent.com/u/18714154?v=4)](https://github.com/markinigor "markinigor (1 commits)")[![mpoiriert](https://avatars.githubusercontent.com/u/4175616?v=4)](https://github.com/mpoiriert "mpoiriert (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mcp-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/mcp-sdk/health.svg)](https://phpackages.com/packages/mcp-sdk)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5723.1M30](/packages/thecodingmachine-graphqlite)[windwalker/framework

The next generation PHP framework.

25639.1k1](/packages/windwalker-framework)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

81733.7k](/packages/flow-php-flow)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[tempest/framework

The PHP framework that gets out of your way.

2.1k23.1k9](/packages/tempest-framework)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
