PHPackages                             prism-php/relay - 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. prism-php/relay

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

prism-php/relay
===============

A Prism tool for interacting with MCP servers

v1.8.0(1mo ago)15236.1k—8.2%20[11 issues](https://github.com/prism-php/relay/issues)2MITPHPPHP ^8.2CI passing

Since Apr 2Pushed 1mo ago4 watchersCompare

[ Source](https://github.com/prism-php/relay)[ Packagist](https://packagist.org/packages/prism-php/relay)[ GitHub Sponsors](https://github.com/sixlive)[ RSS](/packages/prism-php-relay/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (28)Versions (16)Used By (2)

[![](assets/relay-banner.webp)](assets/relay-banner.webp)

 [ ![Total Downloads](https://camo.githubusercontent.com/281a557e584f460df17dea9c61978678341d3a052ac03278af14661f5d8e0a35/68747470733a2f2f706f7365722e707567782e6f72672f707269736d2d7068702f72656c61792f642f746f74616c2e737667) ](https://packagist.org/packages/prism-php/relay) [ ![Latest Stable Version](https://camo.githubusercontent.com/f17f2ecafd08c0059a550ff98667522437c8c0c4f556152bfe11e1b269caed1e/68747470733a2f2f706f7365722e707567782e6f72672f707269736d2d7068702f72656c61792f762f737461626c652e737667) ](https://packagist.org/packages/prism-php/relay) [ ![License](https://camo.githubusercontent.com/fce06205f8a91228576e3cd2e0e2bfdd619a97f10fd0c9a73db33fd775eb0ab9/68747470733a2f2f706f7365722e707567782e6f72672f707269736d2d7068702f72656c61792f6c6963656e73652e737667) ](https://packagist.org/packages/prism-php/relay)

Relay
=====

[](#relay)

A seamless integration between [Prism](https://github.com/prism-php/prism) and Model Context Protocol (MCP) servers that empowers your AI applications with powerful, external tool capabilities.

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

[](#installation)

You can install the package via Composer:

```
composer require prism-php/relay
```

After installation, publish the configuration file:

```
php artisan vendor:publish --tag="relay-config"
```

Configuration
-------------

[](#configuration)

The published config file (`config/relay.php`) is where you'll define your MCP server connections.

### Configuring Servers

[](#configuring-servers)

You must define each MCP server explicitly in the config file. Each server needs a unique name and the appropriate configuration parameters:

```
return [
    'servers' => [
        'puppeteer' => [
            'command' => ['npx', '-y', '@modelcontextprotocol/server-puppeteer'],
            'timeout' => 30,
            'env' => [],
            'transport' => \Prism\Relay\Enums\Transport::Stdio,
        ],
        'github' => [
            'url' => env('RELAY_GITHUB_SERVER_URL', 'http://localhost:8001/api'),
            'timeout' => 30,
            'transport' => \Prism\Relay\Enums\Transport::Http,
        ],
    ],
    'cache_duration' => env('RELAY_TOOLS_CACHE_DURATION', 60), // in minutes (0 to disable)
];
```

Basic Usage
-----------

[](#basic-usage)

Here's how you can integrate MCP tools into your Prism agent:

```
use Prism\Prism\Prism;
use Prism\Relay\Facades\Relay;
use Prism\Prism\Enums\Provider;

$response = Prism::text()
    ->using(Provider::Anthropic, 'claude-3-7-sonnet-latest')
    ->withPrompt('Find information about Laravel on the web')
    ->withTools(Relay::tools('puppeteer'))
    ->asText();

return $response->text;
```

The agent can now use any tools provided by the Puppeteer MCP server, such as navigating to webpages, taking screenshots, clicking buttons, and more.

Real-World Example
------------------

[](#real-world-example)

Here's a practical example of creating a Laravel command that uses MCP tools with Prism:

```
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Prism\Relay\Facades\Relay;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Prism;
use Prism\Prism\Text\PendingRequest;

use function Laravel\Prompts\note;
use function Laravel\Prompts\textarea;

class MCP extends Command
{
    protected $signature = 'prism:mcp';

    public function handle()
    {
        $response = $this->agent(textarea('Prompt'))->asText();

        note($response->text);
    }

    protected function agent(string $prompt): PendingRequest
    {
        return Prism::text()
            ->using(Provider::Anthropic, 'claude-3-7-sonnet-latest')
            ->withSystemPrompt(view('prompts.nova-v2'))
            ->withPrompt($prompt)
            ->withTools([
                ...Relay::tools('puppeteer'),
            ])
            ->usingTopP(1)
            ->withMaxSteps(99)
            ->withMaxTokens(8192);
    }
}
```

This command creates an interactive CLI that lets you input prompts that will be sent to Claude. The agent can use Puppeteer tools to browse the web, complete tasks, and return the results.

Transport Types
---------------

[](#transport-types)

Relay supports multiple transport mechanisms:

### HTTP Transport

[](#http-transport)

For MCP servers that communicate over HTTP:

```
'github' => [
    'url' => env('RELAY_GITHUB_SERVER_URL', 'http://localhost:8000/api'),
    'api_key' => env('RELAY_GITHUB_SERVER_API_KEY'),
    'timeout' => 30,
    'transport' => Transport::Http,
    'headers' => [
        'User-Agent' => 'prism-php-relay/1.0',
    ]
],
```

#### OAuth / Bearer Token Authentication

[](#oauth--bearer-token-authentication)

The [MCP 2025-11-25 authorization spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) defines an OAuth 2.1 flow for HTTP-based transports. **Relay handles only the last step — attaching the token to every request.** Your application is responsible for running the full OAuth flow and supplying the resulting access token at runtime.

##### What your application must handle

[](#what-your-application-must-handle)

Before calling `withToken()`, your code must:

1. **Discover the authorization server** — make an unauthenticated request to the MCP server and read the `WWW-Authenticate` header from the `401` response, or probe `/.well-known/oauth-protected-resource`. The response contains the authorization server URL.
2. **Run the OAuth 2.1 authorization code flow** — including PKCE (`S256` code challenge is required by the spec) and the `resource` parameter ([RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html)) identifying the MCP server.
3. **Exchange the code for a token** and store/refresh it as needed. Tokens are short-lived; implement refresh token rotation.

Note

The spec covers this in detail: [MCP Authorization — 2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).

##### Passing the token to Relay

[](#passing-the-token-to-relay)

Once you have a valid Bearer token, pass it to Relay at request time. The runtime token takes priority over any static `api_key` set in config.

```
use Prism\Relay\Facades\Relay;
use Prism\Relay\Exceptions\AuthorizationException;
use Prism\Relay\Exceptions\TransportException;

// Via the Facade (returns a RelayBuilder)
$tools = Relay::withToken($request->user()->mcp_token)->tools('github');

// Or on a Relay instance
$relay = Relay::make('github');
$tools = $relay->withToken($request->user()->mcp_token)->tools();
```

When the MCP server rejects the token with HTTP 401, Relay throws `AuthorizationException`. Use this to trigger a re-authorization flow in your app:

```
try {
    $tools = Relay::withToken($token)->tools('github');
} catch (AuthorizationException $e) {
    // Token is missing, expired, or rejected (HTTP 401)
    // Re-run the OAuth flow to get a fresh token
    return redirect('/oauth/reconnect');
} catch (TransportException $e) {
    // Other transport failure (non-401)
    Log::error('MCP Transport error: ' . $e->getMessage());
}
```

Note

OAuth tokens are only supported with HTTP transport. Passing a token to a Stdio-configured server throws a `ServerConfigurationException`. For Stdio servers, provide credentials via the `env` config key instead.

### STDIO Transport

[](#stdio-transport)

For locally running MCP servers that communicate via standard I/O:

```
'puppeteer' => [
    'command' => [
      'npx',
      '-y',
      '@modelcontextprotocol/server-puppeteer',
      '--options',
      // Array values are passed as JSON encoded strings
      [
        'debug' => env('MCP_PUPPETEER_DEBUG', false)
      ]
    ],
    'timeout' => 30,
    'transport' => Transport::Stdio,
    'env' => [
        'NODE_ENV' => 'production',  // Set Node environment
        'MCP_SERVER_PORT' => '3001',  // Set a custom port for the server
    ],
],
```

Note

The STDIO transport launches a subprocess and communicates with it through standard input/output. This is perfect for running tools directly on your application server.

Tip

The `env` option allows you to pass environment variables to the MCP server process. This is useful for configuring server behavior, enabling debugging, or setting authentication details.

Advanced Usage
--------------

[](#advanced-usage)

### Using Multiple MCP Servers

[](#using-multiple-mcp-servers)

You can combine tools from multiple MCP servers in a single Prism agent:

```
use Prism\Prism\Prism;
use Prism\Relay\Facades\Relay;
use Prism\Prism\Enums\Provider;

$response = Prism::text()
    ->using(Provider::Anthropic, 'claude-3-7-sonnet-latest')
    ->withTools([
        ...Relay::tools('github'),
        ...Relay::tools('puppeteer')
    ])
    ->withPrompt('Find and take screenshots of Laravel repositories')
    ->asText();
```

### Error Handling

[](#error-handling)

The package uses specific exception types for better error handling:

```
use Prism\Relay\Exceptions\AuthorizationException;
use Prism\Relay\Exceptions\RelayException;
use Prism\Relay\Exceptions\ServerConfigurationException;
use Prism\Relay\Exceptions\ToolCallException;
use Prism\Relay\Exceptions\ToolDefinitionException;
use Prism\Relay\Exceptions\TransportException;

try {
    $tools = Relay::tools('puppeteer');
    // Use the tools...
} catch (ServerConfigurationException $e) {
    // Handle configuration errors (missing server, invalid settings)
    Log::error('MCP Server configuration error: ' . $e->getMessage());
} catch (ToolDefinitionException $e) {
    // Handle issues with tool definitions from the MCP server
    Log::error('MCP Tool definition error: ' . $e->getMessage());
} catch (AuthorizationException $e) {
    // Handle HTTP 401 — token is missing, expired, or invalid
    return redirect('/oauth/reconnect');
} catch (TransportException $e) {
    // Handle communication errors with the MCP server
    Log::error('MCP Transport error: ' . $e->getMessage());
} catch (ToolCallException $e) {
    // Handle errors when calling a specific tool
    Log::error('MCP Tool call error: ' . $e->getMessage());
} catch (RelayException $e) {
    // Handle any other MCP-related errors
    Log::error('Relay general error: ' . $e->getMessage());
}
```

License
-------

[](#license)

The MIT License (MIT). Please see the [License File](LICENSE) for more information.

###  Health Score

57

—

FairBetter than 98% of packages

Maintenance87

Actively maintained with recent releases

Popularity48

Moderate usage in the ecosystem

Community27

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 56.5% of commits — single point of failure

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 ~27 days

Recently: every ~32 days

Total

14

Last Release

59d ago

Major Versions

v0.4.0 → v1.0.02025-04-18

PHP version history (2 changes)v0.1.0PHP ^8.3

v1.1.0PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/5108034?v=4)[TJ Miller](/maintainers/sixlive)[@sixlive](https://github.com/sixlive)

---

Top Contributors

[![sixlive](https://avatars.githubusercontent.com/u/5108034?v=4)](https://github.com/sixlive "sixlive (13 commits)")[![fosron](https://avatars.githubusercontent.com/u/3708631?v=4)](https://github.com/fosron "fosron (1 commits)")[![hipig](https://avatars.githubusercontent.com/u/24596908?v=4)](https://github.com/hipig "hipig (1 commits)")[![kauffinger](https://avatars.githubusercontent.com/u/62616071?v=4)](https://github.com/kauffinger "kauffinger (1 commits)")[![michaeldyrynda](https://avatars.githubusercontent.com/u/558441?v=4)](https://github.com/michaeldyrynda "michaeldyrynda (1 commits)")[![patrickbrouwers](https://avatars.githubusercontent.com/u/7728097?v=4)](https://github.com/patrickbrouwers "patrickbrouwers (1 commits)")[![pushpak1300](https://avatars.githubusercontent.com/u/31663512?v=4)](https://github.com/pushpak1300 "pushpak1300 (1 commits)")[![stuartbrameld](https://avatars.githubusercontent.com/u/4751133?v=4)](https://github.com/stuartbrameld "stuartbrameld (1 commits)")[![vinitkadam03](https://avatars.githubusercontent.com/u/193695937?v=4)](https://github.com/vinitkadam03 "vinitkadam03 (1 commits)")[![Fludem](https://avatars.githubusercontent.com/u/11637247?v=4)](https://github.com/Fludem "Fludem (1 commits)")[![xar](https://avatars.githubusercontent.com/u/184865?v=4)](https://github.com/xar "xar (1 commits)")

---

Tags

ailaravelllmmcpmcp-clientprism

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/prism-php-relay/health.svg)

```
[![Health](https://phpackages.com/badges/prism-php-relay/health.svg)](https://phpackages.com/packages/prism-php-relay)
```

###  Alternatives

[wireui/wireui

TallStack components

1.8k1.3M16](/packages/wireui-wireui)[livewire/volt

An elegantly crafted functional API for Laravel Livewire.

4205.3M84](/packages/livewire-volt)[ramonrietdijk/livewire-tables

Dynamic tables for models with Laravel Livewire

21147.4k](/packages/ramonrietdijk-livewire-tables)[prism-php/bedrock

A provider for Prism adding support for AWS Bedrock.

35116.8k1](/packages/prism-php-bedrock)

PHPackages © 2026

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