PHP code example of bherila / mcp-laravel-bridge

1. Go to this page and download the library: Download bherila/mcp-laravel-bridge 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/ */

    

bherila / mcp-laravel-bridge example snippets


use Bherila\McpLaravelBridge\Http\McpHttpPolicy;

$this->app->singleton(McpHttpPolicy::class, fn () => new McpHttpPolicy(
    allowedOrigins: fn (): array => config('agent_api.mcp_allowed_origins', []),
    allowedHosts: fn (): array => array_values(array_unique([
        McpHttpPolicy::hostFromUrl((string) config('app.url')),
        McpHttpPolicy::hostFromUrl((string) config('bherila-auth.oauth_server.resource')),
    ])),
    maxRequestBodyBytes: (int) config('agent_api.mcp_max_body_bytes', 262_144),
    maxResponseBodyBytes: (int) config('agent_api.mcp_max_response_bytes', 1_048_576),
));

use Bherila\McpLaravelBridge\Http\McpHttpSecurityMiddleware;

Route::match(['POST', 'DELETE'], '/api/v1/mcp', AgentMcpController::class)
    ->middleware([
        McpHttpSecurityMiddleware::class,
        ExpectOAuthResource::class,
        'auth:api',
        CheckToken::using('mcp:use'),
        'throttle:60,1',
    ]);
Route::options('/api/v1/mcp', AgentMcpController::class)
    ->middleware(McpHttpSecurityMiddleware::class);

public function __invoke(
    Request $request,
    AgentMcpServerFactory $servers,
    McpHttpEndpoint $endpoint,
    McpHttpPolicy $policy,
): Response {
    return $endpoint->run(
        $request,
        fn (Request $request): Server => $servers->make($request),
        $policy,
    );
}

$server = SyntheticMcpServerFactory::make(
    fn (): array => $applicationService->ping(),
);

use Bherila\McpLaravelBridge\Mcp\ToolWithSecuritySchemes;

$tool = new ToolWithSecuritySchemes(
    securitySchemes: [[
        'type' => 'oauth2',
        'scopes' => ['mcp:use', 'records:read'],
    ]],
    name: 'records.list',
    title: 'List records',
    // Empty JSON object schemas must remain objects on SDK 0.7.
    inputSchema: ['type' => 'object', 'properties' => (object) []],
    description: 'Lists authorized records.',
    annotations: $annotations,
);

$registry->registerTool($tool, $handler);

use Bherila\McpLaravelBridge\Capabilities\{Effect, IdempotencyKey, McpBinding, Operation, OperationRegistry, Requirement, RestBinding, SchemaRef, WriteSafety};

$registry = (new OperationRegistry)->register(new Operation(
    id: 'things.create',
    title: 'Create thing',
    description: 'Create a thing.',
    effect: Effect::LocalWrite,
    ine array (code-first)
    output: SchemaRef::responseOf('things.create'),
));

$builder = new OpenApiDocumentBuilder($registry, new OpenApiSettings(
    title: 'Things API',
    version: '1',
    serverUrl: config('bherila-auth.oauth_server.resource'),
    authorizationUrl: config('bherila-auth.oauth_server.authorization_endpoint'),
    tokenUrl: config('bherila-auth.oauth_server.token_endpoint'),
    scopes: Scopes::descriptions(),
    connectionScopes: ['mcp:use'],        // operations needing these are OAuth-only
    extraMediaTypes: ['application/toon'], // optional, beside application/json
), $catalog);                              // a SchemaCatalog when operations use SchemaRef

return response()->json($builder->full()); // or ->filtered($availability, $principal)

new RestBinding('DELETE', '/things/{thing}',
    description: 'Deletes one thing at its current version.', // or false for none; null keeps the operation's
    parameters: ['ThingId', 'IdempotencyKey', ['name' => 'reason', 'in' => 'query', 'schema' => ['type' => 'string']]],
    requestSchema: SchemaRef::openApi('ExpectedVersion'),     // the REST body; also how a DELETE documents one; false for none
    responseSchema: SchemaRef::openApi('Deletion'),           // when the REST response differs from the MCP output
    responseDescriptions: [200 => 'Thing deleted'],
    responses: [404 => 'NotFound', 200 => [/* a whole response object, e.g. a binary download */]],
    requestBodyRequired: true,
);

new OpenApiSettings(...,
    summaries: false,            // no summary unless a binding declares one
    agentExtensions: false,      // no x-agent-*; an operation's own `extensions` are still emitted
    parameters: ['ThingId' => [...], 'IdempotencyKey' => [...]],   // components/parameters
    responses: ['Error' => [...], 'NotFound' => [...]],            // components/responses
    sharedResponses: ['default' => 'Error'],                      // added to every operation
    apiTokenBearerFormat: 'JWT', oauthDescription: '...', refreshUrl: false,
);

$this->app->instance(PayloadCodecs::class, new PayloadCodecs(new ToonCodec)); // the bridge ships no codec

OperationRoutes::macro();                       // once, e.g. in a service provider
Route::prefix('api/v1')->name('api.')->group(function () {
    Route::operation('things.list', [ThingController::class, 'index']);
});