diff --git a/README.es.md b/README.es.md
index 2bfb44e..c3cf080 100644
--- a/README.es.md
+++ b/README.es.md
@@ -26,6 +26,10 @@
Español
+
+
+
+
## ⚠️ Información de Versión y Cambios Disruptivos
### Cambios en v1.3.0 (Actual)
@@ -698,6 +702,281 @@ class WelcomePrompt extends Prompt
Los prompts pueden embeber recursos y devolver secuencias de mensajes para guiar un LLM. Ve la documentación oficial para ejemplos avanzados y mejores prácticas.
+### Trabajando con Notificaciones
+
+Las notificaciones son mensajes fire-and-forget de clientes MCP que siempre devuelven HTTP 202 Accepted sin cuerpo de respuesta. Son perfectas para logging, seguimiento de progreso, manejo de eventos y activación de procesos en segundo plano sin bloquear al cliente.
+
+#### Creando Manejadores de Notificaciones
+
+**Uso básico del comando:**
+
+```bash
+php artisan make:mcp-notification ProgressHandler --method=notifications/progress
+```
+
+**Características avanzadas del comando:**
+
+```bash
+# Modo interactivo - solicita método si no se especifica
+php artisan make:mcp-notification MyHandler
+
+# Manejo automático de prefijo de método
+php artisan make:mcp-notification StatusHandler --method=status # se convierte en notifications/status
+
+# Normalización de nombre de clase
+php artisan make:mcp-notification "user activity" # se convierte en UserActivityHandler
+```
+
+El comando proporciona:
+- **Solicitud interactiva de método** cuando no se especifica `--method`
+- **Guía de registro automático** con código listo para copiar y pegar
+- **Ejemplos de prueba incorporados** con comandos curl
+- **Instrucciones de uso completas** y casos de uso comunes
+
+#### Arquitectura de Manejador de Notificaciones
+
+Cada manejador de notificaciones debe implementar la clase abstracta `NotificationHandler`:
+
+```php
+abstract class NotificationHandler
+{
+ // Requerido: Tipo de mensaje (usualmente ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // Requerido: El método de notificación a manejar
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // Requerido: Ejecutar la lógica de notificación
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**Componentes arquitectónicos clave:**
+
+- **`MESSAGE_TYPE`**: Usualmente `ProcessMessageType::HTTP` para notificaciones estándar
+- **`HANDLE_METHOD`**: El método JSON-RPC que procesa este manejador (debe comenzar con `notifications/`)
+- **`execute()`**: Contiene tu lógica de notificación - devuelve void (no se envía respuesta)
+- **Validación del constructor**: Valida automáticamente que las constantes requeridas estén definidas
+
+#### Manejadores de Notificaciones Incorporados
+
+El paquete incluye cuatro manejadores pre-construidos para escenarios MCP comunes:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **Propósito**: Procesa confirmaciones de inicialización del cliente después de handshake exitoso
+- **Parámetros**: Información y capacidades del cliente
+- **Uso**: Seguimiento de sesiones, logging de cliente, eventos de inicialización
+
+**2. ProgressHandler (`notifications/progress`)**
+- **Propósito**: Maneja actualizaciones de progreso para operaciones de larga duración
+- **Parámetros**:
+ - `progressToken` (string): Identificador único para la operación
+ - `progress` (number): Valor de progreso actual
+ - `total` (number, opcional): Valor total de progreso para cálculo de porcentaje
+- **Uso**: Seguimiento de progreso en tiempo real, monitoreo de cargas, finalización de tareas
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **Propósito**: Procesa notificaciones de cancelación de solicitudes
+- **Parámetros**:
+ - `requestId` (string): ID de la solicitud a cancelar
+ - `reason` (string, opcional): Razón de cancelación
+- **Uso**: Terminación de trabajos en segundo plano, limpieza de recursos, aborto de operaciones
+
+**4. MessageHandler (`notifications/message`)**
+- **Propósito**: Maneja mensajes generales de logging y comunicación
+- **Parámetros**:
+ - `level` (string): Nivel de log (info, warning, error, debug)
+ - `message` (string): El contenido del mensaje
+ - `logger` (string, opcional): Nombre del logger
+- **Uso**: Logging del lado del cliente, depuración, comunicación general
+
+#### Ejemplos de Manejadores para Escenarios Comunes
+
+```php
+// Seguimiento de progreso de carga de archivos
+class UploadProgressHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
+
+ public function execute(?array $params = null): void
+ {
+ $token = $params['progressToken'] ?? null;
+ $progress = $params['progress'] ?? 0;
+ $total = $params['total'] ?? 100;
+
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // Transmitir actualización en tiempo real
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
+ }
+}
+
+// Actividad de usuario y logging de auditoría
+class UserActivityHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/user_activity';
+
+ public function execute(?array $params = null): void
+ {
+ UserActivity::create([
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
+ 'ip_address' => request()->ip(),
+ 'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
+ ]);
+
+ // Activar alertas de seguridad para acciones sensibles
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
+ }
+}
+
+// Activación de tareas en segundo plano
+class TaskTriggerHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
+
+ public function execute(?array $params = null): void
+ {
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
+ }
+}
+```
+
+#### Registrando Manejadores de Notificaciones
+
+**En tu proveedor de servicios:**
+
+```php
+// En AppServiceProvider o proveedor de servicios MCP dedicado
+public function boot()
+{
+ $server = app(MCPServer::class);
+
+ // Registrar manejadores incorporados (opcional - se registran por defecto)
+ $server->registerNotificationHandler(new InitializedHandler());
+ $server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // Registrar manejadores personalizados
+ $server->registerNotificationHandler(new UploadProgressHandler());
+ $server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### Probando Notificaciones
+
+**Usando curl para probar manejadores de notificaciones:**
+
+```bash
+# Probar notificación de progreso
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# Esperado: HTTP 202 con cuerpo vacío
+
+# Probar notificación de actividad de usuario
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# Esperado: HTTP 202 con cuerpo vacío
+
+# Probar notificación de cancelación
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# Esperado: HTTP 202 con cuerpo vacío
+```
+
+**Notas importantes de prueba:**
+- Las notificaciones devuelven **HTTP 202** (nunca 200)
+- El cuerpo de respuesta está **siempre vacío**
+- No se envía mensaje de respuesta JSON-RPC
+- Verificar logs del servidor para confirmar procesamiento de notificaciones
+
+#### Manejo de Errores y Validación
+
+**Patrones de validación comunes:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // Validar parámetros requeridos
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // No lances excepción - las notificaciones deben ser tolerantes a fallos
+ }
+
+ // Validar tipos de parámetros
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // Extracción segura de parámetros con valores por defecto
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // Procesar notificación...
+}
+```
+
+**Mejores prácticas de manejo de errores:**
+- **Registrar errores** en lugar de lanzar excepciones
+- **Usar programación defensiva** con verificaciones null y valores por defecto
+- **Fallar elegantemente** - no romper el flujo de trabajo del cliente
+- **Validar entradas** pero continuar procesando cuando sea posible
+- **Monitorear notificaciones** a través de logging y métricas
+
### Probando Herramientas MCP
El paquete incluye un comando especial para probar tus herramientas MCP sin necesidad de un cliente MCP real:
diff --git a/README.ko.md b/README.ko.md
index 0a34e08..e4c9869 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -26,6 +26,10 @@
Español
+
+
+
+
## ⚠️ 버전 정보 및 주요 변경사항
### v1.3.0 변경사항 (현재 버전)
@@ -688,6 +692,280 @@ class WelcomePrompt extends Prompt
프롬프트는 리소스를 포함하고 LLM을 안내하는 메시지 시퀀스를 반환할 수 있습니다. 고급 예시와 모범 사례는 공식 문서를 참조하세요.
+### 알림 작업
+
+알림은 MCP 클라이언트로부터의 fire-and-forget 메시지로, 항상 응답 본문 없이 HTTP 202 Accepted를 반환합니다. 클라이언트를 차단하지 않고 로깅, 진행 상황 추적, 이벤트 처리, 백그라운드 프로세스 트리거에 완벽합니다.
+
+#### 알림 핸들러 생성
+
+**기본 명령어 사용법:**
+
+```bash
+php artisan make:mcp-notification ProgressHandler --method=notifications/progress
+```
+
+**고급 명령어 기능:**
+
+```bash
+# 대화형 모드 - 메서드가 지정되지 않으면 메서드를 묻습니다
+php artisan make:mcp-notification MyHandler
+
+# 자동 메서드 접두사 처리
+php artisan make:mcp-notification StatusHandler --method=status # notifications/status가 됩니다
+
+# 클래스 이름 정규화
+php artisan make:mcp-notification "user activity" # UserActivityHandler가 됩니다
+```
+
+이 명령어는 다음을 제공합니다:
+- `--method`가 지정되지 않았을 때 **대화형 메서드 프롬프트**
+- 복사-붙여넣기가 가능한 코드가 포함된 **자동 등록 가이드**
+- curl 명령어가 포함된 **내장 테스트 예시**
+- **포괄적인 사용 지침**과 일반적인 사용 사례
+
+#### 알림 핸들러 아키텍처
+
+각 알림 핸들러는 `NotificationHandler` 추상 클래스를 구현해야 합니다:
+
+```php
+abstract class NotificationHandler
+{
+ // 필수: 메시지 유형 (일반적으로 ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // 필수: 처리할 알림 메서드
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // 필수: 알림 로직 실행
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**주요 아키텍처 구성 요소:**
+
+- **`MESSAGE_TYPE`**: 표준 알림의 경우 일반적으로 `ProcessMessageType::HTTP`
+- **`HANDLE_METHOD`**: 이 핸들러가 처리하는 JSON-RPC 메서드 (`notifications/`로 시작해야 함)
+- **`execute()`**: 알림 로직 포함 - void 반환 (응답 전송 안 함)
+- **생성자 검증**: 필수 상수가 정의되었는지 자동으로 검증
+
+#### 내장 알림 핸들러
+
+패키지에는 일반적인 MCP 시나리오를 위한 4개의 사전 구축된 핸들러가 포함되어 있습니다:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **목적**: 성공적인 핸드셰이크 후 클라이언트 초기화 확인 처리
+- **매개변수**: 클라이언트 정보 및 기능
+- **사용법**: 세션 추적, 클라이언트 로깅, 초기화 이벤트
+
+**2. ProgressHandler (`notifications/progress`)**
+- **목적**: 장시간 실행되는 작업의 진행 상황 업데이트 처리
+- **매개변수**:
+ - `progressToken` (string): 작업의 고유 식별자
+ - `progress` (number): 현재 진행 값
+ - `total` (number, 선택): 백분율 계산을 위한 총 진행 값
+- **사용법**: 실시간 진행 상황 추적, 업로드 모니터링, 작업 완료
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **목적**: 요청 취소 알림 처리
+- **매개변수**:
+ - `requestId` (string): 취소할 요청의 ID
+ - `reason` (string, 선택): 취소 이유
+- **사용법**: 백그라운드 작업 종료, 리소스 정리, 작업 중단
+
+**4. MessageHandler (`notifications/message`)**
+- **목적**: 일반 로깅 및 통신 메시지 처리
+- **매개변수**:
+ - `level` (string): 로그 레벨 (info, warning, error, debug)
+ - `message` (string): 메시지 내용
+ - `logger` (string, 선택): 로거 이름
+- **사용법**: 클라이언트 측 로깅, 디버깅, 일반 통신
+
+#### 일반적인 시나리오를 위한 핸들러 예시
+
+```php
+// 파일 업로드 진행 상황 추적
+class UploadProgressHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
+
+ public function execute(?array $params = null): void
+ {
+ $token = $params['progressToken'] ?? null;
+ $progress = $params['progress'] ?? 0;
+ $total = $params['total'] ?? 100;
+
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // 실시간 업데이트 브로드캐스트
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
+ }
+}
+
+// 사용자 활동 및 감사 로깅
+class UserActivityHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/user_activity';
+
+ public function execute(?array $params = null): void
+ {
+ UserActivity::create([
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
+ 'ip_address' => request()->ip(),
+ 'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
+ ]);
+
+ // 민감한 작업에 대한 보안 알림 트리거
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
+ }
+}
+
+// 백그라운드 작업 트리거
+class TaskTriggerHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
+
+ public function execute(?array $params = null): void
+ {
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
+ }
+}
+```
+
+#### 알림 핸들러 등록
+
+**서비스 제공자에서:**
+
+```php
+// AppServiceProvider 또는 전용 MCP 서비스 제공자에서
+public function boot()
+{
+ $server = app(MCPServer::class);
+
+ // 내장 핸들러 등록 (선택사항 - 기본적으로 등록됨)
+ $server->registerNotificationHandler(new InitializedHandler());
+ $server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // 사용자 정의 핸들러 등록
+ $server->registerNotificationHandler(new UploadProgressHandler());
+ $server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### 알림 테스트
+
+**curl을 사용한 알림 핸들러 테스트:**
+
+```bash
+# 진행 상황 알림 테스트
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# 예상: 빈 본문으로 HTTP 202
+
+# 사용자 활동 알림 테스트
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# 예상: 빈 본문으로 HTTP 202
+
+# 취소 알림 테스트
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# 예상: 빈 본문으로 HTTP 202
+```
+
+**주요 테스트 참고사항:**
+- 알림은 **HTTP 202**를 반환 (200은 절대 안 함)
+- 응답 본문은 **항상 비어 있음**
+- JSON-RPC 응답 메시지가 전송되지 않음
+- 알림 처리 확인을 위해 서버 로그 확인
+
+#### 오류 처리 및 검증
+
+**일반적인 검증 패턴:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // 필수 매개변수 검증
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // 예외를 던지지 마세요 - 알림은 내결함성이 있어야 합니다
+ }
+
+ // 매개변수 유형 검증
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // 기본값으로 안전한 매개변수 추출
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // 알림 처리...
+}
+```
+
+**오류 처리 모범 사례:**
+- 예외를 던지는 대신 **오류 로깅**
+- null 체크와 기본값으로 **방어적 프로그래밍** 사용
+- **우아하게 실패** - 클라이언트 워크플로를 깨뜨리지 마세요
+- **입력 검증**하되 가능하면 처리 계속
+- 로깅과 메트릭을 통한 **알림 모니터링**
### MCP 도구 테스트
diff --git a/README.md b/README.md
index 1540322..a36b877 100644
--- a/README.md
+++ b/README.md
@@ -704,21 +704,100 @@ Prompts can embed resources and return sequences of messages to guide an LLM. Se
### Working with Notifications
-Notifications are one-way messages from MCP clients that return HTTP 202 (no response). Use them for logging, progress updates, and event handling.
+Notifications are fire-and-forget messages from MCP clients that always return HTTP 202 Accepted with no response body. They're perfect for logging, progress tracking, event handling, and triggering background processes without blocking the client.
-**Create a notification handler:**
+#### Creating Notification Handlers
+
+**Basic command usage:**
```bash
php artisan make:mcp-notification ProgressHandler --method=notifications/progress
```
-**Example handlers for common scenarios:**
+**Advanced command features:**
+
+```bash
+# Interactive mode - prompts for method if not specified
+php artisan make:mcp-notification MyHandler
+
+# Automatic method prefix handling
+php artisan make:mcp-notification StatusHandler --method=status # becomes notifications/status
+
+# Class name normalization
+php artisan make:mcp-notification "user activity" # becomes UserActivityHandler
+```
+
+The command provides:
+- **Interactive method prompting** when `--method` is not specified
+- **Automatic registration guidance** with copy-paste ready code
+- **Built-in testing examples** with curl commands
+- **Comprehensive usage instructions** and common use cases
+
+#### Notification Handler Architecture
+
+Each notification handler must implement the `NotificationHandler` abstract class:
+
+```php
+abstract class NotificationHandler
+{
+ // Required: Message type (usually ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // Required: The notification method to handle
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // Required: Execute the notification logic
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**Key architectural components:**
+
+- **`MESSAGE_TYPE`**: Usually `ProcessMessageType::HTTP` for standard notifications
+- **`HANDLE_METHOD`**: The JSON-RPC method this handler processes (must start with `notifications/`)
+- **`execute()`**: Contains your notification logic - returns void (no response sent)
+- **Constructor validation**: Automatically validates required constants are defined
+
+#### Built-in Notification Handlers
+
+The package includes four pre-built handlers for common MCP scenarios:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **Purpose**: Processes client initialization acknowledgments after successful handshake
+- **Parameters**: Client information and capabilities
+- **Usage**: Session tracking, client logging, initialization events
+
+**2. ProgressHandler (`notifications/progress`)**
+- **Purpose**: Handles progress updates for long-running operations
+- **Parameters**:
+ - `progressToken` (string): Unique identifier for the operation
+ - `progress` (number): Current progress value
+ - `total` (number, optional): Total progress value for percentage calculation
+- **Usage**: Real-time progress tracking, upload monitoring, task completion
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **Purpose**: Processes request cancellation notifications
+- **Parameters**:
+ - `requestId` (string): ID of the request to cancel
+ - `reason` (string, optional): Cancellation reason
+- **Usage**: Background job termination, resource cleanup, operation abortion
+
+**4. MessageHandler (`notifications/message`)**
+- **Purpose**: Handles general logging and communication messages
+- **Parameters**:
+ - `level` (string): Log level (info, warning, error, debug)
+ - `message` (string): The message content
+ - `logger` (string, optional): Logger name
+- **Usage**: Client-side logging, debugging, general communication
+
+#### Example Handlers for Common Scenarios
```php
-// Progress tracking for file uploads
-class ProgressHandler extends NotificationHandler
+// File upload progress tracking
+class UploadProgressHandler extends NotificationHandler
{
- protected const HANDLE_METHOD = 'notifications/progress';
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
public function execute(?array $params = null): void
{
@@ -726,61 +805,177 @@ class ProgressHandler extends NotificationHandler
$progress = $params['progress'] ?? 0;
$total = $params['total'] ?? 100;
- // Store in cache for real-time updates
- Cache::put("upload_progress_{$token}", [
- 'progress' => $progress,
- 'total' => $total,
- 'percentage' => round(($progress / $total) * 100, 2)
- ], 300);
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // Broadcast real-time update
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
}
}
-// User activity logging
+// User activity and audit logging
class UserActivityHandler extends NotificationHandler
{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
protected const HANDLE_METHOD = 'notifications/user_activity';
public function execute(?array $params = null): void
{
UserActivity::create([
- 'user_id' => $params['userId'],
- 'action' => $params['action'],
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
'ip_address' => request()->ip(),
'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
]);
+
+ // Trigger security alerts for sensitive actions
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
}
}
-// Task cancellation
-class CancelledHandler extends NotificationHandler
+// Background task triggering
+class TaskTriggerHandler extends NotificationHandler
{
- protected const HANDLE_METHOD = 'notifications/cancelled';
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
public function execute(?array $params = null): void
{
- $requestId = $params['requestId'] ?? null;
- if ($requestId) {
- // Stop background job
- Queue::deleteReserved('default', $requestId);
- \Log::info("Task {$requestId} cancelled by client");
- }
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
}
}
```
-**Register handlers in your service provider:**
+#### Registering Notification Handlers
+
+**In your service provider:**
```php
// In AppServiceProvider or dedicated MCP service provider
public function boot()
{
$server = app(MCPServer::class);
+
+ // Register built-in handlers (optional - they're registered by default)
+ $server->registerNotificationHandler(new InitializedHandler());
$server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // Register custom handlers
+ $server->registerNotificationHandler(new UploadProgressHandler());
$server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### Testing Notifications
+
+**Using curl to test notification handlers:**
+
+```bash
+# Test progress notification
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# Expected: HTTP 202 with empty body
+
+# Test user activity notification
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# Expected: HTTP 202 with empty body
+
+# Test cancellation notification
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# Expected: HTTP 202 with empty body
+```
+
+**Key testing notes:**
+- Notifications return **HTTP 202** (never 200)
+- Response body is **always empty**
+- No JSON-RPC response message is sent
+- Check server logs to verify notification processing
+
+#### Error Handling and Validation
+
+**Common validation patterns:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // Validate required parameters
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // Don't throw - notifications should be fault-tolerant
+ }
+
+ // Validate parameter types
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // Safe parameter extraction with defaults
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // Process notification...
}
```
-**Built-in handlers:** `notifications/initialized`, `notifications/progress`, `notifications/cancelled`, `notifications/message`
+**Error handling best practices:**
+- **Log errors** instead of throwing exceptions
+- **Use defensive programming** with null checks and defaults
+- **Fail gracefully** - don't break the client's workflow
+- **Validate inputs** but continue processing when possible
+- **Monitor notifications** through logging and metrics
### Testing MCP Tools
diff --git a/README.pl.md b/README.pl.md
index 31c16e9..3c3840d 100644
--- a/README.pl.md
+++ b/README.pl.md
@@ -26,6 +26,10 @@
Español
+
+
+
+
## ⚠️ Informacje o wersji i zmiany łamiące kompatybilność
### Zmiany w v1.3.0 (Aktualna)
@@ -680,6 +684,281 @@ class WelcomePrompt extends Prompt
Prompty mogą osadzać zasoby i zwracać sekwencje wiadomości do prowadzenia LLM. Zobacz oficjalną dokumentację dla zaawansowanych przykładów i najlepszych praktyk.
+### Praca z powiadomieniami
+
+Powiadomienia to wiadomości typu fire-and-forget od klientów MCP, które zawsze zwracają HTTP 202 Accepted bez treści odpowiedzi. Są idealne do logowania, śledzenia postępu, obsługi zdarzeń i wyzwalania procesów w tle bez blokowania klienta.
+
+#### Tworzenie obsługi powiadomień
+
+**Podstawowe użycie komendy:**
+
+```bash
+php artisan make:mcp-notification ProgressHandler --method=notifications/progress
+```
+
+**Zaawansowane funkcje komendy:**
+
+```bash
+# Tryb interaktywny - pyta o metodę jeśli nie została określona
+php artisan make:mcp-notification MyHandler
+
+# Automatyczne obsługiwanie prefiksu metody
+php artisan make:mcp-notification StatusHandler --method=status # staje się notifications/status
+
+# Normalizacja nazwy klasy
+php artisan make:mcp-notification "user activity" # staje się UserActivityHandler
+```
+
+Komenda zapewnia:
+- **Interaktywne pytanie o metodę** gdy `--method` nie jest określony
+- **Automatyczny przewodnik rejestracji** z gotowym do skopiowania kodem
+- **Wbudowane przykłady testów** z komendami curl
+- **Kompleksowe instrukcje użycia** i powszechne przypadki użycia
+
+#### Architektura obsługi powiadomień
+
+Każda obsługa powiadomień musi implementować abstrakcyjną klasę `NotificationHandler`:
+
+```php
+abstract class NotificationHandler
+{
+ // Wymagane: Typ wiadomości (zwykle ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // Wymagane: Metoda powiadomienia do obsługi
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // Wymagane: Wykonanie logiki powiadomienia
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**Kluczowe komponenty architektoniczne:**
+
+- **`MESSAGE_TYPE`**: Zwykle `ProcessMessageType::HTTP` dla standardowych powiadomień
+- **`HANDLE_METHOD`**: Metoda JSON-RPC, którą przetwarza ta obsługa (musi zaczynać się od `notifications/`)
+- **`execute()`**: Zawiera twoją logikę powiadomień - zwraca void (nie wysyła odpowiedzi)
+- **Walidacja konstruktora**: Automatycznie waliduje, czy wymagane stałe są zdefiniowane
+
+#### Wbudowane obsługi powiadomień
+
+Pakiet zawiera cztery prebudowane obsługi dla powszechnych scenariuszy MCP:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **Cel**: Przetwarza potwierdzenia inicjalizacji klienta po udanym handshake
+- **Parametry**: Informacje o kliencie i możliwości
+- **Użycie**: Śledzenie sesji, logowanie klienta, zdarzenia inicjalizacji
+
+**2. ProgressHandler (`notifications/progress`)**
+- **Cel**: Obsługuje aktualizacje postępu dla długotrwałych operacji
+- **Parametry**:
+ - `progressToken` (string): Unikalny identyfikator operacji
+ - `progress` (number): Bieżąca wartość postępu
+ - `total` (number, opcjonalnie): Całkowita wartość postępu do obliczenia procentu
+- **Użycie**: Śledzenie postępu w czasie rzeczywistym, monitorowanie uploadów, ukończenie zadań
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **Cel**: Przetwarza powiadomienia o anulowaniu żądań
+- **Parametry**:
+ - `requestId` (string): ID żądania do anulowania
+ - `reason` (string, opcjonalnie): Powód anulowania
+- **Użycie**: Zakończenie zadań w tle, czyszczenie zasobów, przerywanie operacji
+
+**4. MessageHandler (`notifications/message`)**
+- **Cel**: Obsługuje ogólne wiadomości logowania i komunikacji
+- **Parametry**:
+ - `level` (string): Poziom loga (info, warning, error, debug)
+ - `message` (string): Treść wiadomości
+ - `logger` (string, opcjonalnie): Nazwa loggera
+- **Użycie**: Logowanie po stronie klienta, debugowanie, ogólna komunikacja
+
+#### Przykłady obsługi dla powszechnych scenariuszy
+
+```php
+// Śledzenie postępu uploadu plików
+class UploadProgressHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
+
+ public function execute(?array $params = null): void
+ {
+ $token = $params['progressToken'] ?? null;
+ $progress = $params['progress'] ?? 0;
+ $total = $params['total'] ?? 100;
+
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // Transmituj aktualizację w czasie rzeczywistym
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
+ }
+}
+
+// Aktywność użytkownika i logowanie audytu
+class UserActivityHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/user_activity';
+
+ public function execute(?array $params = null): void
+ {
+ UserActivity::create([
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
+ 'ip_address' => request()->ip(),
+ 'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
+ ]);
+
+ // Wyzwól alerty bezpieczeństwa dla wrażliwych działań
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
+ }
+}
+
+// Wyzwalanie zadań w tle
+class TaskTriggerHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
+
+ public function execute(?array $params = null): void
+ {
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
+ }
+}
+```
+
+#### Rejestrowanie obsługi powiadomień
+
+**W twoim dostawcy usług:**
+
+```php
+// W AppServiceProvider lub dedykowanym dostawcy usług MCP
+public function boot()
+{
+ $server = app(MCPServer::class);
+
+ // Zarejestruj wbudowane obsługi (opcjonalnie - są rejestrowane domyślnie)
+ $server->registerNotificationHandler(new InitializedHandler());
+ $server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // Zarejestruj niestandardowe obsługi
+ $server->registerNotificationHandler(new UploadProgressHandler());
+ $server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### Testowanie powiadomień
+
+**Używając curl do testowania obsługi powiadomień:**
+
+```bash
+# Testuj powiadomienie o postępie
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# Oczekiwane: HTTP 202 z pustą treścią
+
+# Testuj powiadomienie o aktywności użytkownika
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# Oczekiwane: HTTP 202 z pustą treścią
+
+# Testuj powiadomienie o anulowaniu
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# Oczekiwane: HTTP 202 z pustą treścią
+```
+
+**Kluczowe uwagi dotyczące testowania:**
+- Powiadomienia zwracają **HTTP 202** (nigdy 200)
+- Treść odpowiedzi jest **zawsze pusta**
+- Nie jest wysyłana wiadomość odpowiedzi JSON-RPC
+- Sprawdź logi serwera aby zweryfikować przetwarzanie powiadomień
+
+#### Obsługa błędów i walidacja
+
+**Powszechne wzorce walidacji:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // Waliduj wymagane parametry
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // Nie rzucaj wyjątkiem - powiadomienia powinny być odporne na błędy
+ }
+
+ // Waliduj typy parametrów
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // Bezpieczna ekstrakcja parametrów z domyślnymi wartościami
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // Przetwarzaj powiadomienie...
+}
+```
+
+**Najlepsze praktyki obsługi błędów:**
+- **Loguj błędy** zamiast rzucać wyjątkami
+- **Używaj programowania defensywnego** ze sprawdzaniem null i domyślnymi wartościami
+- **Graceful failure** - nie psuj przepływu pracy klienta
+- **Waliduj wejścia** ale kontynuuj przetwarzanie gdy to możliwe
+- **Monitoruj powiadomienia** poprzez logowanie i metryki
+
### Testowanie narzędzi MCP
Pakiet zawiera specjalną komendę do testowania twoich narzędzi MCP bez potrzeby prawdziwego klienta MCP:
diff --git a/README.pt-BR.md b/README.pt-BR.md
index e766930..d5bb4b9 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -26,6 +26,10 @@
Español
+
+
+
+
## ⚠️ Informações de Versão & Breaking Changes
### Mudanças na v1.3.0 (Atual)
@@ -698,6 +702,280 @@ class WelcomePrompt extends Prompt
Prompts podem incorporar resources e retornar sequências de mensagens para guiar um LLM. Veja a documentação oficial para exemplos avançados e melhores práticas.
+### Trabalhando com Notificações
+
+Notificações são mensagens fire-and-forget de clientes MCP que sempre retornam HTTP 202 Accepted sem corpo de resposta. São perfeitas para logging, rastreamento de progresso, tratamento de eventos e acionamento de processos em segundo plano sem bloquear o cliente.
+
+#### Criando Manipuladores de Notificação
+
+**Uso básico do comando:**
+
+```bash
+php artisan make:mcp-notification ProgressHandler --method=notifications/progress
+```
+
+**Recursos avançados do comando:**
+
+```bash
+# Modo interativo - solicita método se não especificado
+php artisan make:mcp-notification MyHandler
+
+# Tratamento automático de prefixo de método
+php artisan make:mcp-notification StatusHandler --method=status # torna-se notifications/status
+
+# Normalização de nome de classe
+php artisan make:mcp-notification "user activity" # torna-se UserActivityHandler
+```
+
+O comando fornece:
+- **Solicitação interativa de método** quando `--method` não é especificado
+- **Guia de registro automático** com código pronto para copiar e colar
+- **Exemplos de teste integrados** com comandos curl
+- **Instruções de uso abrangentes** e casos de uso comuns
+
+#### Arquitetura do Manipulador de Notificação
+
+Cada manipulador de notificação deve implementar a classe abstrata `NotificationHandler`:
+
+```php
+abstract class NotificationHandler
+{
+ // Obrigatório: Tipo de mensagem (geralmente ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // Obrigatório: O método de notificação a ser tratado
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // Obrigatório: Executar a lógica de notificação
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**Componentes arquiteturais principais:**
+
+- **`MESSAGE_TYPE`**: Geralmente `ProcessMessageType::HTTP` para notificações padrão
+- **`HANDLE_METHOD`**: O método JSON-RPC que este manipulador processa (deve começar com `notifications/`)
+- **`execute()`**: Contém sua lógica de notificação - retorna void (nenhuma resposta enviada)
+- **Validação do construtor**: Valida automaticamente que as constantes obrigatórias estão definidas
+
+#### Manipuladores de Notificação Integrados
+
+O pacote inclui quatro manipuladores pré-construídos para cenários MCP comuns:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **Propósito**: Processa confirmações de inicialização do cliente após handshake bem-sucedido
+- **Parâmetros**: Informações e capacidades do cliente
+- **Uso**: Rastreamento de sessão, logging de cliente, eventos de inicialização
+
+**2. ProgressHandler (`notifications/progress`)**
+- **Propósito**: Trata atualizações de progresso para operações de longa duração
+- **Parâmetros**:
+ - `progressToken` (string): Identificador único para a operação
+ - `progress` (number): Valor de progresso atual
+ - `total` (number, opcional): Valor total de progresso para cálculo de porcentagem
+- **Uso**: Rastreamento de progresso em tempo real, monitoramento de uploads, conclusão de tarefas
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **Propósito**: Processa notificações de cancelamento de solicitação
+- **Parâmetros**:
+ - `requestId` (string): ID da solicitação a ser cancelada
+ - `reason` (string, opcional): Motivo do cancelamento
+- **Uso**: Terminação de jobs em segundo plano, limpeza de recursos, aborto de operações
+
+**4. MessageHandler (`notifications/message`)**
+- **Propósito**: Trata mensagens gerais de logging e comunicação
+- **Parâmetros**:
+ - `level` (string): Nível de log (info, warning, error, debug)
+ - `message` (string): O conteúdo da mensagem
+ - `logger` (string, opcional): Nome do logger
+- **Uso**: Logging do lado do cliente, depuração, comunicação geral
+
+#### Exemplos de Manipuladores para Cenários Comuns
+
+```php
+// Rastreamento de progresso de upload de arquivo
+class UploadProgressHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
+
+ public function execute(?array $params = null): void
+ {
+ $token = $params['progressToken'] ?? null;
+ $progress = $params['progress'] ?? 0;
+ $total = $params['total'] ?? 100;
+
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // Transmitir atualização em tempo real
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
+ }
+}
+
+// Atividade do usuário e logging de auditoria
+class UserActivityHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/user_activity';
+
+ public function execute(?array $params = null): void
+ {
+ UserActivity::create([
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
+ 'ip_address' => request()->ip(),
+ 'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
+ ]);
+
+ // Acionar alertas de segurança para ações sensíveis
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
+ }
+}
+
+// Acionamento de tarefas em segundo plano
+class TaskTriggerHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
+
+ public function execute(?array $params = null): void
+ {
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
+ }
+}
+```
+
+#### Registrando Manipuladores de Notificação
+
+**Em seu provedor de serviços:**
+
+```php
+// No AppServiceProvider ou provedor de serviços MCP dedicado
+public function boot()
+{
+ $server = app(MCPServer::class);
+
+ // Registrar manipuladores integrados (opcional - são registrados por padrão)
+ $server->registerNotificationHandler(new InitializedHandler());
+ $server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // Registrar manipuladores personalizados
+ $server->registerNotificationHandler(new UploadProgressHandler());
+ $server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### Testando Notificações
+
+**Usando curl para testar manipuladores de notificação:**
+
+```bash
+# Testar notificação de progresso
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# Esperado: HTTP 202 com corpo vazio
+
+# Testar notificação de atividade do usuário
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# Esperado: HTTP 202 com corpo vazio
+
+# Testar notificação de cancelamento
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# Esperado: HTTP 202 com corpo vazio
+```
+
+**Notas importantes sobre testes:**
+- Notificações retornam **HTTP 202** (nunca 200)
+- Corpo da resposta está **sempre vazio**
+- Nenhuma mensagem de resposta JSON-RPC é enviada
+- Verificar logs do servidor para confirmar processamento de notificações
+
+#### Tratamento de Erros e Validação
+
+**Padrões de validação comuns:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // Validar parâmetros obrigatórios
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // Não lance exceção - notificações devem ser tolerantes a falhas
+ }
+
+ // Validar tipos de parâmetros
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // Extração segura de parâmetros com valores padrão
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // Processar notificação...
+}
+```
+
+**Melhores práticas de tratamento de erros:**
+- **Registrar erros** em vez de lançar exceções
+- **Usar programação defensiva** com verificações null e valores padrão
+- **Falha elegante** - não quebrar o fluxo de trabalho do cliente
+- **Validar entradas** mas continuar processamento quando possível
+- **Monitorar notificações** através de logging e métricas
### Testando MCP Tools
diff --git a/README.ru.md b/README.ru.md
index 5908238..5765cf9 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -26,6 +26,10 @@
Español
+
+
+
+
## ⚠️ Информация о версиях и критические изменения
### Изменения в v1.3.0 (Текущая версия)
@@ -680,6 +684,281 @@ class WelcomePrompt extends Prompt
Промпты могут встраивать ресурсы и возвращать последовательности сообщений для направления LLM. См. официальную документацию для продвинутых примеров и лучших практик.
+### Работа с уведомлениями
+
+Уведомления - это fire-and-forget сообщения от MCP клиентов, которые всегда возвращают HTTP 202 Accepted без тела ответа. Они идеально подходят для логирования, отслеживания прогресса, обработки событий и запуска фоновых процессов без блокировки клиента.
+
+#### Создание обработчиков уведомлений
+
+**Базовое использование команды:**
+
+```bash
+php artisan make:mcp-notification ProgressHandler --method=notifications/progress
+```
+
+**Продвинутые возможности команды:**
+
+```bash
+# Интерактивный режим - запрашивает метод, если не указан
+php artisan make:mcp-notification MyHandler
+
+# Автоматическая обработка префикса метода
+php artisan make:mcp-notification StatusHandler --method=status # становится notifications/status
+
+# Нормализация имени класса
+php artisan make:mcp-notification "user activity" # становится UserActivityHandler
+```
+
+Команда предоставляет:
+- **Интерактивный запрос метода** когда `--method` не указан
+- **Автоматическое руководство по регистрации** с готовым для копирования кодом
+- **Встроенные примеры тестов** с curl командами
+- **Всеобъемлющие инструкции по использованию** и общие случаи использования
+
+#### Архитектура обработчика уведомлений
+
+Каждый обработчик уведомлений должен реализовывать абстрактный класс `NotificationHandler`:
+
+```php
+abstract class NotificationHandler
+{
+ // Обязательно: Тип сообщения (обычно ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // Обязательно: Метод уведомления для обработки
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // Обязательно: Выполнение логики уведомления
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**Ключевые архитектурные компоненты:**
+
+- **`MESSAGE_TYPE`**: Обычно `ProcessMessageType::HTTP` для стандартных уведомлений
+- **`HANDLE_METHOD`**: JSON-RPC метод, который обрабатывает этот обработчик (должен начинаться с `notifications/`)
+- **`execute()`**: Содержит вашу логику уведомлений - возвращает void (ответ не отправляется)
+- **Валидация конструктора**: Автоматически валидирует, что обязательные константы определены
+
+#### Встроенные обработчики уведомлений
+
+Пакет включает четыре предварительно созданных обработчика для общих MCP сценариев:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **Цель**: Обрабатывает подтверждения инициализации клиента после успешного handshake
+- **Параметры**: Информация о клиенте и возможности
+- **Использование**: Отслеживание сессий, логирование клиента, события инициализации
+
+**2. ProgressHandler (`notifications/progress`)**
+- **Цель**: Обрабатывает обновления прогресса для долгосрочных операций
+- **Параметры**:
+ - `progressToken` (string): Уникальный идентификатор операции
+ - `progress` (number): Текущее значение прогресса
+ - `total` (number, опционально): Общее значение прогресса для расчета процентов
+- **Использование**: Отслеживание прогресса в реальном времени, мониторинг загрузок, завершение задач
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **Цель**: Обрабатывает уведомления об отмене запросов
+- **Параметры**:
+ - `requestId` (string): ID запроса для отмены
+ - `reason` (string, опционально): Причина отмены
+- **Использование**: Завершение фоновых задач, очистка ресурсов, прерывание операций
+
+**4. MessageHandler (`notifications/message`)**
+- **Цель**: Обрабатывает общие сообщения логирования и коммуникации
+- **Параметры**:
+ - `level` (string): Уровень лога (info, warning, error, debug)
+ - `message` (string): Содержимое сообщения
+ - `logger` (string, опционально): Имя логгера
+- **Использование**: Логирование на стороне клиента, отладка, общая коммуникация
+
+#### Примеры обработчиков для общих сценариев
+
+```php
+// Отслеживание прогресса загрузки файлов
+class UploadProgressHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
+
+ public function execute(?array $params = null): void
+ {
+ $token = $params['progressToken'] ?? null;
+ $progress = $params['progress'] ?? 0;
+ $total = $params['total'] ?? 100;
+
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // Трансляция обновления в реальном времени
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
+ }
+}
+
+// Активность пользователя и логирование аудита
+class UserActivityHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/user_activity';
+
+ public function execute(?array $params = null): void
+ {
+ UserActivity::create([
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
+ 'ip_address' => request()->ip(),
+ 'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
+ ]);
+
+ // Запуск уведомлений о безопасности для чувствительных действий
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
+ }
+}
+
+// Запуск фоновых задач
+class TaskTriggerHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
+
+ public function execute(?array $params = null): void
+ {
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
+ }
+}
+```
+
+#### Регистрация обработчиков уведомлений
+
+**В вашем провайдере сервисов:**
+
+```php
+// В AppServiceProvider или выделенном MCP провайдере сервисов
+public function boot()
+{
+ $server = app(MCPServer::class);
+
+ // Регистрация встроенных обработчиков (опционально - регистрируются по умолчанию)
+ $server->registerNotificationHandler(new InitializedHandler());
+ $server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // Регистрация пользовательских обработчиков
+ $server->registerNotificationHandler(new UploadProgressHandler());
+ $server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### Тестирование уведомлений
+
+**Использование curl для тестирования обработчиков уведомлений:**
+
+```bash
+# Тестирование уведомления о прогрессе
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# Ожидается: HTTP 202 с пустым телом
+
+# Тестирование уведомления об активности пользователя
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# Ожидается: HTTP 202 с пустым телом
+
+# Тестирование уведомления об отмене
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# Ожидается: HTTP 202 с пустым телом
+```
+
+**Ключевые заметки о тестировании:**
+- Уведомления возвращают **HTTP 202** (никогда 200)
+- Тело ответа **всегда пустое**
+- JSON-RPC ответное сообщение не отправляется
+- Проверьте логи сервера для подтверждения обработки уведомлений
+
+#### Обработка ошибок и валидация
+
+**Общие паттерны валидации:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // Валидация обязательных параметров
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // Не бросайте исключение - уведомления должны быть отказоустойчивыми
+ }
+
+ // Валидация типов параметров
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // Безопасная экстракция параметров со значениями по умолчанию
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // Обработка уведомления...
+}
+```
+
+**Лучшие практики обработки ошибок:**
+- **Логировать ошибки** вместо выбрасывания исключений
+- **Использовать защитное программирование** с null проверками и значениями по умолчанию
+- **Изящное падение** - не ломать рабочий процесс клиента
+- **Валидировать входы** но продолжать обработку когда возможно
+- **Мониторить уведомления** через логирование и метрики
+
### Тестирование MCP инструментов
Пакет включает специальную команду для тестирования ваших MCP инструментов без необходимости в реальном MCP клиенте:
diff --git a/README.zh-CN.md b/README.zh-CN.md
index a5416f3..8dd6027 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -26,6 +26,10 @@
Español
+
+
+
+
## ⚠️ 版本信息与重大变更
### v1.3.0 变更(当前版本)
@@ -680,6 +684,280 @@ class WelcomePrompt extends Prompt
提示可以嵌入资源并返回消息序列来指导 LLM。有关高级示例和最佳实践,请参阅官方文档。
+### 使用通知
+
+通知是来自 MCP 客户端的 fire-and-forget 消息,它们总是返回 HTTP 202 Accepted 而没有响应正文。它们非常适合日志记录、进度跟踪、事件处理和触发后台进程,而不会阻塞客户端。
+
+#### 创建通知处理器
+
+**基本命令用法:**
+
+```bash
+php artisan make:mcp-notification ProgressHandler --method=notifications/progress
+```
+
+**高级命令功能:**
+
+```bash
+# 交互模式 - 如果未指定方法则提示输入
+php artisan make:mcp-notification MyHandler
+
+# 自动方法前缀处理
+php artisan make:mcp-notification StatusHandler --method=status # 变成 notifications/status
+
+# 类名标准化
+php artisan make:mcp-notification "user activity" # 变成 UserActivityHandler
+```
+
+该命令提供:
+- 当未指定 `--method` 时**交互式方法提示**
+- 带有复制粘贴就绪代码的**自动注册指南**
+- 带有 curl 命令的**内置测试示例**
+- **全面的使用说明**和常见用例
+
+#### 通知处理器架构
+
+每个通知处理器必须实现抽象类 `NotificationHandler`:
+
+```php
+abstract class NotificationHandler
+{
+ // 必需:消息类型(通常是 ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // 必需:要处理的通知方法
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // 必需:执行通知逻辑
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**关键架构组件:**
+
+- **`MESSAGE_TYPE`**:标准通知通常使用 `ProcessMessageType::HTTP`
+- **`HANDLE_METHOD`**:此处理器处理的 JSON-RPC 方法(必须以 `notifications/` 开头)
+- **`execute()`**:包含您的通知逻辑 - 返回 void(不发送响应)
+- **构造函数验证**:自动验证必需常量是否已定义
+
+#### 内置通知处理器
+
+包包含四个为常见 MCP 场景预构建的处理器:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **目的**:在成功握手后处理客户端初始化确认
+- **参数**:客户端信息和能力
+- **用法**:会话跟踪、客户端日志记录、初始化事件
+
+**2. ProgressHandler (`notifications/progress`)**
+- **目的**:处理长时间运行操作的进度更新
+- **参数**:
+ - `progressToken` (string):操作的唯一标识符
+ - `progress` (number):当前进度值
+ - `total` (number,可选):用于百分比计算的总进度值
+- **用法**:实时进度跟踪、上传监控、任务完成
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **目的**:处理请求取消通知
+- **参数**:
+ - `requestId` (string):要取消的请求 ID
+ - `reason` (string,可选):取消原因
+- **用法**:后台作业终止、资源清理、操作中止
+
+**4. MessageHandler (`notifications/message`)**
+- **目的**:处理一般日志记录和通信消息
+- **参数**:
+ - `level` (string):日志级别(info、warning、error、debug)
+ - `message` (string):消息内容
+ - `logger` (string,可选):记录器名称
+- **用法**:客户端日志记录、调试、一般通信
+
+#### 常见场景的处理器示例
+
+```php
+// 文件上传进度跟踪
+class UploadProgressHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
+
+ public function execute(?array $params = null): void
+ {
+ $token = $params['progressToken'] ?? null;
+ $progress = $params['progress'] ?? 0;
+ $total = $params['total'] ?? 100;
+
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // 广播实时更新
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
+ }
+}
+
+// 用户活动和审计日志记录
+class UserActivityHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/user_activity';
+
+ public function execute(?array $params = null): void
+ {
+ UserActivity::create([
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
+ 'ip_address' => request()->ip(),
+ 'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
+ ]);
+
+ // 为敏感操作触发安全警报
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
+ }
+}
+
+// 后台任务触发
+class TaskTriggerHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
+
+ public function execute(?array $params = null): void
+ {
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
+ }
+}
+```
+
+#### 注册通知处理器
+
+**在您的服务提供者中:**
+
+```php
+// 在 AppServiceProvider 或专用的 MCP 服务提供者中
+public function boot()
+{
+ $server = app(MCPServer::class);
+
+ // 注册内置处理器(可选 - 默认注册)
+ $server->registerNotificationHandler(new InitializedHandler());
+ $server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // 注册自定义处理器
+ $server->registerNotificationHandler(new UploadProgressHandler());
+ $server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### 测试通知
+
+**使用 curl 测试通知处理器:**
+
+```bash
+# 测试进度通知
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# 预期:HTTP 202 且正文为空
+
+# 测试用户活动通知
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# 预期:HTTP 202 且正文为空
+
+# 测试取消通知
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# 预期:HTTP 202 且正文为空
+```
+
+**重要测试注意事项:**
+- 通知返回 **HTTP 202**(从不返回 200)
+- 响应正文**总是空的**
+- 不发送 JSON-RPC 响应消息
+- 检查服务器日志以验证通知处理
+
+#### 错误处理和验证
+
+**常见验证模式:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // 验证必需参数
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // 不要抛出异常 - 通知应该容错
+ }
+
+ // 验证参数类型
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // 使用默认值安全提取参数
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // 处理通知...
+}
+```
+
+**错误处理最佳实践:**
+- **记录错误**而不是抛出异常
+- **使用防御性编程**,进行空值检查和默认值
+- **优雅失败** - 不要破坏客户端的工作流
+- **验证输入**但在可能时继续处理
+- 通过日志记录和指标**监控通知**
### 测试 MCP 工具
diff --git a/README.zh-TW.md b/README.zh-TW.md
index 94de04f..72d30d7 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -26,6 +26,10 @@
Español
+
+
+
+
## ⚠️ 版本資訊與重大變更
### v1.3.0 變更 (目前版本)
@@ -680,6 +684,281 @@ class WelcomePrompt extends Prompt
提示可以嵌入資源並回傳訊息序列來引導 LLM。請參閱官方文件以獲得進階範例和最佳實務。
+### 使用通知
+
+通知是來自 MCP 客戶端的 fire-and-forget 訊息,它們總是回傳 HTTP 202 Accepted 而沒有回應主體。它們非常適合記錄、進度追蹤、事件處理和觸發背景程序,而不會阻塞客戶端。
+
+#### 建立通知處理器
+
+**基本指令用法:**
+
+```bash
+php artisan make:mcp-notification ProgressHandler --method=notifications/progress
+```
+
+**進階指令功能:**
+
+```bash
+# 互動模式 - 如果未指定方法則提示輸入
+php artisan make:mcp-notification MyHandler
+
+# 自動方法前綴處理
+php artisan make:mcp-notification StatusHandler --method=status # 變成 notifications/status
+
+# 類別名稱標準化
+php artisan make:mcp-notification "user activity" # 變成 UserActivityHandler
+```
+
+該指令提供:
+- 當未指定 `--method` 時**互動式方法提示**
+- 帶有複製貼上就緒程式碼的**自動註冊指南**
+- 帶有 curl 指令的**內建測試範例**
+- **全面的使用說明**和常見用例
+
+#### 通知處理器架構
+
+每個通知處理器必須實作抽象類別 `NotificationHandler`:
+
+```php
+abstract class NotificationHandler
+{
+ // 必需:訊息類型(通常是 ProcessMessageType::HTTP)
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+
+ // 必需:要處理的通知方法
+ protected const HANDLE_METHOD = 'notifications/your_method';
+
+ // 必需:執行通知邏輯
+ abstract public function execute(?array $params = null): void;
+}
+```
+
+**關鍵架構組件:**
+
+- **`MESSAGE_TYPE`**:標準通知通常使用 `ProcessMessageType::HTTP`
+- **`HANDLE_METHOD`**:此處理器處理的 JSON-RPC 方法(必須以 `notifications/` 開頭)
+- **`execute()`**:包含您的通知邏輯 - 回傳 void(不發送回應)
+- **建構函式驗證**:自動驗證必需常數是否已定義
+
+#### 內建通知處理器
+
+套件包含四個為常見 MCP 場景預建的處理器:
+
+**1. InitializedHandler (`notifications/initialized`)**
+- **目的**:在成功握手後處理客戶端初始化確認
+- **參數**:客戶端資訊和能力
+- **用法**:會話追蹤、客戶端記錄、初始化事件
+
+**2. ProgressHandler (`notifications/progress`)**
+- **目的**:處理長時間執行操作的進度更新
+- **參數**:
+ - `progressToken` (string):操作的唯一識別符
+ - `progress` (number):目前進度值
+ - `total` (number,可選):用於百分比計算的總進度值
+- **用法**:即時進度追蹤、上傳監控、任務完成
+
+**3. CancelledHandler (`notifications/cancelled`)**
+- **目的**:處理請求取消通知
+- **參數**:
+ - `requestId` (string):要取消的請求 ID
+ - `reason` (string,可選):取消原因
+- **用法**:背景作業終止、資源清理、操作中止
+
+**4. MessageHandler (`notifications/message`)**
+- **目的**:處理一般記錄和通訊訊息
+- **參數**:
+ - `level` (string):記錄層級(info、warning、error、debug)
+ - `message` (string):訊息內容
+ - `logger` (string,可選):記錄器名稱
+- **用法**:客戶端記錄、除錯、一般通訊
+
+#### 常見場景的處理器範例
+
+```php
+// 檔案上傳進度追蹤
+class UploadProgressHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/upload_progress';
+
+ public function execute(?array $params = null): void
+ {
+ $token = $params['progressToken'] ?? null;
+ $progress = $params['progress'] ?? 0;
+ $total = $params['total'] ?? 100;
+
+ if ($token) {
+ Cache::put("upload_progress_{$token}", [
+ 'progress' => $progress,
+ 'total' => $total,
+ 'percentage' => $total ? round(($progress / $total) * 100, 2) : 0,
+ 'updated_at' => now()
+ ], 3600);
+
+ // 廣播即時更新
+ broadcast(new UploadProgressUpdated($token, $progress, $total));
+ }
+ }
+}
+
+// 使用者活動和稽核記錄
+class UserActivityHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/user_activity';
+
+ public function execute(?array $params = null): void
+ {
+ UserActivity::create([
+ 'user_id' => $params['userId'] ?? null,
+ 'action' => $params['action'] ?? 'unknown',
+ 'resource' => $params['resource'] ?? null,
+ 'ip_address' => request()->ip(),
+ 'user_agent' => request()->userAgent(),
+ 'metadata' => $params['metadata'] ?? [],
+ 'created_at' => now()
+ ]);
+
+ // 為敏感操作觸發安全警報
+ if (in_array($params['action'] ?? '', ['delete', 'export', 'admin_access'])) {
+ SecurityAlert::dispatch($params);
+ }
+ }
+}
+
+// 背景任務觸發
+class TaskTriggerHandler extends NotificationHandler
+{
+ protected const MESSAGE_TYPE = ProcessMessageType::HTTP;
+ protected const HANDLE_METHOD = 'notifications/trigger_task';
+
+ public function execute(?array $params = null): void
+ {
+ $taskType = $params['taskType'] ?? null;
+ $taskData = $params['data'] ?? [];
+
+ match ($taskType) {
+ 'send_email' => SendEmailJob::dispatch($taskData),
+ 'generate_report' => GenerateReportJob::dispatch($taskData),
+ 'sync_data' => DataSyncJob::dispatch($taskData),
+ 'cleanup' => CleanupJob::dispatch($taskData),
+ default => Log::warning("Unknown task type: {$taskType}")
+ };
+ }
+}
+```
+
+#### 註冊通知處理器
+
+**在您的服務提供者中:**
+
+```php
+// 在 AppServiceProvider 或專用的 MCP 服務提供者中
+public function boot()
+{
+ $server = app(MCPServer::class);
+
+ // 註冊內建處理器(可選 - 預設註冊)
+ $server->registerNotificationHandler(new InitializedHandler());
+ $server->registerNotificationHandler(new ProgressHandler());
+ $server->registerNotificationHandler(new CancelledHandler());
+ $server->registerNotificationHandler(new MessageHandler());
+
+ // 註冊自訂處理器
+ $server->registerNotificationHandler(new UploadProgressHandler());
+ $server->registerNotificationHandler(new UserActivityHandler());
+ $server->registerNotificationHandler(new TaskTriggerHandler());
+}
+```
+
+#### 測試通知
+
+**使用 curl 測試通知處理器:**
+
+```bash
+# 測試進度通知
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": "upload_123",
+ "progress": 75,
+ "total": 100
+ }
+ }'
+# 預期:HTTP 202 且主體為空
+
+# 測試使用者活動通知
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/user_activity",
+ "params": {
+ "userId": 123,
+ "action": "file_download",
+ "resource": "document.pdf"
+ }
+ }'
+# 預期:HTTP 202 且主體為空
+
+# 測試取消通知
+curl -X POST http://localhost:8000/mcp \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {
+ "requestId": "req_abc123",
+ "reason": "User requested cancellation"
+ }
+ }'
+# 預期:HTTP 202 且主體為空
+```
+
+**重要測試注意事項:**
+- 通知回傳 **HTTP 202**(從不回傳 200)
+- 回應主體**總是空的**
+- 不發送 JSON-RPC 回應訊息
+- 檢查伺服器記錄以驗證通知處理
+
+#### 錯誤處理和驗證
+
+**常見驗證模式:**
+
+```php
+public function execute(?array $params = null): void
+{
+ // 驗證必需參數
+ if (!isset($params['userId'])) {
+ Log::error('UserActivityHandler: Missing required userId parameter', $params);
+ return; // 不要拋出例外 - 通知應該容錯
+ }
+
+ // 驗證參數型別
+ if (!is_numeric($params['userId'])) {
+ Log::warning('UserActivityHandler: userId must be numeric', $params);
+ return;
+ }
+
+ // 使用預設值安全提取參數
+ $userId = (int) $params['userId'];
+ $action = $params['action'] ?? 'unknown';
+ $metadata = $params['metadata'] ?? [];
+
+ // 處理通知...
+}
+```
+
+**錯誤處理最佳實務:**
+- **記錄錯誤**而不是拋出例外
+- **使用防禦性程式設計**,進行空值檢查和預設值
+- **優雅失敗** - 不要破壞客戶端的工作流程
+- **驗證輸入**但在可能時繼續處理
+- 透過記錄和指標**監控通知**
+
### 測試 MCP 工具
套件包含一個特殊指令,用於測試你的 MCP 工具而無需真正的 MCP 客戶端: