PHP code example of organiseyou / mcp-server

1. Go to this page and download the library: Download organiseyou/mcp-server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

organiseyou / mcp-server example snippets


return [
    'server' => [
        'name'    => env('APP_NAME', 'Laravel'),
        'version' => '1.0.0',
    ],

    'transport' => [
        'http'            => true,   // expose POST /mcp
        'http_path'       => '/mcp',
        'http_middleware' => [],     // e.g. ['auth:sanctum']
    ],

    'tools' => [
        // App\Mcp\Tools\StaticTool::class,
    ],
];

use OrganiseYou\McpServer\Facades\Mcp;

// Single tool
Mcp::tool('add_numbers')
    ->description('Add two numbers together and return the sum.')
    ->inputSchema([
        'type'       => 'object',
        'properties' => [
            'a' => ['type' => 'number', 'description' => 'First operand.'],
            'b' => ['type' => 'number', 'description' => 'Second operand.'],
        ],
        '

// In a tenant boot hook or middleware
foreach ($tenant->enabledDataSources() as $source) {
    Mcp::tool("query_{$source->slug}")
        ->description("Query the {$source->name} dataset. " . $source->description)
        ->inputSchema($source->buildInputSchema())
        ->handle(fn (array $input) => $source->query($input));
}



namespace App\Mcp\Tools;

use App\Models\Order;
use OrganiseYou\McpServer\Contracts\McpTool;

class GetOrderTool implements McpTool
{
    public function __construct(private OrderRepository $orders) {}

    public function name(): string
    {
        return 'get_order';
    }

    public function description(): string
    {
        return 'Retrieve an order by its ID, including line items and shipping status.';
    }

    public function inputSchema(): array
    {
        return [
            'type'       => 'object',
            'properties' => [
                'order_id' => [
                    'type'        => 'integer',
                    'description' => 'The ID of the order to retrieve.',
                ],
            ],
            '

// config/mcp.php
'tools' => [
    App\Mcp\Tools\GetOrderTool::class,
],

use OrganiseYou\McpServer\ToolContext;

Mcp::tool('list_fields')
    ->handle(function (array $input, ToolContext $context) {
        // $context->requestId  — the JSON-RPC id of this call
        // $context->actor      — whatever your app put there (a user, a tenant, …)
        // $context->scopes     — string[]
        // $context->attributes — anything else, opaque to the package
        return $context->hasScope('metadata:read') ? $this->fields() : [];
    });

$this->app->scoped(ToolContext::class, fn () => new ToolContext(
    actor:  auth()->user(),
    scopes: auth()->user()?->mcpScopes() ?? [],
));

use OrganiseYou\McpServer\Exceptions\ToolError;

throw new ToolError('forbidden', 'You cannot edit this model.');
// → {"content":[{"type":"text","text":"{\"reason\":\"forbidden\",\"message\":\"You cannot edit this model.\"}"}],"isError":true}

Mcp::tool('delete_field')
    ->annotations(['destructiveHint' => true, 'idempotentHint' => true])
    ->handle(fn (array $input) => ...);

use OrganiseYou\McpServer\Server\McpServer;
use OrganiseYou\McpServer\ToolContext;

$result = app(McpServer::class)->callTool('list_fields', ['model' => 'order'], new ToolContext(actor: $user));
// ['content' => [['type' => 'text', 'text' => '...']], 'isError' => false]

'logging' => [
    'enabled' => env('MCP_LOGGING_ENABLED', false),
    'channel' => env('MCP_LOG_CHANNEL', null),
    'level'   => env('MCP_LOG_LEVEL', 'debug'),
    'redact'  => null,
],

'redact' => App\Mcp\RedactSecrets::class,

// app/Mcp/RedactSecrets.php
class RedactSecrets
{
    public function __invoke(array $input): array
    {
        return array_diff_key($input, array_flip(['password', 'token']));
    }
}

use OrganiseYou\McpServer\Logging\McpLogger;

class GetOrderTool implements McpTool
{
    public function __construct(
        private OrderRepository $orders,
        private McpLogger $logger,
    ) {}

    public function __invoke(array $input): mixed
    {
        $this->logger->logActivity('Fetching order', ['order_id' => $input['order_id']]);

        return $this->orders->find($input['order_id']);
    }
}

use Illuminate\Support\Facades\Log;

Mcp::tool('ping')
    ->description('Health check')
    ->inputSchema(['type' => 'object', 'properties' => []])
    ->handle(function (array $input) {
        Log::debug('ping tool called', $input);
        return 'pong';
    });

// app/Mcp/TenantMcpLogger.php
namespace App\Mcp;

use OrganiseYou\McpServer\Logging\McpLogger;

class TenantMcpLogger extends McpLogger
{
    protected function context(): array
    {
        return ['tenant_id' => tenant()?->id];
    }
}

// AppServiceProvider::register()
$this->app->singleton(\OrganiseYou\McpServer\Logging\McpLogger::class, \App\Mcp\TenantMcpLogger::class);

'http_middleware' => ['auth:sanctum'],
bash
php artisan vendor:publish --tag=mcp-config
bash
php artisan mcp:serve
bash
docker run --rm -v $(pwd):/app -w /app php:8.4-cli php vendor/bin/phpunit
docker run --rm -v $(pwd):/app -w /app php:8.3-cli php vendor/bin/phpunit