UNPKG

@chinchillaenterprises/mcp-amplify

Version:

AWS Amplify MCP server with intelligent deployment automation, specialized logging suite, and recursive resource discovery

1,475 lines (1,266 loc) โ€ข 49.4 kB
# MCP-Amplify Server A Model Context Protocol (MCP) server for AWS Amplify deployment and management with GitHub integration. This server provides comprehensive tools for managing AWS Amplify applications, including **revolutionary recursive resource discovery**, DynamoDB operations, Lambda management, and **CloudWatch logs analysis**. ๐Ÿš€ **Version 1.8.8 - GIT HANDLING FIX**: Fixed bug where Create Next.js App tool would run git commands even when initGit was set to false! ## Recent Updates (Version 1.8.2 - 1.8.8) ### Git Handling Fix (v1.8.8) - **Fixed initGit parameter bug**: The tool now properly respects the `initGit: false` parameter - **No more git errors**: Won't try to run `git add -A` when not in a git repository or when git initialization is disabled - **Better edge case handling**: Works correctly in non-git directories when `initGit: false` ### Safer Error Handling (v1.8.7) - **Removed all automatic cleanup**: Failed operations now leave created files/directories intact - **Better user experience**: Users can review what was created and manually clean up if needed - **No risk of data loss**: Completely eliminates any possibility of accidental deletion ## Previous Updates ### Critical Safety Fix (v1.8.6) - **๐Ÿšจ FIXED DANGEROUS BUG**: The `amplify_create_nextjs_app` tool had a critical bug where it would delete the entire directory (including parent/current directories) on any error - **Added multiple safety checks**: - Never deletes current directory when using `useCurrentDirectory` or `projectName: "."` - Only cleans up directories created within the last 5 minutes - Validates paths to prevent parent directory operations - Blocks dangerous patterns like `..`, `/`, or home directory - **Error handling is now safe**: Failed operations leave directories intact rather than risk deleting user data ### Bug Fixes and Improvements - **Fixed keytar module import** (v1.8.3): Resolved dynamic import issues with the keytar credential storage module - **Fixed npm binary permissions** (v1.8.4): Added automatic chmod +x during build to ensure proper executable permissions - **Standardized bin path** (v1.8.5): Updated package.json to use `"./dist/index.js"` matching other MCP servers for consistency - **Improved build process**: Build script now ensures executable permissions are set correctly ### Installation Now Works Seamlessly ```bash # Simple installation - no special flags needed! claude mcp add amplify -s user -- npx @chinchillaenterprises/mcp-amplify ``` ## Version 1.8.0 Update - INTELLIGENT DEPLOYMENT AUTOMATION ๐Ÿค– **๐Ÿš€ BREAKTHROUGH: End-to-End Deployment Intelligence**: Complete overhaul of the deployment system that eliminates manual AWS CLI intervention and handles all edge cases! ### What's New in v1.8.0 **Revolutionary Smart Deployment Logic**: The `amplify_deploy_app` tool now automatically: 1. **Detects existing apps** for the repository and configures them properly 2. **Updates build specs** to Node 20+ with CDK bootstrap support 3. **Assigns IAM roles** automatically for CDK operations 4. **Triggers deployments** intelligently (only when needed) 5. **Handles all edge cases** that previously required manual intervention ### New Tools Added - **`amplify_check_app_exists`** - Detect existing Amplify apps by GitHub repository - **`amplify_update_build_spec`** - Update build configuration to Node 20+ defaults - **`amplify_setup_iam_role`** - Auto-assign IAM roles for CDK operations - **`amplify_trigger_deployment`** - Manual deployment triggering with validation ### Enhanced Default Build Spec (Node 20+ + CDK) ```yaml version: 1 backend: phases: preBuild: commands: - nvm use 20 build: commands: - npm ci --cache .npm --prefer-offline - npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID frontend: phases: preBuild: commands: - nvm use 20 - npm ci --cache .npm --prefer-offline build: commands: - env | grep -E '^NEXT_PUBLIC_' >> .env.production - env | grep -E '^AMPLIFY_' >> .env.production - npx ampx generate outputs --branch $AWS_BRANCH --app-id $AWS_APP_ID - npm run build artifacts: baseDirectory: .next files: - '**/*' cache: paths: - .next/cache/**/* - .npm/**/* - node_modules/**/* ``` ### Critical Issues Solved โœ… **App Creation vs. Deployment Gap** - Smart detection and handling of existing apps โœ… **Missing Build Configuration** - Automatic Node 20+ updates with CDK support โœ… **Missing IAM Role Assignment** - Auto-detection and assignment of AmplifySSRLoggingRole โœ… **No Deployment Triggering** - Intelligent deployment logic that works end-to-end **๐ŸŽฏ IMPACT**: No more manual AWS CLI commands needed. The MCP server now handles the complete deployment workflow automatically! ## Version 1.7.0 Update - COMPLETE SPECIALIZED LOGGING SUITE ๐ŸŽฏ **๐Ÿš€ NEW: Complete Service-Specific Logging Tools**: Added comprehensive logging tools for all major AWS services used in Amplify applications! ### What's New in v1.7.0 **Revolutionary Specialized Logging Approach**: Moved from generic CloudWatch logs to **service-specific logging tools** that provide precise control and better debugging experience: - **`amplify_get_lambda_logs`** โœ… - Specialized Lambda function logging with function-specific filtering - **`amplify_get_appsync_logs`** โœ… - GraphQL resolver logging with operation type filtering - **`amplify_get_cognito_logs`** โœ… - Authentication event logging with security analysis - **`amplify_get_apigateway_logs`** โœ… - REST API request logging with endpoint and method filtering ### Key Benefits - **Service-Specific Parameters**: Each tool has parameters tailored to its service (resolver types, HTTP methods, auth events) - **Intelligent Filtering**: Filter by log level, time range, specific operations, and service-specific criteria - **Enhanced Discovery**: Uses recursive CloudFormation traversal to find ALL service resources - **Performance Analysis**: Built-in metrics, slow query detection, and performance insights - **Better Error Handling**: Graceful handling of missing log groups and services - **AI-Friendly Responses**: Structured JSON output optimized for AI analysis and debugging ### Before vs After - **Before**: Generic `amplify_get_recent_logs` with limited filtering - **After**: 4 specialized tools with service-specific parameters and intelligent analysis **๐ŸŽฏ IMPACT**: Perfect debugging experience - get exactly the logs you need with the right level of detail for each AWS service! ## Version 1.6.1 Update - CRITICAL RECURSIVE DISCOVERY BUG FIX ๐Ÿ”ง **๐Ÿ› THE BUG**: The `amplify_discover_resources` tool was only finding 2 infrastructure Lambda functions instead of 16+ application functions. **๐Ÿ” ROOT CAUSE DISCOVERED**: The recursive discovery logic had a critical flaw in the CloudFormation stack status check: - **Problem**: Code only recursed into nested stacks with status `CREATE_COMPLETE` - **Reality**: Updated Amplify stacks have status `UPDATE_COMPLETE` - **Result**: Recursion never happened, only top-level infrastructure functions were found **โšก THE FIX**: ```typescript // BEFORE (Broken) if (resource.ResourceStatus === 'CREATE_COMPLETE') { // AFTER (Fixed) if (resource.ResourceStatus === 'CREATE_COMPLETE' || resource.ResourceStatus === 'UPDATE_COMPLETE') { ``` **๐Ÿ“Š VERIFICATION RESULTS**: - **Before Fix**: 2 Lambda functions (only infrastructure) - **After Fix**: 13+ Lambda functions including: - `stripepaymentlambda` โ†’ Payment processing - `stripevippaymentlambda` โ†’ VIP payment processing - `stripewebhooklambda` โ†’ Webhook handling - `paymentintentnotificationlambda` โ†’ Payment notifications - `processapplicationlambda` โ†’ Application processing - `postconfirmationlambda` โ†’ Cognito post-signup trigger **๐ŸŽฏ IMPACT**: The tool now works as designed - finding ALL application resources through proper recursive nested stack traversal! ## Version 1.5.0 Update - RECURSIVE NESTED STACK DISCOVERY ๐ŸŽฏ **๐Ÿš€ BREAKTHROUGH: Recursive Nested Stack Resource Discovery**: Solved the #1 problem with Amplify resource discovery! ### The Problem We Solved Amplify Gen 2 uses **deeply nested CloudFormation stacks** (3-4 levels deep). Previous approaches only looked at the top-level stack, which contains only Amplify infrastructure functions. The actual application resources (Lambda functions, DynamoDB tables, AppSync APIs, Cognito pools) are buried in nested child stacks. ### The Revolutionary Solution **Recursive CloudFormation Stack Traversal**: 1. **Golden Key Extraction**: Get CloudFormation stack ARN from `amplify_get_app_info` 2. **Recursive Discovery**: Scan for `AWS::CloudFormation::Stack` resources (nested stacks) 3. **Deep Traversal**: Recursively query each nested stack for application resources 4. **Complete Mapping**: Find ALL Lambda functions, DynamoDB tables, AppSync APIs, Cognito pools ### What This Discovers (Real Example: Chinchilla-Ai-Academy) - โœ… **16 Lambda Functions** including: - **6 REST API Functions**: Stripe payment handlers, webhook processors, application logic - **1 Cognito Trigger**: Post-confirmation Lambda - **9 Infrastructure Functions**: Table management, S3 deployment, branch linking - โœ… **5+ DynamoDB Tables** (Achievement, Announcement, Course, User, UserProgress) - โœ… **1 AppSync GraphQL API** (mmj7kae5zjemfn6pzbuqm2edf4) with full CRUD resolvers - โœ… **Cognito Authentication** (User Pool: us-east-1_W6Fgqi8qt, Identity Pool, Groups) - โœ… **Perfect Branch Isolation** (dev vs main completely separate) ### Complete Lambda Function Discovery **REST API Business Logic Functions:** - `stripepaymentlambda` โ†’ Handles `/stripe/payment POST` - `stripevippaymentlambda` โ†’ Handles `/stripe/vip-payment POST` - `stripewebhooklambda` โ†’ Handles `/stripe/webhook POST` - `paymentintentnotificationlambda` โ†’ Payment intent notifications - `processapplicationlambda` โ†’ Application processing - `postconfirmationlambda` โ†’ Cognito post-signup trigger **Key Pattern**: Custom Lambda functions use pattern: `amplify-{appId}-{branch}-{logicalId}-{hash}` ### Technical Architecture ``` Main Stack (amplify-{appId}-{branch}-branch-{hash}) โ”œโ”€โ”€ PaymentApi Stack โ†’ REST API Lambda functions โ”œโ”€โ”€ auth Stack โ†’ Cognito User/Identity Pools + Groups โ”œโ”€โ”€ data Stack โ”‚ โ”œโ”€โ”€ Achievement Model Stack โ†’ DynamoDB + GraphQL resolvers โ”‚ โ”œโ”€โ”€ Announcement Model Stack โ†’ DynamoDB + GraphQL resolvers โ”‚ โ”œโ”€โ”€ Course Model Stack โ†’ DynamoDB + GraphQL resolvers โ”‚ โ”œโ”€โ”€ User Model Stack โ†’ DynamoDB + GraphQL resolvers โ”‚ โ””โ”€โ”€ UserProgress Model Stack โ†’ DynamoDB + GraphQL resolvers โ””โ”€โ”€ Infrastructure Functions (branch linking, deployment) ``` ### Testing Framework Breakthrough **Direct AWS Credential Testing**: Bypasses MCP account system completely - **`test/test-nested-stack-discovery.js`**: Full recursive discovery with real AWS - **`test/test-resource-discovery-simple.js`**: Golden Key logic validation - **`test/test-resource-discovery-direct.js`**: Direct AWS credential testing - **No MCP Dependencies**: Uses terminal AWS credentials directly ### Impact - **100% Application Resource Discovery**: No more missing Lambda functions or DynamoDB tables - **Perfect Debugging**: Get logs from actual application functions, not infrastructure - **Revolutionary Accuracy**: From 2 infrastructure functions โ†’ 16+ application functions - **Production Ready**: Handles real-world Amplify Gen 2 complexity ## Version 1.6.0 Update - COMPREHENSIVE LOG GROUP DISCOVERY ๐Ÿ“‹ **๐Ÿ” NEW: Integrated CloudWatch Log Group Discovery**: Enhanced `amplify_discover_resources` with comprehensive log group discovery and verification! ### What's New The resource discovery tool now automatically: 1. **Discovers All Log Groups**: Finds log groups for Lambda, AppSync, API Gateway, Cognito, and Step Functions 2. **Verifies Existence**: Checks if each log group actually exists in CloudWatch 3. **Provides Metadata**: Returns size, retention policy, and last event time for each log group 4. **Service Categorization**: Groups log groups by service type for easy filtering ### Log Group Patterns Discovered - **Lambda Functions**: `/aws/lambda/{functionName}` - **AppSync GraphQL**: `/aws/appsync/apis/{apiId}` - **API Gateway**: `API-Gateway-Execution-Logs_{apiId}/prod` and `/aws/apigateway/{apiId}/prod` - **Cognito User Pools**: `/aws/cognito/userpools/{userPoolId}` - **Step Functions**: `/aws/vendedlogs/states/{stateMachineId}` ### Usage Examples **Get All Resources with Log Groups:** ```typescript { "appId": "du9fm1pcbkcto", "branchName": "dev", "resourceType": "all" } ``` **Get Just Log Groups:** ```typescript { "appId": "du9fm1pcbkcto", "branchName": "dev", "resourceType": "log-groups" } ``` ### Response Includes ```json { "logGroups": [ { "name": "/aws/lambda/amplify-du9fm1pcbkcto-dev-stripepaymentlambda", "type": "Lambda", "service": "lambda", "resourceName": "amplify-du9fm1pcbkcto-dev-stripepaymentlambda", "exists": true, "sizeBytes": 1234567, "retentionDays": 7, "lastEventTime": "2024-01-15T10:30:00Z" } ], "logGroupsByService": { "lambda": [...], "appsync": [...], "apigateway": [...], "cognito": [...], "stepfunctions": [...] }, "summary": { "totalLogGroups": 20, "verifiedLogGroups": 16, "logGroupsByType": { "lambda": 16, "appsync": 1, "apigateway": 0, "cognito": 0, "stepfunctions": 0 } } } ``` ### Key Benefits - **One Tool, Complete Discovery**: No need for separate log group discovery tool - **Automatic Verification**: Know which log groups are active vs. potential - **Ready for CloudWatch Tools**: Use discovered log groups directly with `amplify_get_cloudwatch_logs` - **Service-Specific Filtering**: Easy to find logs for specific AWS services ## Version 1.4.0 Update - GOLDEN KEY APPROACH **๐Ÿ”‘ MAJOR UPGRADE: Golden Key Resource Discovery**: Completely rewrote `amplify_discover_resources` tool with revolutionary approach: - **100% Branch Isolation**: Uses CloudFormation stack ARNs from `amplify_get_app_info` as the "Golden Key" - **No More Guessing**: Direct CloudFormation stack queries - zero cross-contamination between branches - **Perfect Accuracy**: Eliminates the previous issue where tools would return logs from wrong branches or apps - **Simplified Logic**: No more searching through hundreds of stacks - we know exactly which stack to query **๐Ÿงช NEW: Testing Framework**: Added comprehensive testing infrastructure: - **`test/` directory**: Unit tests for core functions without MCP overhead - **Direct AWS testing**: Test resource discovery with real AWS credentials - **Golden Key validation**: Verify stack ARN extraction and parsing logic ## Version 1.3.0 Update **๐ŸŽฏ NEW: Tag-Based Resource Discovery**: Added `amplify_discover_branch_resources` tool that uses CloudFormation stack tags to reliably map logical function names to actual AWS resources and CloudWatch log groups. No more guessing naming patterns! ## Version 1.2.1 Update **๐Ÿš€ NEW: CloudWatch Logs Integration**: Added powerful CloudWatch logs tools for debugging Amplify applications: - **`amplify_get_app_info`** - Get comprehensive app details with branch-specific resource naming patterns - **`amplify_get_cloudwatch_logs`** - Full CloudWatch logs with AI-friendly formatting and advanced filtering - **`amplify_get_recent_logs`** - Quick debugging tool optimized for development with smart defaults (last 15 minutes, errors-first, minimal output) Perfect for development workflows: quickly check "are there any recent errors?" without information overload. ## Version 3.0.0 Update **Major Simplification**: Replaced complex, hard-coded tools with simple generic `ampx_execute` tool, inspired by the dev-logger pattern. Now works like dev-logger but for Amplify CLI commands - just pass any ampx command and it executes it. Removed brittle validation logic that was causing errors. ## Version 2.3.0 Update **Direct Command Execution**: Changed from `spawn("npx")` to `spawn("ampx")` to avoid the npx โ†’ npm exec transformation. This ensures processes show as `ampx` instead of `npm exec` in process lists and prevents potential confusion. ## Version 2.2.0 Update **Security Enhancement**: Removed AWS credential environment variables. The server now uses standard AWS credential chain (AWS CLI configuration, IAM roles, etc.) for better security and best practices. ## Version 2.1.1 Update **Fixed Command Validation**: The validation function now properly executes to catch incorrect command formats before they run. This ensures all Amplify commands use the correct `npx ampx` format. ## Version 2.1.0 Update **Improved Resource Discovery**: The server now uses `amplify_outputs.json` for accurate resource discovery, ensuring tools only find resources from the active sandbox deployment. This prevents cross-sandbox resource conflicts. **Command Validation**: Added validation to ensure correct command usage. The server now prevents common mistakes like using `npm exec ampx` and provides helpful error messages directing users to use `npx ampx` instead. ## Features - **App Lifecycle Management**: Create, delete, and get info for Amplify applications - **Environment Variables**: Set, get, and delete environment variables - **GitHub Integration**: Connect repositories and validate access - **Resource Discovery**: Automatically find and work with AWS resources from your Amplify deployment - **DynamoDB Operations**: Full CRUD operations on DynamoDB tables - **Lambda Functions**: Invoke functions, view logs, and get metrics - **CloudWatch Integration**: Tail logs and run insights queries - **GraphQL/AppSync**: Execute queries and get schema information - **Development Tools**: Stream function logs, deploy sandboxes, and more ## Tools Provided ### Core App Management - `amplify_list_apps` - List all Amplify apps in current AWS account - `amplify_get_app_info` - Get comprehensive app details with branch info and resource naming patterns - `amplify_list_branches` - List all branches for a specific app - `amplify_get_build_logs` - Get build/deployment logs for debugging - `amplify_create_nextjs_app` - Create a new Amplify Gen 2 Next.js application from the official AWS template - `amplify_deploy_app` - **ENHANCED v1.8.0** - Intelligent deployment with automatic existing app detection, Node 20+ configuration, and IAM role setup ### ๐Ÿ†• Intelligent Deployment Automation (v1.8.0) - `amplify_check_app_exists` - **Smart Detection** - Check if an Amplify app already exists for a GitHub repository - `amplify_update_build_spec` - **Node 20+ Configuration** - Update build specifications with Node 20+ and CDK support - `amplify_setup_iam_role` - **Automatic IAM** - Auto-detect and assign IAM roles for CDK operations - `amplify_trigger_deployment` - **Manual Control** - Force trigger deployments with validation and error handling ### ๐Ÿ†• Complete Specialized Logging Suite (v1.7.0) - `amplify_get_lambda_logs` - **Lambda function logging** - Specialized logging with function-specific filtering, time ranges, and log level support - `amplify_get_appsync_logs` - **GraphQL resolver logging** - AppSync operation logging with resolver type filtering and performance analysis - `amplify_get_cognito_logs` - **Authentication logging** - Cognito event logging with security analysis and failed attempt tracking - `amplify_get_apigateway_logs` - **REST API logging** - API Gateway request logging with endpoint, method, and status code filtering - `amplify_get_recent_logs` - **Quick debugging** - Get recent errors/warnings (last 15 minutes, max 25 entries) - `amplify_get_cloudwatch_logs` - **Advanced analysis** - Full CloudWatch logs with custom time ranges and filtering ### ๐Ÿ” Resource Discovery - `amplify_discover_resources` - **Revolutionary recursive discovery** - Find ALL Lambda functions, DynamoDB tables, AppSync APIs through nested CloudFormation stack traversal ### Environment Variables - `amplify_set_environment_vars` - Set or update environment variables - `amplify_get_environment_vars` - Get current environment variables - `amplify_delete_environment_var` - Delete specific environment variable ### Branch Management - `amplify_trigger_deployment` - **IMPLEMENTED v1.8.0** - Manually trigger deployment for any branch with validation - `amplify_add_branch` - Add branch for deployment (Future Implementation) - `amplify_delete_branch` - Remove branch deployment (Future Implementation) ## Prerequisites 1. **AWS Account** with Amplify access 2. **AWS CLI configured** with credentials (`aws configure`) 3. **GitHub Account** with repository access 4. **GitHub Personal Access Token** with repo permissions ## Installation ### From NPM (Recommended) ```bash # Install the server claude mcp add amplify -s user -- npx @chinchillaenterprises/mcp-amplify # After installation, add an account with AWS and GitHub credentials # (See Account Management section below) ``` ### For Development/Testing ```bash # Clone and build locally git clone <repository-url> cd mcp-amplify npm install npm run build # Add to Claude Code (local development) claude mcp add amplify-local -s user -- node $(pwd)/dist/index.js ``` ## Account Management The mcp-amplify server uses a built-in account management system to securely store AWS credentials and GitHub tokens. No environment variables are required. ### Setting Up Accounts with GitHub Credentials To use deployment features like `amplify_deploy_app`, you need to add an account with GitHub credentials: ```typescript // Add account with GitHub credentials { "name": "my-aws-account", "access_key_id": "YOUR_AWS_ACCESS_KEY", "secret_access_key": "YOUR_AWS_SECRET_KEY", "region": "us-east-1", "github_username": "your-github-username", "github_token": "ghp_your_github_token" } ``` ### GitHub Token Requirements For the `amplify_deploy_app` tool, you need a GitHub Personal Access Token with: - **repo** scope (for private repositories) - **public_repo** scope (for public repositories) Create your token at: https://github.com/settings/tokens ## AWS Configuration This server uses your existing AWS credentials from the standard AWS credential chain: - AWS CLI configuration (`~/.aws/credentials` and `~/.aws/config`) - IAM instance profiles (when running on EC2) - Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY if set globally) - IAM roles Configure AWS credentials using: ```bash aws configure ``` ## Usage Examples ### ๐Ÿ†• Intelligent Deployment Automation (v1.8.0) #### Check if App Exists for Repository ```typescript // Check if an Amplify app already exists for a GitHub repository { "githubOwner": "your-username", "githubRepo": "your-repository" } ``` **Response:** ```json { "exists": true, "app": { "appId": "d1a2b3c4d5e6f7", "name": "my-amplify-app", "repository": "https://github.com/your-username/your-repository", "platform": "WEB_COMPUTE", "branches": [ { "branchName": "main", "totalNumberOfJobs": 5, "enableAutoBuild": true } ], "hasDeployments": true } } ``` #### Smart Deploy App (Enhanced v1.8.0) ```typescript // Deploy app with automatic existing app detection and configuration { "appName": "my-next-app", "githubOwner": "your-username", "githubRepo": "your-repository", "branch": "main" } ``` **Response for Existing App:** ```json { "success": true, "appId": "d1a2b3c4d5e6f7", "existingApp": true, "updatesApplied": { "buildSpecUpdated": true, "iamRoleConfigured": true, "deploymentTriggered": true }, "message": "โœ… Successfully configured and deployed existing Amplify app", "nextSteps": [ "Monitor deployment progress at: https://console.aws.amazon.com/amplify/home#/d1a2b3c4d5e6f7/main", "View app (when ready): https://main.d1a2b3c4d5e6f7.amplifyapp.com" ] } ``` #### Update Build Spec to Node 20+ ```typescript // Update existing app to use Node 20+ with CDK support { "appId": "d1a2b3c4d5e6f7" } ``` **Response:** ```json { "success": true, "appId": "d1a2b3c4d5e6f7", "message": "Build spec updated successfully with Node 20+ configuration", "buildSpec": { "updated": true, "usesNode20": true, "supportsCDK": true, "hasBackendPhase": true, "hasFrontendPhase": true } } ``` #### Setup IAM Role for CDK Operations ```typescript // Auto-assign IAM role for CDK operations { "appId": "d1a2b3c4d5e6f7" } ``` **Response:** ```json { "success": true, "appId": "d1a2b3c4d5e6f7", "iamServiceRoleArn": "arn:aws:iam::123456789012:role/service-role/AmplifySSRLoggingRole-abc123", "message": "IAM service role assigned successfully", "roleInfo": { "assigned": true, "autoDetected": true, "roleArn": "arn:aws:iam::123456789012:role/service-role/AmplifySSRLoggingRole-abc123" } } ``` #### Trigger Manual Deployment ```typescript // Manually trigger deployment with validation { "appId": "d1a2b3c4d5e6f7", "branchName": "main", "jobType": "RELEASE" } ``` **Response:** ```json { "success": true, "appId": "d1a2b3c4d5e6f7", "branchName": "main", "deployment": { "jobId": "1", "jobType": "RELEASE", "status": "PENDING", "startTime": "2024-01-15T10:30:00Z", "commitId": "abc123def456", "commitMessage": "Update deployment configuration" }, "message": "Deployment triggered successfully for branch 'main'", "nextSteps": [ "Monitor deployment at: https://console.aws.amazon.com/amplify/home#/d1a2b3c4d5e6f7/main", "Use amplify_get_build_logs to check deployment progress" ] } ``` ### ๐Ÿ†• Quick Debugging with Recent Logs ```typescript // Simple usage - check for recent errors { "appId": "d1a2b3c4d5e6f7" } ``` **Response:** ```json { "quickSummary": "๐Ÿšจ 3 error(s) found in main branch (last 15m)", "metrics": { "timeWindow": "15m", "targetBranch": "main", "errorCount": 3, "warningCount": 1 }, "immediateIssues": [ { "service": "Lambda", "logGroup": "myFunction-abc123", "errorCount": 2, "lastError": "Database connection timeout after 5000ms..." } ], "suggestions": [ "๐Ÿ” Check the errors above - they might indicate immediate issues to fix", "๐Ÿ”ง For Lambda errors, check function permissions and environment variables" ] } ``` ### ๐Ÿ†• Specialized Lambda Logging (NEW v1.7.0) ```typescript // Get all Lambda function logs from last hour { "appId": "du9fm1pcbkcto", "branchName": "dev", "logLevel": "all", "timeRange": "1h", "maxEvents": 50 } // Get ERROR logs from specific function { "appId": "du9fm1pcbkcto", "branchName": "dev", "functionName": "stripepaymentlambda", "logLevel": "ERROR", "timeRange": "6h", "maxEvents": 100 } // Get logs with custom filter pattern { "appId": "du9fm1pcbkcto", "branchName": "dev", "logLevel": "INFO", "timeRange": "24h", "filterPattern": "VIP checkout", "includeMetrics": true } ``` **Response Format:** ```json { "success": true, "appId": "du9fm1pcbkcto", "branchName": "dev", "totalFunctions": 13, "functionsWithLogs": 1, "totalLogs": 7, "functionLogs": [ { "functionName": "amplify-du9fm1pcbkcto-dev-paymentintentnotificatio-Z1jCS5CFQYkQ", "logicalId": "paymentintentnotificationlambdaCB168223", "logGroupName": "/aws/lambda/amplify-du9fm1pcbkcto-dev-paymentintentnotificatio-Z1jCS5CFQYkQ", "logsFound": 7, "logs": [ { "timestamp": "2025-07-09T23:00:06.885Z", "message": "๐Ÿšจ PAYMENT INTENT: Someone reached VIP checkout page!", "logStream": "2025/07/09/[$LATEST]fc332d7cccd64951a8b2a77fcfb30562", "requestId": "70864545-fa46-4ddb-99a7-904579d7ed8f" } ] } ] } ``` ### ๐Ÿ†• Specialized API Gateway Logging (NEW v1.7.0) ```typescript // Get all API Gateway logs from last hour { "appId": "du9fm1pcbkcto", "branchName": "dev", "httpMethod": "all", "timeRange": "1h", "includeLatency": true, "maxEvents": 50 } // Get only POST requests with latency data { "appId": "du9fm1pcbkcto", "branchName": "dev", "httpMethod": "POST", "includeLatency": true, "includeRequestResponse": true, "timeRange": "6h" } // Get 4XX/5XX errors for specific endpoint { "appId": "du9fm1pcbkcto", "branchName": "dev", "endpoint": "/stripe/payment", "statusCode": 500, "timeRange": "24h", "maxEvents": 100 } ``` **Response Format:** ```json { "success": true, "appId": "du9fm1pcbkcto", "branchName": "dev", "totalApis": 2, "apisWithLogs": 1, "totalLogs": 15, "methodStats": { "POST": 12, "GET": 3 }, "endpointStats": { "/stripe/payment": 8, "/stripe/webhook": 4, "/api/health": 3 }, "apiLogs": [ { "apiId": "abc123def456", "name": "API Gateway API abc123def456", "apiType": "REST", "logsFound": 15, "performanceStats": { "averageResponseTime": 245.6, "maxResponseTime": 1200, "slowRequests": 0 }, "statusCodeStats": { "200": 12, "400": 2, "500": 1 }, "logs": [ { "timestamp": "2025-07-09T23:15:42.123Z", "message": "POST /stripe/payment 200 245ms", "logType": "access", "httpMethod": "POST", "endpoint": "/stripe/payment", "statusCode": 200, "responseTime": 245, "requestId": "abc123-def456-789ghi" } ] } ] } ``` ### ๐Ÿ†• Specialized Cognito Authentication Logging (NEW v1.7.0) ```typescript // Get all authentication events from last hour { "appId": "du9fm1pcbkcto", "branchName": "dev", "eventType": "all", "timeRange": "1h", "includeFailedAttempts": true } // Get only sign-in attempts for specific user { "appId": "du9fm1pcbkcto", "branchName": "dev", "eventType": "signin", "userId": "abc123-def456-789ghi", "timeRange": "24h", "includeFailedAttempts": true } // Get failed authentication attempts for security analysis { "appId": "du9fm1pcbkcto", "branchName": "dev", "eventType": "all", "includeFailedAttempts": true, "timeRange": "6h", "logLevel": "ERROR" } ``` **Response Format:** ```json { "success": true, "appId": "du9fm1pcbkcto", "branchName": "dev", "totalUserPools": 1, "userPoolsWithLogs": 1, "totalLogs": 15, "uniqueUsers": 3, "overallEventStats": { "signin": 12, "signup": 2, "token_refresh": 1 }, "overallSuccessFailureStats": { "successful": 13, "failed": 2, "unknown": 0 }, "userPoolLogs": [ { "userPoolId": "us-east-1_W6Fgqi8qt", "name": "amplifyAuthUserPool4BA7F805", "logsFound": 15, "logs": [ { "timestamp": "2025-07-09T23:15:30.123Z", "message": "User signin successful for user abc123-def456-789ghi", "eventType": "signin", "userId": "abc123-def456-789ghi", "username": "john@example.com", "success": true, "ipAddress": "192.168.1.100" } ], "successFailureStats": { "successful": 13, "failed": 2, "unknown": 0 } } ], "summary": { "securityInsights": { "hasFailedAttempts": true, "failedAttemptRate": "13.3%", "uniqueUsersActive": 3, "mostCommonEvent": "signin" }, "recommendations": [ "Failed authentication attempts detected. Monitor for potential security issues.", "3 unique user(s) had authentication activity." ] } } ``` ### Advanced CloudWatch Log Analysis ```typescript // Get Lambda errors from last hour with custom filtering { "appId": "d1a2b3c4d5e6f7", "branchName": "staging", "serviceType": "lambda", "startTime": "1h ago", "filterPattern": "ERROR", "format": "structured" } ``` ### ๐Ÿ”‘ Recursive Nested Stack Discovery (Revolutionary Real-World Results) ```typescript // Discover ALL resources for a specific branch with 100% accuracy using recursive traversal { "appId": "du9fm1pcbkcto", "branchName": "dev", "resourceType": "all" } ``` **Response (Real Chinchilla-Ai-Academy Results):** ```json { "success": true, "appId": "du9fm1pcbkcto", "branchName": "dev", "mainStackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b", "stackArn": "arn:aws:cloudformation:us-east-1:755956835466:stack/amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b/83b33200-5b6c-11f0-87ba-12b9f467ba8f", "discoveryMethod": "recursive-nested-stack-discovery", "lambdaFunctions": [ { "functionName": "amplify-du9fm1pcbkcto-dev-stripepaymentlambdaF20FF-CxHwX3cu9VsV", "logGroupName": "/aws/lambda/amplify-du9fm1pcbkcto-dev-stripepaymentlambdaF20FF-CxHwX3cu9VsV", "logicalId": "stripepaymentlambdaF20FFA93", "purpose": "Handles /stripe/payment POST" }, { "functionName": "amplify-du9fm1pcbkcto-dev-stripevippaymentlambdaE3-V9jObhBec78s", "logGroupName": "/aws/lambda/amplify-du9fm1pcbkcto-dev-stripevippaymentlambdaE3-V9jObhBec78s", "logicalId": "stripevippaymentlambdaE3FE7860", "purpose": "Handles /stripe/vip-payment POST" }, { "functionName": "amplify-du9fm1pcbkcto-dev-stripewebhooklambdaF97E3-O81jN6geKtXv", "logGroupName": "/aws/lambda/amplify-du9fm1pcbkcto-dev-stripewebhooklambdaF97E3-O81jN6geKtXv", "logicalId": "stripewebhooklambdaF97E31A6", "purpose": "Handles /stripe/webhook POST" }, { "functionName": "amplify-du9fm1pcbkcto-dev-postconfirmationlambda19-GvdRI9a91WVH", "logGroupName": "/aws/lambda/amplify-du9fm1pcbkcto-dev-postconfirmationlambda19-GvdRI9a91WVH", "logicalId": "postconfirmationlambda195D98D2", "purpose": "Cognito post-confirmation trigger" } // ... plus 12 more infrastructure functions ], "dynamoDBTables": [ { "tableName": "Achievement-mmj7kae5zjemfn6pzbuqm2edf4-NONE", "logicalId": "AchievementTable", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-amplifyDataAchievementNestedStackAchieveme-DZWNFR7ZMD3U", "status": "CREATE_COMPLETE" }, { "tableName": "Announcement-mmj7kae5zjemfn6pzbuqm2edf4-NONE", "logicalId": "AnnouncementTable", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-amplifyDataAnnouncementNestedStackAnnounce-1HZDWWTCM04IU", "status": "CREATE_COMPLETE" }, { "tableName": "Course-mmj7kae5zjemfn6pzbuqm2edf4-NONE", "logicalId": "CourseTable", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-amplifyDataCourseNestedStackCourseNestedSt-1LTUN6L8IC2NJ", "status": "CREATE_COMPLETE" }, { "tableName": "User-mmj7kae5zjemfn6pzbuqm2edf4-NONE", "logicalId": "UserTable", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-amplifyDataUserNestedStackUserNestedStackR-1AN6UZ5QBL5IS", "status": "CREATE_COMPLETE" }, { "tableName": "UserProgress-mmj7kae5zjemfn6pzbuqm2edf4-NONE", "logicalId": "UserProgressTable", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-amplifyDataUserProgressNestedStackUserProg-S6L2T2LDI88A", "status": "CREATE_COMPLETE" } ], "appSyncApis": [ { "apiId": "mmj7kae5zjemfn6pzbuqm2edf4", "logicalId": "amplifyDataGraphQLAPI", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-data7552DF31-1GIA017EE5958", "status": "CREATE_COMPLETE" } ], "cognitoUserPools": [ { "userPoolId": "us-east-1_W6Fgqi8qt", "logicalId": "amplifyAuthUserPool4BA7F805", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-auth179371D7-1WAAZFBXXGJJF", "status": "CREATE_COMPLETE" } ], "cognitoIdentityPools": [ { "identityPoolId": "us-east-1:0cbf0ed9-c4de-41dd-8047-8304642141f1", "logicalId": "amplifyAuthIdentityPool3FDE84CC", "stackName": "amplify-du9fm1pcbkcto-dev-branch-f81f5dda9b-auth179371D7-1WAAZFBXXGJJF", "status": "CREATE_COMPLETE" } ], "summary": { "totalLambdaFunctions": 16, "totalDynamoDBTables": 5, "totalAppSyncApis": 1, "totalCognitoUserPools": 1, "totalCognitoIdentityPools": 1, "totalNestedStacks": 8, "verifiedLogGroups": 16, "readyForCloudWatchQuery": 16 } } ``` **๐ŸŽฏ Revolutionary Breakthrough:** - **16 Lambda Functions Discovered**: From 2 basic infrastructure โ†’ 16 real application functions - **5 DynamoDB Tables Found**: Achievement, Announcement, Course, User, UserProgress - **Complete AppSync API**: GraphQL API with all resolvers and CRUD operations - **Full Cognito Setup**: User Pool, Identity Pool, User Groups (ADMIN, INSTRUCTOR, STUDENT) - **Perfect Branch Isolation**: 100% dev-branch specific resources, zero cross-contamination - **Recursive Traversal**: Automatically discovers resources 3-4 levels deep in nested stacks ### Create a New Amplify App ```typescript // Create app connected to GitHub repository { "appName": "my-react-app", "githubOwner": "username", "githubRepo": "my-repo", "branch": "main", "environmentVars": { "NODE_ENV": "production", "API_URL": "https://api.example.com" }, "platform": "WEB" } ``` **Response:** ```json { "status": "created", "appId": "d1a2b3c4d5e6f7", "appName": "my-react-app", "appUrl": "https://main.d1a2b3c4d5e6f7.amplifyapp.com", "repository": "username/my-repo", "branch": "main", "platform": "WEB" } ``` ### Create a Next.js Amplify App from Template ```typescript // Create a new Next.js app from the official AWS template { "projectName": "my-amplify-app", "directory": "/Users/username/projects", // Optional, defaults to current directory "installDependencies": true, // Optional, defaults to true "initGit": true, // Optional, defaults to true "useCurrentDirectory": false // Optional, defaults to false } // Or create in current directory: { "projectName": ".", "installDependencies": true } ``` **Response:** ```json { "success": true, "projectName": "my-amplify-app", "projectPath": "/Users/username/projects/my-amplify-app", "templateVersion": "1.0.0", "dependencies": { "installed": true, "count": 12, "devCount": 8 }, "git": { "initialized": true, "remote": null }, "nextSteps": [ "cd my-amplify-app", "npx ampx sandbox", "npm run dev", "Deploy to AWS Amplify Console when ready" ], "structure": { "hasAmplifyFolder": true, "hasAuth": true, "hasData": true, "hasSrcFolder": true, "isTypeScript": true, "isAppRouter": true }, "message": "โœ… Successfully created Amplify Next.js app..." } ``` ### Deploy App to AWS ```typescript // Deploy an app to AWS Amplify by connecting to GitHub { "appName": "my-amplify-nextjs-app", "githubOwner": "username", "githubRepo": "my-nextjs-repo", "branch": "main", // Optional, defaults to 'main' "platform": "WEB_COMPUTE", // Optional, defaults to 'WEB_COMPUTE' for SSR "environmentVariables": { // Optional "NEXT_PUBLIC_API_URL": "https://api.example.com" } } ``` **Response:** ```json { "success": true, "appId": "d3a4b5c6d7e8f9", "appName": "my-amplify-nextjs-app", "appUrl": "https://main.d3a4b5c6d7e8f9.amplifyapp.com", "repository": "username/my-nextjs-repo", "branch": "main", "platform": "WEB_COMPUTE", "deployment": { "jobId": "1", "status": "PENDING", "message": "Deployment started. It may take 5-10 minutes to complete." }, "nextSteps": [ "Monitor deployment progress at: https://console.aws.amazon.com/amplify/home#/d3a4b5c6d7e8f9/main", "View app (when ready): https://main.d3a4b5c6d7e8f9.amplifyapp.com", "Run \"amplify_get_build_logs\" to check deployment status", "Set up custom domain if needed" ] } ``` ### Set Environment Variables ```typescript // Add or update environment variables { "appId": "d1a2b3c4d5e6f7", "environmentVars": { "DATABASE_URL": "postgres://...", "JWT_SECRET": "secret-key", "STRIPE_KEY": "pk_live_..." } } ``` ### Get App Information ```typescript // Get comprehensive app details { "appId": "d1a2b3c4d5e6f7" } ``` **Response:** ```json { "appId": "d1a2b3c4d5e6f7", "name": "my-react-app", "repository": "https://github.com/username/my-repo", "platform": "WEB", "defaultDomain": "d1a2b3c4d5e6f7.amplifyapp.com", "enableBranchAutoBuild": true, "enableBranchAutoDeletion": true, "environmentVariables": { "NODE_ENV": "production", "API_URL": "https://api.example.com" }, "createTime": "2024-01-15T10:30:00Z", "updateTime": "2024-01-15T11:45:00Z" } ``` ### Delete an App ```typescript // Remove app completely { "appId": "d1a2b3c4d5e6f7" } ``` ## GitHub Repository Requirements For successful Amplify deployment, your GitHub repository should contain: 1. **Frontend Framework**: React, Next.js, Vue, Angular, etc. 2. **Build Configuration**: `amplify.yml` file (optional - Amplify can auto-detect) 3. **Package Manager**: `package.json` with build scripts ### Example `amplify.yml` ```yaml version: 1 frontend: phases: preBuild: commands: - npm ci build: commands: - npm run build artifacts: baseDirectory: build files: - '**/*' cache: paths: - node_modules/**/* ``` ## Authentication Setup ### AWS Credentials 1. **IAM User**: Create IAM user with Amplify permissions 2. **Access Keys**: Generate Access Key ID and Secret Access Key 3. **Permissions**: Attach `AmplifyFullAccess` policy or custom policy ### GitHub Token 1. Go to GitHub Settings > Developer settings > Personal access tokens 2. Create token with `repo` scope for private repos, `public_repo` for public repos 3. Copy the token for use when adding accounts with GitHub credentials ## Limitations - **Branch Management**: Currently requires AWS CLI or Console for branch operations - **Build Triggering**: Manual builds require direct API calls - **GitHub Integration**: Requires GitHub Personal Access Token (GitHub Apps not yet supported) ## Error Handling The server provides detailed error messages for common issues: - **Repository Not Found**: Validates GitHub repository exists and is accessible - **AWS Permissions**: Clear messages for missing AWS permissions - **Invalid App ID**: Validation for non-existent Amplify applications - **GitHub Token**: Clear error when GitHub credentials are missing for deployment ## Troubleshooting ### Common Deployment Issues #### "GitHub token is required" Error **Problem**: The `amplify_deploy_app` tool fails with a GitHub token error. **Solution**: 1. Check if your active account has GitHub credentials: ```typescript // List accounts and check hasGitHub status amplify_list_accounts() ``` 2. If `hasGitHub: false`, add GitHub credentials to your account: ```typescript // Update existing account with GitHub credentials amplify_update_account({ "account_id": "your-account-id", "github_username": "your-github-username", "github_token": "ghp_your_github_token" }) ``` 3. Or create a new account with GitHub credentials: ```typescript // Add new account with GitHub credentials amplify_add_account({ "name": "aws-with-github", "access_key_id": "YOUR_AWS_ACCESS_KEY", "secret_access_key": "YOUR_AWS_SECRET_KEY", "region": "us-east-1", "github_username": "your-github-username", "github_token": "ghp_your_github_token" }) ``` #### "Repository not found or not accessible" Error **Problem**: GitHub repository validation fails during deployment. **Solution**: 1. Verify the repository exists: `https://github.com/owner/repo` 2. Check GitHub token permissions: - Must have `repo` scope for private repositories - Must have `public_repo` scope for public repositories 3. Verify the token is not expired 4. Test token access by visiting: https://github.com/settings/tokens #### "App name already exists" Error **Problem**: Amplify app name conflicts with existing app. **Solution**: 1. Use a unique app name 2. Or delete the existing app first: ```typescript amplify_list_apps() // Find the conflicting app // Delete via AWS Console or CLI ``` #### "Branch has never been deployed" Issue **Problem**: App is created but deployment doesn't start automatically. **Solution**: - **COMPLETELY SOLVED in v1.8.0**: The intelligent deployment system now automatically handles all deployment scenarios - **For existing apps**: Use `amplify_trigger_deployment` to manually trigger deployments with validation - **For new apps**: The enhanced `amplify_deploy_app` automatically triggers initial builds - **Smart Detection**: The system detects apps that need deployment and handles them automatically #### "No AmplifySSRLoggingRole found" Warning **Problem**: `amplify_setup_iam_role` can't find the required IAM role for CDK operations. **Solution**: 1. **Auto-create the role**: Deploy any Amplify app with SSR/CDK features through the AWS Console first 2. **Manual creation**: Create the AmplifySSRLoggingRole in IAM with appropriate permissions 3. **Provide custom role**: Use `amplify_setup_iam_role` with a specific `roleArn` parameter #### Build Spec Update Issues **Problem**: `amplify_update_build_spec` fails or build still uses old Node version. **Solution**: 1. **Check app permissions**: Ensure you have `amplify:UpdateApp` permission 2. **Custom build spec**: Provide a custom `buildSpec` parameter if the default doesn't work 3. **Verify deployment**: Use `amplify_trigger_deployment` after updating build spec 4. **Check logs**: Use `amplify_get_build_logs` to verify the Node version is actually being used #### Deployment Trigger Failures **Problem**: `amplify_trigger_deployment` fails with validation errors. **Solution**: 1. **Verify branch exists**: Check that the branch exists in the GitHub repository 2. **Check app status**: Ensure the app is in a healthy state (not currently deploying) 3. **Validate permissions**: Ensure you have `amplify:StartJob` permission 4. **Use different job type**: Try `jobType: "RETRY"` if `RELEASE` fails #### AWS Permissions Issues **Problem**: AWS API calls fail with permission errors. **Solution**: 1. Ensure your AWS account has `AmplifyFullAccess` policy 2. For custom policies, include these permissions (enhanced for v1.8.0): ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "amplify:*", "iam:PassRole", "iam:ListRoles", "iam:GetRole", "codecommit:GitPull" ], "Resource": "*" } ] } ``` ### Quick Diagnostic Commands ```typescript // Check account status amplify_list_accounts() // Check active account details amplify_get_active_account() // Test AWS connectivity amplify_list_apps() // Check if app exists for repository (v1.8.0) amplify_check_app_exists({ "githubOwner": "your-username", "githubRepo": "your-repository" }) // Update app configuration (v1.8.0) amplify_update_build_spec({ "appId": "your-app-id" }) // Setup IAM role (v1.8.0) amplify_setup_iam_role({ "appId": "your-app-id" }) // Trigger manual deployment (v1.8.0) amplify_trigger_deployment({ "appId": "your-app-id", "branchName": "main" }) // Monitor deployment amplify_get_build_logs({ "appId": "your-app-id", "branchName": "main" }) ``` ## Development ### Building ```bash npm run build ``` ### Watch Mode ```bash npm run dev ``` ### ๐Ÿงช Testing Framework The server includes a comprehensive testing framework for development: ```bash # Test Golden Key resource discovery logic (no AWS required) node test/test-resource-discovery-simple.js # Test full resource discovery with real AWS credentials node test/test-resource-discovery.js # Test specialized logging tools without MCP overhead node test/test-lambda-logs-direct.js node test/test-apigateway-logs-direct.js # Test specific functions without MCP overhead node test/test-[function-name].js ``` **Testing Benefits:** - **No MCP Context Required**: Test functions directly with terminal AWS credentials - **Faster Development**: No need to restart Claude Code for each test - **Real AWS Data**: Test with actual CloudFormation stacks and resources - **Isolated Testing**: Test individual functions without MCP server complexity ### MCP Integration Testing ```bash # Test with local installation claude mcp add amplify-test -s user -- node $(pwd)/dist/index.js # Start Claude and test tools claude > /mcp # Check if server is connected ``` ## Contributing 1. Fork the repository 2. Create feature branch 3. Make changes and test thoroughly 4. Submit pull request with clear description ## License MIT License - see LICENSE file for details. ## Support For issues and questions: - Check the troubleshooting section in the main ChillMCP README - Open an issue in the repository - Verify AWS and GitHub credentials are correctly configured