Laravel MCP
Introduction
Laravel MCP는 AI 클라이언트가 Model Context Protocol을 사용해 Laravel 애플리케이션과 상호작용할 수 있는 간결하고 우아한 방법을 제공합니다. 서버, 툴, 리소스, 프롬프트를 정의하는 표현력 있고 유창한 인터페이스를 제공하여 애플리케이션에서 AI 기반 상호작용을 구현할 수 있게 합니다.
Installation
시작하려면 Composer 패키지 매니저로 프로젝트에 Laravel MCP를 설치합니다.
composer require laravel/mcp
Publishing Routes
Laravel MCP를 설치한 뒤, MCP 서버를 정의할 routes/ai.php 파일을 퍼블리싱하려면 vendor:publish Artisan 명령어를 실행합니다.
php artisan vendor:publish --tag=ai-routes
이 명령어는 애플리케이션의 routes 디렉터리에 routes/ai.php 파일을 생성합니다. 이 파일에서 MCP 서버를 등록합니다.
Creating Servers
make:mcp-server Artisan 명령어로 MCP 서버를 만들 수 있습니다. 서버는 툴, 리소스, 프롬프트 같은 MCP 기능을 AI 클라이언트에 노출하는 중앙 통신 지점 역할을 합니다.
php artisan make:mcp-server WeatherServer
이 명령어는 app/Mcp/Servers 디렉터리에 새 서버 클래스를 생성합니다. 생성된 서버 클래스는 Laravel MCP의 기본 Laravel\Mcp\Server 클래스를 확장하며, 툴, 리소스, 프롬프트를 등록하기 위한 프로퍼티를 제공합니다.
<?php
namespace App\Mcp\Servers;
use Laravel\Mcp\Server;
class WeatherServer extends Server
{
/**
* The tools registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Tool>>
*/
protected array $tools = [
// ExampleTool::class,
];
/**
* The resources registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Resource>>
*/
protected array $resources = [
// ExampleResource::class,
];
/**
* The prompts registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Prompt>>
*/
protected array $prompts = [
// ExamplePrompt::class,
];
}
Server Registration
서버를 만들었다면 접근할 수 있도록 routes/ai.php 파일에 등록해야 합니다. Laravel MCP는 서버를 등록하는 두 가지 메서드를 제공합니다. HTTP로 접근 가능한 서버에는 web, 명령줄 서버에는 local을 사용합니다.
Web Servers
웹 서버는 가장 일반적인 서버 유형이며 HTTP POST 요청으로 접근할 수 있어 원격 AI 클라이언트나 웹 기반 통합에 적합합니다. web 메서드로 웹 서버를 등록합니다.
use App\Mcp\Servers\WeatherServer;
use Laravel\Mcp\Facades\Mcp;
Mcp::web('/mcp/weather', WeatherServer::class);
일반 라우트처럼 미들웨어를 적용하여 웹 서버를 보호할 수 있습니다.
Mcp::web('/mcp/weather', WeatherServer::class)
->middleware(['throttle:mcp']);
Local Servers
로컬 서버는 Artisan 명령어로 실행되며 개발, 테스트, 로컬 AI 어시스턴트 통합에 적합합니다. local 메서드로 로컬 서버를 등록합니다.
use App\Mcp\Servers\WeatherServer;
use Laravel\Mcp\Facades\Mcp;
Mcp::local('weather', WeatherServer::class);
등록한 뒤에는 일반적으로 mcp:start를 직접 실행할 필요가 없습니다. 대신 MCP 클라이언트(AI 에이전트)가 서버를 시작하도록 설정합니다. mcp:start 명령어는 클라이언트가 호출하도록 설계되어 있으며, 클라이언트가 필요에 따라 서버 시작과 중지를 처리합니다.
php artisan mcp:start weather
Tools
툴을 사용하면 서버가 AI 클라이언트에서 호출할 수 있는 기능을 노출할 수 있습니다. 언어 모델은 툴을 통해 작업을 수행하거나, 코드를 실행하거나, 외부 시스템과 상호작용할 수 있습니다.
Creating Tools
툴을 만들려면 make:mcp-tool Artisan 명령어를 실행합니다.
php artisan make:mcp-tool CurrentWeatherTool
툴을 만든 뒤 서버의 $tools 프로퍼티에 등록합니다.
<?php
namespace App\Mcp\Servers;
use App\Mcp\Tools\CurrentWeatherTool;
use Laravel\Mcp\Server;
class WeatherServer extends Server
{
/**
* The tools registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Tool>>
*/
protected array $tools = [
CurrentWeatherTool::class,
];
}
Tool Name, Title, and Description
기본적으로 툴의 이름과 제목은 클래스 이름에서 파생됩니다. 예를 들어 CurrentWeatherTool의 이름은 current-weather, 제목은 Current Weather Tool이 됩니다. 툴의 $name과 $title 프로퍼티를 정의하여 이 값을 사용자 지정할 수 있습니다.
class CurrentWeatherTool extends Tool
{
/**
* The tool's name.
*/
protected string $name = 'get-optimistic-weather';
/**
* The tool's title.
*/
protected string $title = 'Get Optimistic Weather Forecast';
// ...
}
툴 설명은 자동으로 생성되지 않습니다. 툴에 $description 프로퍼티를 정의하여 항상 의미 있는 설명을 제공해야 합니다.
class CurrentWeatherTool extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'Fetches the current weather forecast for a specified location.';
//
}
설명은 AI 모델이 툴을 언제, 어떻게 효과적으로 사용할지 이해하는 데 도움이 되므로 툴 메타데이터의 중요한 부분입니다.
Tool Input Schemas
툴은 AI 클라이언트에서 어떤 인수를 받을지 지정하는 입력 스키마를 정의할 수 있습니다. Laravel의 Illuminate\JsonSchema\JsonSchema 빌더를 사용해 툴의 입력 요구 사항을 정의합니다.
<?php
namespace App\Mcp\Tools;
use Illuminate\JsonSchema\JsonSchema;
use Laravel\Mcp\Server\Tool;
class CurrentWeatherTool extends Tool
{
/**
* Get the tool's input schema.
*
* @return array<string, JsonSchema>
*/
public function schema(JsonSchema $schema): array
{
return [
'location' => $schema->string()
->description('The location to get the weather for.')
->required(),
'units' => $schema->enum(['celsius', 'fahrenheit'])
->description('The temperature units to use.')
->default('celsius'),
];
}
}
Validating Tool Arguments
JSON Schema 정의는 툴 인수의 기본 구조를 제공하지만, 더 복잡한 유효성 검증 규칙을 적용하고 싶을 수도 있습니다.
Laravel MCP는 Laravel의 validation features과 자연스럽게 통합됩니다. 툴의 handle 메서드 안에서 들어오는 툴 인수를 검증할 수 있습니다.
<?php
namespace App\Mcp\Tools;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
class CurrentWeatherTool extends Tool
{
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$validated = $request->validate([
'location' => 'required|string|max:100',
'units' => 'in:celsius,fahrenheit',
]);
// Fetch weather data using the validated arguments...
}
}
유효성 검증이 실패하면 AI 클라이언트는 제공된 오류 메시지를 기준으로 동작합니다. 따라서 명확하고 실행 가능한 오류 메시지를 제공하는 것이 중요합니다.
$validated = $request->validate([
'location' => ['required','string','max:100'],
'units' => 'in:celsius,fahrenheit',
],[
'location.required' => 'You must specify a location to get the weather for. For example, "New York City" or "Tokyo".',
'units.in' => 'You must specify either "celsius" or "fahrenheit" for the units.',
]);
Tool Dependency Injection
Laravel service container는 모든 툴을 해결하는 데 사용됩니다. 따라서 툴 생성자에서 필요한 의존성을 타입 힌트할 수 있습니다. 선언된 의존성은 자동으로 해결되어 툴 인스턴스에 주입됩니다.
<?php
namespace App\Mcp\Tools;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Server\Tool;
class CurrentWeatherTool extends Tool
{
/**
* Create a new tool instance.
*/
public function __construct(
protected WeatherRepository $weather,
) {}
// ...
}
생성자 주입뿐 아니라 툴의 handle() 메서드에서도 의존성을 타입 힌트할 수 있습니다. 메서드가 호출될 때 서비스 컨테이너가 의존성을 자동으로 해결하고 주입합니다.
<?php
namespace App\Mcp\Tools;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
class CurrentWeatherTool extends Tool
{
/**
* Handle the tool request.
*/
public function handle(Request $request, WeatherRepository $weather): Response
{
$location = $request->get('location');
$forecast = $weather->getForecastFor($location);
// ...
}
}
Tool Annotations
annotations으로 툴을 보강하여 AI 클라이언트에 추가 메타데이터를 제공할 수 있습니다. 이러한 애너테이션은 AI 모델이 툴의 동작과 기능을 이해하는 데 도움이 됩니다. 애너테이션은 attributes를 통해 툴에 추가합니다.
<?php
namespace App\Mcp\Tools;
use Laravel\Mcp\Server\Tools\Annotations\IsIdempotent;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
use Laravel\Mcp\Server\Tool;
#[IsIdempotent]
#[IsReadOnly]
class CurrentWeatherTool extends Tool
{
//
}
사용 가능한 애너테이션은 다음과 같습니다.
| Annotation | Type | Description |
|---|---|---|
#[IsReadOnly] | boolean | 툴이 환경을 수정하지 않음을 나타냅니다. |
#[IsDestructive] | boolean | 툴이 파괴적인 업데이트를 수행할 수 있음을 나타냅니다(읽기 전용이 아닐 때만 의미가 있습니다). |
#[IsIdempotent] | boolean | 같은 인수로 반복 호출해도 추가 효과가 없음을 나타냅니다(읽기 전용이 아닐 때). |
#[IsOpenWorld] | boolean | 툴이 외부 엔티티와 상호작용할 수 있음을 나타냅니다. |
Conditional Tool Registration
툴 클래스에 shouldRegister 메서드를 구현하면 런타임에 조건부로 툴을 등록할 수 있습니다. 이 메서드를 사용하면 애플리케이션 상태, 설정, 요청 파라미터를 기준으로 툴을 사용할 수 있게 할지 결정할 수 있습니다.
<?php
namespace App\Mcp\Tools;
use Laravel\Mcp\Request;
use Laravel\Mcp\Server\Tool;
class CurrentWeatherTool extends Tool
{
/**
* Determine if the tool should be registered.
*/
public function shouldRegister(Request $request): bool
{
return $request?->user()?->subscribed() ?? false;
}
}
툴의 shouldRegister 메서드가 false를 반환하면, 사용 가능한 툴 목록에 표시되지 않으며 AI 클라이언트가 호출할 수 없습니다.
Tool Responses
툴은 Laravel\Mcp\Response 인스턴스를 반환해야 합니다. Response 클래스는 여러 종류의 응답을 만들 수 있는 편리한 메서드를 제공합니다.
간단한 텍스트 응답에는 text 메서드를 사용합니다.
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
// ...
return Response::text('Weather Summary: Sunny, 72°F');
}
툴 실행 중 오류가 발생했음을 나타내려면 error 메서드를 사용합니다.
return Response::error('Unable to fetch weather data. Please try again.');
Multiple Content Responses
툴은 Response 인스턴스 배열을 반환하여 여러 콘텐츠를 반환할 수 있습니다.
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
/**
* Handle the tool request.
*
* @return array<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): array
{
// ...
return [
Response::text('Weather Summary: Sunny, 72°F'),
Response::text('**Detailed Forecast**\n- Morning: 65°F\n- Afternoon: 78°F\n- Evening: 70°F')
];
}
Streaming Responses
오래 실행되는 작업이나 실시간 데이터 스트리밍의 경우, 툴은 handle 메서드에서 generator를 반환할 수 있습니다. 이렇게 하면 최종 응답 전에 중간 업데이트를 클라이언트에 보낼 수 있습니다.
<?php
namespace App\Mcp\Tools;
use Generator;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
class CurrentWeatherTool extends Tool
{
/**
* Handle the tool request.
*
* @return \Generator<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): Generator
{
$locations = $request->array('locations');
foreach ($locations as $index => $location) {
yield Response::notification('processing/progress', [
'current' => $index + 1,
'total' => count($locations),
'location' => $location,
]);
yield Response::text($this->forecastFor($location));
}
}
}
웹 기반 서버를 사용할 때 스트리밍 응답은 자동으로 SSE (Server-Sent Events) 스트림을 열고, yield된 각 메시지를 이벤트로 클라이언트에 전송합니다.
Prompts
Prompts를 사용하면 서버가 AI 클라이언트가 언어 모델과 상호작용할 때 사용할 수 있는 재사용 가능한 프롬프트 템플릿을 공유할 수 있습니다. 프롬프트는 일반적인 쿼리와 상호작용을 구조화하는 표준화된 방식을 제공합니다.
Creating Prompts
프롬프트를 생성하려면 make:mcp-prompt Artisan 명령어를 실행합니다.
php artisan make:mcp-prompt DescribeWeatherPrompt
프롬프트를 생성한 뒤에는 서버의 $prompts 프로퍼티에 등록합니다.
<?php
namespace App\Mcp\Servers;
use App\Mcp\Prompts\DescribeWeatherPrompt;
use Laravel\Mcp\Server;
class WeatherServer extends Server
{
/**
* The prompts registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Prompt>>
*/
protected array $prompts = [
DescribeWeatherPrompt::class,
];
}
Prompt Name, Title, and Description
기본적으로 프롬프트의 이름과 제목은 클래스 이름에서 파생됩니다. 예를 들어 DescribeWeatherPrompt는 이름이 describe-weather, 제목이 Describe Weather Prompt가 됩니다. 프롬프트에 $name과 $title 프로퍼티를 정의하여 이 값을 직접 지정할 수 있습니다.
class DescribeWeatherPrompt extends Prompt
{
/**
* The prompt's name.
*/
protected string $name = 'weather-assistant';
/**
* The prompt's title.
*/
protected string $title = 'Weather Assistant Prompt';
// ...
}
프롬프트 설명은 자동으로 생성되지 않습니다. 프롬프트에 $description 프로퍼티를 정의하여 의미 있는 설명을 항상 제공해야 합니다.
class DescribeWeatherPrompt extends Prompt
{
/**
* The prompt's description.
*/
protected string $description = 'Generates a natural-language explanation of the weather for a given location.';
//
}
설명은 AI 모델이 프롬프트를 언제, 어떻게 가장 잘 활용할 수 있는지 이해하는 데 도움을 주므로 프롬프트 메타데이터에서 매우 중요한 부분입니다.
Prompt Arguments
프롬프트는 AI 클라이언트가 특정 값으로 프롬프트 템플릿을 커스터마이징할 수 있도록 인수를 정의할 수 있습니다. 프롬프트가 허용하는 인수는 arguments 메서드로 정의합니다.
<?php
namespace App\Mcp\Prompts;
use Laravel\Mcp\Server\Prompt;
use Laravel\Mcp\Server\Prompts\Argument;
class DescribeWeatherPrompt extends Prompt
{
/**
* Get the prompt's arguments.
*
* @return array<int, \Laravel\Mcp\Server\Prompts\Argument>
*/
public function arguments(): array
{
return [
new Argument(
name: 'tone',
description: 'The tone to use in the weather description (e.g., formal, casual, humorous).',
required: true,
),
];
}
}
Validating Prompt Arguments
프롬프트 인수는 정의에 따라 자동으로 유효성 검증되지만, 더 복잡한 유효성 검증 규칙을 적용하고 싶을 수도 있습니다.
Laravel MCP는 Laravel의 validation features과 자연스럽게 통합됩니다. 프롬프트의 handle 메서드 안에서 들어오는 프롬프트 인수를 검증할 수 있습니다.
<?php
namespace App\Mcp\Prompts;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;
class DescribeWeatherPrompt extends Prompt
{
/**
* Handle the prompt request.
*/
public function handle(Request $request): Response
{
$validated = $request->validate([
'tone' => 'required|string|max:50',
]);
$tone = $validated['tone'];
// Generate the prompt response using the given tone...
}
}
유효성 검증에 실패하면 AI 클라이언트는 제공된 오류 메시지에 따라 동작합니다. 따라서 명확하고 조치 가능한 오류 메시지를 제공하는 것이 중요합니다.
$validated = $request->validate([
'tone' => ['required','string','max:50'],
],[
'tone.*' => 'You must specify a tone for the weather description. Examples include "formal", "casual", or "humorous".',
]);
Prompt Dependency Injection
모든 프롬프트는 Laravel service container를 사용해 resolve됩니다. 따라서 프롬프트 생성자에 필요한 의존성을 타입 힌트할 수 있습니다. 선언된 의존성은 자동으로 resolve되어 프롬프트 인스턴스에 주입됩니다.
<?php
namespace App\Mcp\Prompts;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Server\Prompt;
class DescribeWeatherPrompt extends Prompt
{
/**
* Create a new prompt instance.
*/
public function __construct(
protected WeatherRepository $weather,
) {}
//
}
생성자 주입뿐 아니라 프롬프트의 handle 메서드에서도 의존성을 타입 힌트할 수 있습니다. 메서드가 호출될 때 서비스 컨테이너가 해당 의존성을 자동으로 resolve하고 주입합니다.
<?php
namespace App\Mcp\Prompts;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;
class DescribeWeatherPrompt extends Prompt
{
/**
* Handle the prompt request.
*/
public function handle(Request $request, WeatherRepository $weather): Response
{
$isAvailable = $weather->isServiceAvailable();
// ...
}
}
Conditional Prompt Registration
프롬프트 클래스에 shouldRegister 메서드를 구현하면 런타임에 프롬프트를 조건부로 등록할 수 있습니다. 이 메서드를 사용하면 애플리케이션 상태, 설정, 요청 파라미터에 따라 프롬프트를 사용할 수 있어야 하는지 결정할 수 있습니다.
<?php
namespace App\Mcp\Prompts;
use Laravel\Mcp\Request;
use Laravel\Mcp\Server\Prompt;
class CurrentWeatherPrompt extends Prompt
{
/**
* Determine if the prompt should be registered.
*/
public function shouldRegister(Request $request): bool
{
return $request?->user()?->subscribed() ?? false;
}
}
프롬프트의 shouldRegister 메서드가 false를 반환하면, 사용 가능한 프롬프트 목록에 표시되지 않으며 AI 클라이언트가 호출할 수 없습니다.
Prompt Responses
프롬프트는 단일 Laravel\Mcp\Response 또는 Laravel\Mcp\Response 인스턴스의 iterable을 반환할 수 있습니다. 이 응답들은 AI 클라이언트로 전송될 콘텐츠를 캡슐화합니다.
<?php
namespace App\Mcp\Prompts;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;
class DescribeWeatherPrompt extends Prompt
{
/**
* Handle the prompt request.
*
* @return array<int, \Laravel\Mcp\Response>
*/
public function handle(Request $request): array
{
$tone = $request->string('tone');
$systemMessage = "You are a helpful weather assistant. Please provide a weather description in a {$tone} tone.";
$userMessage = "What is the current weather like in New York City?";
return [
Response::text($systemMessage)->asAssistant(),
Response::text($userMessage),
];
}
}
asAssistant() 메서드를 사용하면 응답 메시지를 AI 어시스턴트가 보낸 것으로 처리해야 함을 나타낼 수 있습니다. 일반 메시지는 사용자 입력으로 처리됩니다.
Resources
Resources를 사용하면 서버가 AI 클라이언트가 언어 모델과 상호작용할 때 읽고 컨텍스트로 사용할 수 있는 데이터와 콘텐츠를 노출할 수 있습니다. 리소스는 문서, 설정처럼 정적 또는 동적인 정보나 AI 응답에 도움이 되는 데이터를 공유하는 방법을 제공합니다.
Creating Resources
리소스를 생성하려면 make:mcp-resource Artisan 명령어를 실행합니다.
php artisan make:mcp-resource WeatherGuidelinesResource
리소스를 만든 뒤 서버의 $resources 프로퍼티에 등록합니다.
<?php
namespace App\Mcp\Servers;
use App\Mcp\Resources\WeatherGuidelinesResource;
use Laravel\Mcp\Server;
class WeatherServer extends Server
{
/**
* The resources registered with this MCP server.
*
* @var array<int, class-string<\Laravel\Mcp\Server\Resource>>
*/
protected array $resources = [
WeatherGuidelinesResource::class,
];
}
Resource Name, Title, and Description
기본적으로 리소스의 이름과 제목은 클래스 이름에서 파생됩니다. 예를 들어 WeatherGuidelinesResource의 이름은 weather-guidelines이고 제목은 Weather Guidelines Resource입니다. 리소스에 $name과 $title 프로퍼티를 정의하여 이 값을 직접 지정할 수 있습니다.
class WeatherGuidelinesResource extends Resource
{
/**
* The resource's name.
*/
protected string $name = 'weather-api-docs';
/**
* The resource's title.
*/
protected string $title = 'Weather API Documentation';
// ...
}
리소스 설명은 자동으로 생성되지 않습니다. 리소스에 $description 프로퍼티를 정의하여 항상 의미 있는 설명을 제공해야 합니다.
class WeatherGuidelinesResource extends Resource
{
/**
* The resource's description.
*/
protected string $description = 'Comprehensive guidelines for using the Weather API.';
//
}
설명은 리소스 메타데이터의 중요한 부분입니다. AI 모델이 리소스를 언제, 어떻게 효과적으로 사용할지 이해하는 데 도움이 되기 때문입니다.
Resource URI and MIME Type
각 리소스는 고유한 URI로 식별되며, AI 클라이언트가 리소스 형식을 이해하는 데 도움이 되는 MIME 타입이 연결됩니다.
기본적으로 리소스 URI는 리소스 이름을 기준으로 생성되므로, WeatherGuidelinesResource의 URI는 weather://resources/weather-guidelines입니다. 기본 MIME 타입은 text/plain입니다.
리소스에 $uri와 $mimeType 프로퍼티를 정의하여 이 값을 직접 지정할 수 있습니다.
<?php
namespace App\Mcp\Resources;
use Laravel\Mcp\Server\Resource;
class WeatherGuidelinesResource extends Resource
{
/**
* The resource's URI.
*/
protected string $uri = 'weather://resources/guidelines';
/**
* The resource's MIME type.
*/
protected string $mimeType = 'application/pdf';
}
URI와 MIME 타입은 AI 클라이언트가 리소스 콘텐츠를 적절히 처리하고 해석하는 방법을 결정하는 데 도움이 됩니다.
Resource Request
툴과 프롬프트와 달리 리소스는 입력 스키마나 인수를 정의할 수 없습니다. 하지만 리소스의 handle 메서드 안에서 요청 객체와 상호작용할 수는 있습니다.
<?php
namespace App\Mcp\Resources;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Resource;
class WeatherGuidelinesResource extends Resource
{
/**
* Handle the resource request.
*/
public function handle(Request $request): Response
{
// ...
}
}
Resource Dependency Injection
Laravel service container는 모든 리소스를 resolve하는 데 사용됩니다. 따라서 리소스 생성자에서 필요한 의존성을 타입 힌트할 수 있습니다. 선언한 의존성은 자동으로 resolve되어 리소스 인스턴스에 주입됩니다.
<?php
namespace App\Mcp\Resources;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Server\Resource;
class WeatherGuidelinesResource extends Resource
{
/**
* Create a new resource instance.
*/
public function __construct(
protected WeatherRepository $weather,
) {}
// ...
}
생성자 주입뿐 아니라 리소스의 handle 메서드에서도 의존성을 타입 힌트할 수 있습니다. 이 메서드가 호출될 때 서비스 컨테이너가 의존성을 자동으로 resolve하여 주입합니다.
<?php
namespace App\Mcp\Resources;
use App\Repositories\WeatherRepository;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Resource;
class WeatherGuidelinesResource extends Resource
{
/**
* Handle the resource request.
*/
public function handle(WeatherRepository $weather): Response
{
$guidelines = $weather->guidelines();
return Response::text($guidelines);
}
}
Conditional Resource Registration
리소스 클래스에 shouldRegister 메서드를 구현하면 런타임에 리소스를 조건부로 등록할 수 있습니다. 이 메서드로 애플리케이션 상태, 설정, 요청 파라미터를 기준으로 리소스를 사용할 수 있는지 결정할 수 있습니다.
<?php
namespace App\Mcp\Resources;
use Laravel\Mcp\Request;
use Laravel\Mcp\Server\Resource;
class WeatherGuidelinesResource extends Resource
{
/**
* Determine if the resource should be registered.
*/
public function shouldRegister(Request $request): bool
{
return $request?->user()?->subscribed() ?? false;
}
}
리소스의 shouldRegister 메서드가 false를 반환하면 사용 가능한 리소스 목록에 표시되지 않으며, AI 클라이언트가 접근할 수 없습니다.
Resource Responses
리소스는 Laravel\Mcp\Response 인스턴스를 반환해야 합니다. Response 클래스는 여러 유형의 응답을 만들 수 있는 편리한 메서드를 제공합니다.
단순한 텍스트 콘텐츠에는 text 메서드를 사용합니다.
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
/**
* Handle the resource request.
*/
public function handle(Request $request): Response
{
// ...
return Response::text($weatherData);
}
Blob Responses
blob 콘텐츠를 반환하려면 blob 콘텐츠를 전달하여 blob 메서드를 사용합니다.
return Response::blob(file_get_contents(storage_path('weather/radar.png')));
blob 콘텐츠를 반환할 때 MIME 타입은 리소스 클래스의 $mimeType 프로퍼티 값으로 결정됩니다.
<?php
namespace App\Mcp\Resources;
use Laravel\Mcp\Server\Resource;
class WeatherGuidelinesResource extends Resource
{
/**
* The resource's MIME type.
*/
protected string $mimeType = 'image/png';
//
}
Error Responses
리소스를 가져오는 중 오류가 발생했음을 나타내려면 error() 메서드를 사용합니다.
return Response::error('Unable to fetch weather data for the specified location.');
Authentication
라우트에서 하듯이 미들웨어로 웹 MCP 서버를 인증할 수 있습니다. 이렇게 하면 사용자는 서버의 어떤 기능을 사용하기 전에 인증해야 합니다.
MCP 서버 접근을 인증하는 방법은 두 가지입니다. Laravel Sanctum을 이용한 단순한 토큰 기반 인증 또는 Authorization HTTP 헤더로 전달되는 임의의 API 토큰을 사용할 수 있습니다. 또는 Laravel Passport를 사용해 OAuth로 인증할 수도 있습니다.
OAuth 2.1
웹 기반 MCP 서버를 보호하는 가장 견고한 방법은 Laravel Passport를 통한 OAuth입니다.
OAuth로 MCP 서버를 인증할 때는 routes/ai.php 파일에서 Mcp::oauthRoutes 메서드를 호출하여 필요한 OAuth2 discovery와 클라이언트 등록 라우트를 등록합니다. 그런 다음 routes/ai.php 파일의 Mcp::web 라우트에 Passport의 auth:api 미들웨어를 적용합니다.
use App\Mcp\Servers\WeatherExample;
use Laravel\Mcp\Facades\Mcp;
Mcp::oauthRoutes();
Mcp::web('/mcp/weather', WeatherExample::class)
->middleware('auth:api');
New Passport Installation
애플리케이션에서 아직 Laravel Passport를 사용하고 있지 않다면 Passport의 installation and deployment steps를 먼저 따르십시오. 다음 단계로 넘어가기 전에 OAuthenticatable 모델, 새 인증 가드, passport 키가 있어야 합니다.
다음으로 Laravel MCP가 제공하는 Passport 인가 뷰를 게시해야 합니다.
php artisan vendor:publish --tag=mcp-views
그런 다음 Passport::authorizationView 메서드로 Passport가 이 뷰를 사용하도록 지정합니다. 일반적으로 이 메서드는 애플리케이션의 AppServiceProvider의 boot 메서드에서 호출해야 합니다.
use Laravel\Passport\Passport;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Passport::authorizationView(function ($parameters) {
return view('mcp.authorize', $parameters);
});
}
이 뷰는 인증 중 최종 사용자에게 표시되어 AI 에이전트의 인증 시도를 거부하거나 승인할 수 있게 합니다.
이 시나리오에서는 OAuth를 기본 authenticatable 모델로 이어지는 변환 계층으로만 사용합니다. 스코프 같은 OAuth의 많은 요소는 무시합니다.
Using an Existing Passport Installation
애플리케이션에서 이미 Laravel Passport를 사용하고 있다면 Laravel MCP는 기존 Passport 설치 안에서 원활하게 동작해야 합니다. 다만 OAuth는 주로 기본 authenticatable 모델로 이어지는 변환 계층으로 사용되므로, 현재 커스텀 스코프는 지원되지 않습니다.
Laravel MCP는 앞서 설명한 Mcp::oauthRoutes() 메서드를 통해 단일 mcp:use 스코프를 추가하고, 알리고, 사용합니다.
Passport vs. Sanctum
OAuth2.1은 Model Context Protocol 명세에 문서화된 인증 메커니즘이며 MCP 클라이언트에서 가장 폭넓게 지원됩니다. 따라서 가능하면 Passport 사용을 권장합니다.
애플리케이션에서 이미 Sanctum을 사용하고 있다면 Passport를 추가하는 일이 번거로울 수 있습니다. 이 경우 OAuth만 지원하는 MCP 클라이언트를 사용해야 하는 명확하고 필요한 요구 사항이 생기기 전까지는 Passport 없이 Sanctum을 사용하는 것을 권장합니다.
Sanctum
Sanctum으로 MCP 서버를 보호하려면 routes/ai.php 파일에서 서버에 Sanctum 인증 미들웨어를 추가하면 됩니다. 그런 다음 인증이 성공하도록 MCP 클라이언트가 Authorization: Bearer <token> 헤더를 제공하는지 확인합니다.
use App\Mcp\Servers\WeatherExample;
use Laravel\Mcp\Facades\Mcp;
Mcp::web('/mcp/demo', WeatherExample::class)
->middleware('auth:sanctum');
Custom MCP Authentication
애플리케이션에서 자체 커스텀 API 토큰을 발급한다면 원하는 미들웨어를 Mcp::web 라우트에 할당하여 MCP 서버를 인증할 수 있습니다. 커스텀 미들웨어는 Authorization 헤더를 직접 검사하여 들어오는 MCP 요청을 인증할 수 있습니다.
Authorization
$request->user() 메서드로 현재 인증된 사용자에 접근할 수 있으므로, MCP 툴과 리소스 안에서 authorization checks를 수행할 수 있습니다.
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
if (! $request->user()->can('read-weather')) {
return Response::error('Permission denied.');
}
// ...
}
Testing Servers
내장 MCP Inspector를 사용하거나 단위 테스트를 작성하여 MCP 서버를 테스트할 수 있습니다.
MCP Inspector
MCP Inspector는 MCP 서버를 테스트하고 디버깅하는 대화형 도구입니다. 이 도구로 서버에 연결하고, 인증을 확인하며, 툴, 리소스, 프롬프트를 시험해 볼 수 있습니다.
등록된 어떤 서버에 대해서도 inspector를 실행할 수 있습니다. 예를 들어 "weather"라는 로컬 서버에는 다음처럼 실행합니다.
php artisan mcp:inspector weather
이 명령어는 MCP Inspector를 실행하고, 모든 설정이 올바른지 확인하기 위해 MCP 클라이언트에 복사할 수 있는 클라이언트 설정을 제공합니다. 웹 서버가 인증 미들웨어로 보호되어 있다면 연결할 때 Authorization bearer 토큰 같은 필수 헤더를 반드시 포함하십시오.
Unit Tests
MCP 서버, 툴, 리소스, 프롬프트에 대한 단위 테스트를 작성할 수 있습니다.
시작하려면 새 테스트 케이스를 만들고, 해당 primitive를 등록한 서버에서 원하는 primitive를 호출합니다. 예를 들어 WeatherServer의 툴을 테스트하려면 다음처럼 작성합니다.
test('tool', function () {
$response = WeatherServer::tool(CurrentWeatherTool::class, [
'location' => 'New York City',
'units' => 'fahrenheit',
]);
$response
->assertOk()
->assertSee('The current weather in New York City is 72°F and sunny.');
});
/**
* Test a tool.
*/
public function test_tool(): void
{
$response = WeatherServer::tool(CurrentWeatherTool::class, [
'location' => 'New York City',
'units' => 'fahrenheit',
]);
$response
->assertOk()
->assertSee('The current weather in New York City is 72°F and sunny.');
}
마찬가지로 프롬프트와 리소스도 테스트할 수 있습니다.
$response = WeatherServer::prompt(...);
$response = WeatherServer::resource(...);
프리미티브를 호출하기 전에 actingAs 메서드를 체이닝하면 인증된 사용자로 동작할 수도 있습니다.
$response = WeatherServer::actingAs($user)->tool(...);
응답을 받으면 다양한 어설션 메서드로 응답의 내용과 상태를 검증할 수 있습니다.
assertOk 메서드를 사용해 응답이 성공했는지 검증할 수 있습니다. 이 메서드는 응답에 오류가 없는지 확인합니다.
$response->assertOk();
assertSee 메서드를 사용해 응답에 특정 텍스트가 포함되어 있는지 검증할 수 있습니다.
$response->assertSee('The current weather in New York City is 72°F and sunny.');
assertHasErrors 메서드를 사용해 응답에 오류가 포함되어 있는지 검증할 수 있습니다.
$response->assertHasErrors();
$response->assertHasErrors([
'Something went wrong.',
]);
assertHasNoErrors 메서드를 사용해 응답에 오류가 포함되어 있지 않은지 검증할 수 있습니다.
$response->assertHasNoErrors();
assertName(), assertTitle(), assertDescription() 메서드를 사용해 응답에 특정 메타데이터가 포함되어 있는지 검증할 수 있습니다.
$response->assertName('current-weather');
$response->assertTitle('Current Weather Tool');
$response->assertDescription('Fetches the current weather forecast for a specified location.');
assertSentNotification과 assertNotificationCount 메서드를 사용해 알림이 전송되었는지 검증할 수 있습니다.
$response->assertSentNotification('processing/progress', [
'step' => 1,
'total' => 5,
]);
$response->assertSentNotification('processing/progress', [
'step' => 2,
'total' => 5,
]);
$response->assertNotificationCount(5);
마지막으로 원시 응답 내용을 확인하려면 dd 또는 dump 메서드를 사용해 디버깅 목적으로 응답을 출력할 수 있습니다.
$response->dd();
$response->dump();