Repository navigation
Expand file tree
/
Copy pathdeploy.sh
More file actions
executable file
·2599 lines (2287 loc) · 101 KB
/
Copy pathdeploy.sh
File metadata and controls
executable file
·2599 lines (2287 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
set -e
# Automatick AgentCore Deployment
# Usage: ./deploy.sh --email admin@example.com [--region us-east-1]
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Parse arguments
EMAIL=""
REGION="us-east-1"
while [[ $# -gt 0 ]]; do
case $1 in
--email)
EMAIL="$2"
shift 2
;;
--region)
REGION="$2"
shift 2
;;
*)
echo "Unknown option: $1"
echo "Usage: ./deploy.sh --email user@example.com [--region us-east-1]"
exit 1
;;
esac
done
if [ -z "$EMAIL" ]; then
echo -e "${RED}Error: --email required${NC}"
exit 1
fi
# Load environment variables from backend/.env
if [ -f "backend/.env" ]; then
echo "Loading configuration from backend/.env..."
export $(grep -v '^#' backend/.env | xargs)
echo "✓ Configuration loaded"
else
echo -e "${RED}Error: backend/.env not found${NC}"
echo "Please copy backend/.env.example to backend/.env and configure it"
echo ""
echo "Required variables:"
echo " - AWS_REGION"
echo " - MODEL"
echo " - FRESHDESK_DOMAIN"
echo " - FRESHDESK_API_KEY"
echo " - FRESHDESK_WEBHOOK_SECRET"
exit 1
fi
# Deployment mode defaults for the Automatick Freshdesk MVP.
export AUTOMATICK_MODE="${AUTOMATICK_MODE:-headless}"
export ENABLE_FRONTEND="${ENABLE_FRONTEND:-false}"
export ENABLE_JIRA="${ENABLE_JIRA:-false}"
export ENABLE_FRESHDESK="${ENABLE_FRESHDESK:-true}"
export PROJECT_TAG_VALUE="${PROJECT_TAG_VALUE:-mps-ops-utomation-poc}"
export OWNER_TAG_VALUE="${OWNER_TAG_VALUE:-simone.ferraro}"
export CDK_PYTHON="${CDK_PYTHON:-python3.11}"
if [ -z "${BACKEND_DOCKER_PLATFORM:-}" ]; then
case "$(uname -m)" in
aarch64|arm64)
export BACKEND_DOCKER_PLATFORM="linux/arm64"
export BACKEND_CPU_ARCHITECTURE="${BACKEND_CPU_ARCHITECTURE:-ARM64}"
;;
*)
export BACKEND_DOCKER_PLATFORM="linux/amd64"
export BACKEND_CPU_ARCHITECTURE="${BACKEND_CPU_ARCHITECTURE:-X86_64}"
;;
esac
else
export BACKEND_CPU_ARCHITECTURE="${BACKEND_CPU_ARCHITECTURE:-X86_64}"
fi
echo -e "${GREEN}╔════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Automatick → AgentCore Deployment ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════╝${NC}"
echo ""
echo "Email: $EMAIL"
echo "Region: $REGION"
echo "Mode: $AUTOMATICK_MODE"
echo "Frontend: $ENABLE_FRONTEND | Jira: $ENABLE_JIRA | Freshdesk: $ENABLE_FRESHDESK"
echo "Backend platform: $BACKEND_DOCKER_PLATFORM | ECS CPU: $BACKEND_CPU_ARCHITECTURE"
echo "CDK Python: $CDK_PYTHON"
echo "Resource tags: Project=$PROJECT_TAG_VALUE | owner=$OWNER_TAG_VALUE"
echo ""
# Tee all output (stdout + stderr) to a timestamped log file
LOG_FILE="deploy-$(date +%Y%m%d-%H%M%S).log"
exec > >(tee -a "$LOG_FILE") 2>&1
echo "Logging to $LOG_FILE"
# Validate required environment variables
echo "Validating environment variables..."
REQUIRED_VARS=("MODEL")
if [ "$ENABLE_FRESHDESK" = "true" ]; then
REQUIRED_VARS+=("FRESHDESK_DOMAIN" "FRESHDESK_API_KEY" "FRESHDESK_WEBHOOK_SECRET")
fi
if [ "$ENABLE_JIRA" = "true" ]; then
REQUIRED_VARS+=("JIRA_DOMAIN" "JIRA_EMAIL" "JIRA_API_TOKEN" "JIRA_PROJECT_KEY")
fi
MISSING_VARS=()
for var in "${REQUIRED_VARS[@]}"; do
if [ -z "${!var}" ]; then
MISSING_VARS+=("$var")
fi
done
if [ ${#MISSING_VARS[@]} -gt 0 ]; then
echo -e "${RED}Error: Missing required environment variables:${NC}"
for var in "${MISSING_VARS[@]}"; do
echo " - $var"
done
echo ""
echo "Please configure these in backend/.env"
exit 1
fi
echo "✓ All required variables configured"
if [ "$ENABLE_FRESHDESK" = "true" ]; then
echo " Freshdesk Domain: $FRESHDESK_DOMAIN"
fi
if [ "$ENABLE_JIRA" = "true" ]; then
echo " Jira Domain: $JIRA_DOMAIN"
echo " Jira Email: $JIRA_EMAIL"
fi
echo " Model: $MODEL"
echo ""
# Set script directory for absolute path references
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_TAG_ARGS=("Key=Project,Value=$PROJECT_TAG_VALUE" "Key=owner,Value=$OWNER_TAG_VALUE")
PROJECT_TAG_MAP="Project=$PROJECT_TAG_VALUE,owner=$OWNER_TAG_VALUE"
tag_agentcore_resource() {
local RESOURCE_ARN="$1"
local LABEL="$2"
if [ -z "$RESOURCE_ARN" ] || [ "$RESOURCE_ARN" = "None" ] || [ "$RESOURCE_ARN" = "null" ]; then
return 0
fi
aws bedrock-agentcore-control tag-resource \
--resource-arn "$RESOURCE_ARN" \
--tags "$PROJECT_TAG_MAP" \
--region "$REGION" >/dev/null 2>&1 && \
echo " ✓ Tagged $LABEL" || echo " ⚠️ Could not tag $LABEL"
}
tag_iam_role() {
local ROLE_NAME="$1"
aws iam tag-role --role-name "$ROLE_NAME" --tags "${PROJECT_TAG_ARGS[@]}" >/dev/null 2>&1 && \
echo " ✓ Tagged IAM role: $ROLE_NAME" || true
}
# Helper function: Get CLI caller's managed policies (handles both IAM users and assumed roles)
get_cli_managed_policies() {
local caller_arn=$(aws sts get-caller-identity --query 'Arn' --output text --region "$REGION")
# Detect if caller is IAM user or assumed role
if [[ "$caller_arn" == *":user/"* ]]; then
# IAM User
local username=$(echo "$caller_arn" | awk -F'/' '{print $NF}')
aws iam list-attached-user-policies --user-name "$username" \
--query 'AttachedPolicies[].PolicyArn' --output text --region "$REGION" 2>/dev/null || echo ""
elif [[ "$caller_arn" == *":assumed-role/"* ]]; then
# Assumed Role (SSO, EC2 instance role, etc.)
local role_name=$(echo "$caller_arn" | awk -F'/' '{print $2}')
aws iam list-attached-role-policies --role-name "$role_name" \
--query 'AttachedPolicies[].PolicyArn' --output text --region "$REGION" 2>/dev/null || echo ""
else
# Unknown principal type - return empty
echo ""
fi
}
# Step 1: Prerequisites validation
echo -e "${YELLOW}[1/14] Validating prerequisites...${NC}"
chmod +x scripts/validate-prerequisites.sh
scripts/validate-prerequisites.sh "$REGION"
# Step 2: Build backend Docker image
echo -e "${YELLOW}[2/14] Building backend Docker image...${NC}"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR_REPO_NAME="msp-assistant-backend"
ECR_REPO_URI="$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$ECR_REPO_NAME"
echo "Building Docker image (no cache for fresh build)..."
docker build --platform "$BACKEND_DOCKER_PLATFORM" --no-cache -t msp-assistant-backend:latest -f backend/Dockerfile .
# Verify build succeeded
if ! docker images msp-assistant-backend:latest --format "{{.ID}}" | grep -q .; then
echo -e "${RED}Error: Docker build failed${NC}"
exit 1
fi
echo "✓ Docker image built"
# Tag for ECR
echo "Tagging image for ECR: $ECR_REPO_URI:latest"
docker tag msp-assistant-backend:latest "$ECR_REPO_URI:latest"
# Verify tag succeeded
if ! docker images "$ECR_REPO_URI:latest" --format "{{.ID}}" | grep -q .; then
echo -e "${RED}Error: Docker tag failed${NC}"
exit 1
fi
echo "✓ Docker image tagged for ECR"
# Step 3: Push backend image to ECR
echo -e "${YELLOW}[3/14] Pushing backend image to ECR...${NC}"
# Ensure ECR repository exists
echo "Checking ECR repository..."
if ! aws ecr describe-repositories --repository-names "$ECR_REPO_NAME" --region "$REGION" &>/dev/null; then
echo "Creating ECR repository: $ECR_REPO_NAME"
aws ecr create-repository \
--repository-name "$ECR_REPO_NAME" \
--region "$REGION" \
--tags "${PROJECT_TAG_ARGS[@]}" \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=AES256
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to create ECR repository${NC}"
exit 1
fi
echo "✓ ECR repository created"
else
echo "✓ ECR repository exists"
fi
aws ecr tag-resource \
--resource-arn "arn:aws:ecr:${REGION}:${ACCOUNT_ID}:repository/${ECR_REPO_NAME}" \
--tags "${PROJECT_TAG_ARGS[@]}" \
--region "$REGION" >/dev/null 2>&1 || true
# Login to ECR
echo "Authenticating with ECR..."
echo " Account: $ACCOUNT_ID"
echo " Region: $REGION"
echo " Repository: $ECR_REPO_URI"
aws ecr get-login-password --region "$REGION" | docker login --username AWS --password-stdin "$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: ECR authentication failed${NC}"
exit 1
fi
echo "✓ ECR authentication successful"
# Push image
echo ""
echo "Pushing image to ECR..."
echo " Source: msp-assistant-backend:latest"
echo " Destination: $ECR_REPO_URI:latest"
echo ""
docker push "$ECR_REPO_URI:latest"
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Docker push failed${NC}"
exit 1
fi
echo ""
echo "✓ Backend image pushed to ECR"
# Verify image exists in ECR
echo "Verifying image in ECR..."
IMAGE_DIGEST=$(aws ecr describe-images --repository-name "$ECR_REPO_NAME" --region "$REGION" --image-ids imageTag=latest --query 'imageDetails[0].imageDigest' --output text 2>/dev/null)
if [ -n "$IMAGE_DIGEST" ] && [ "$IMAGE_DIGEST" != "None" ]; then
echo "✓ Image verified in ECR: $IMAGE_DIGEST"
else
echo -e "${YELLOW}⚠️ Warning: Could not verify image in ECR, but push appeared successful${NC}"
fi
# Step 4: Deploy Supervisor Runtime (MOVED BEFORE CDK)
echo -e "${YELLOW}[4/14] Deploying Supervisor Runtime...${NC}"
echo ""
echo "⚠️ CRITICAL: Supervisor must deploy BEFORE CDK"
echo " CDK reads outputs.json to get Runtime ARN for ECS environment variables"
echo ""
cd "$SCRIPT_DIR/agents/runtime"
# Clean old configuration AND stale env files to force fresh deployment
rm -f .bedrock_agentcore.yaml
rm -f env_config.txt
echo "Configuring Supervisor Runtime with Direct Python deployment..."
agentcore configure \
--entrypoint supervisor_runtime.py \
--protocol HTTP \
--name msp_supervisor_agent \
--region "$REGION" \
--requirements-file requirements.txt \
--non-interactive
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Supervisor configuration failed${NC}"
cd "$SCRIPT_DIR"
exit 1
fi
echo " Configuration complete, starting deployment..."
echo " (This will take 10-15 minutes - progress shown below)"
echo ""
# Deploy with live output and auto-update flag
agentcore deploy --auto-update-on-conflict
if [ $? -ne 0 ]; then
echo -e "${RED}Error: Supervisor deployment failed${NC}"
cd "$SCRIPT_DIR"
exit 1
fi
# Get ARN from AWS API (more reliable than parsing agentcore status output)
SUPERVISOR_ARN=$(aws bedrock-agentcore-control list-agent-runtimes --region "$REGION" --output json | \
jq -r '.agentRuntimes[] | select(.agentRuntimeName == "msp_supervisor_agent") | .agentRuntimeArn')
if [ -z "$SUPERVISOR_ARN" ] || [ "$SUPERVISOR_ARN" = "null" ]; then
echo -e "${RED}Error: Could not get Supervisor Runtime ARN from AWS${NC}"
echo " Supervisor may not have deployed successfully"
cd "$SCRIPT_DIR"
exit 1
fi
# Validate ARN is complete (not truncated)
if [ ${#SUPERVISOR_ARN} -lt 70 ]; then
echo -e "${RED}Error: Supervisor ARN appears truncated: $SUPERVISOR_ARN${NC}"
echo " Expected length >70 chars, got ${#SUPERVISOR_ARN}"
cd "$SCRIPT_DIR"
exit 1
fi
tag_agentcore_resource "$SUPERVISOR_ARN" "Supervisor runtime"
echo ""
echo "✓ Supervisor Runtime deployed"
echo " Runtime ARN: $SUPERVISOR_ARN"
# Return to project root
cd "$SCRIPT_DIR"
# Save Supervisor ARN to backend/.env (MEMORY_ID will be written after CDK in Step 5)
if [ -f "backend/.env" ]; then
# Update SUPERVISOR_RUNTIME_ARN
if grep -q "^SUPERVISOR_RUNTIME_ARN=" backend/.env 2>/dev/null; then
# Update existing line
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' "s|^SUPERVISOR_RUNTIME_ARN=.*|SUPERVISOR_RUNTIME_ARN=$SUPERVISOR_ARN|" backend/.env
else
sed -i "s|^SUPERVISOR_RUNTIME_ARN=.*|SUPERVISOR_RUNTIME_ARN=$SUPERVISOR_ARN|" backend/.env
fi
else
# Append new line
echo "" >> backend/.env
echo "# Supervisor Runtime ARN (Added by deploy.sh)" >> backend/.env
echo "SUPERVISOR_RUNTIME_ARN=$SUPERVISOR_ARN" >> backend/.env
fi
echo "✓ Supervisor ARN saved to backend/.env"
fi
# Update CDK outputs.json with real Supervisor ARN
echo " Updating CDK outputs.json..."
cd infrastructure/cdk
# Ensure outputs.json exists (first deploy won't have it yet)
[ -f outputs.json ] || echo '{}' > outputs.json
# Add SupervisorRuntimeARN to MSPAssistantAgentCoreStack
jq --arg arn "$SUPERVISOR_ARN" \
'.MSPAssistantAgentCoreStack.SupervisorRuntimeARN = $arn' \
outputs.json > outputs.tmp.json && mv outputs.tmp.json outputs.json
if [ $? -eq 0 ]; then
echo "✓ Supervisor ARN saved to CDK outputs"
echo " ARN: $SUPERVISOR_ARN"
echo ""
echo "✅ CDK will now read REAL Runtime ARN (not placeholder)"
else
echo -e "${YELLOW}⚠️ Warning: Could not update outputs.json with Supervisor ARN${NC}"
fi
cd "$SCRIPT_DIR"
echo ""
# Step 4b: Create Gateway Execution Role (BEFORE CDK)
echo -e "${YELLOW}[4b/14] Creating Gateway execution role...${NC}"
echo ""
echo "⚠️ CRITICAL: Gateway role must exist BEFORE CDK creates the gateway"
echo " CDK will use msp-gateway-execution-role when creating the gateway"
echo ""
GATEWAY_ROLE_NAME="msp-gateway-execution-role"
ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' --output text --region "$REGION")
echo "Creating/verifying gateway execution role: $GATEWAY_ROLE_NAME"
aws iam create-role \
--role-name "$GATEWAY_ROLE_NAME" \
--assume-role-policy-document '{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Principal":{"Service":"bedrock-agentcore.amazonaws.com"},
"Action":"sts:AssumeRole"
}]
}' >/dev/null 2>&1 || true
aws iam put-role-policy \
--role-name "$GATEWAY_ROLE_NAME" \
--policy-name AgentCoreAccess \
--policy-document "{
\"Version\":\"2012-10-17\",
\"Statement\":[
{\"Sid\":\"InvokeGateway\",\"Effect\":\"Allow\",\"Action\":[\"bedrock-agentcore:InvokeGateway\"],\"Resource\":\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:gateway/*\"},
{\"Sid\":\"InvokeMCPRuntimes\",\"Effect\":\"Allow\",\"Action\":\"bedrock-agentcore:InvokeAgentRuntime\",\"Resource\":\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:runtime/*\"},
{\"Sid\":\"WorkloadIdentity\",\"Effect\":\"Allow\",\"Action\":[\"bedrock-agentcore:GetWorkloadAccessToken\",\"bedrock-agentcore:GetResourceOauth2Token\",\"bedrock-agentcore:GetResourceApiKey\"],\"Resource\":[\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:workload-identity-directory/default\",\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:workload-identity-directory/default/workload-identity/*\"]},
{\"Sid\":\"TokenVault\",\"Effect\":\"Allow\",\"Action\":[\"bedrock-agentcore:GetResourceOauth2Token\",\"bedrock-agentcore:GetResourceApiKey\"],\"Resource\":\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:token-vault/*\"},
{\"Sid\":\"GetSecretValue\",\"Effect\":\"Allow\",\"Action\":[\"secretsmanager:GetSecretValue\"],\"Resource\":\"arn:aws:secretsmanager:${REGION}:${ACCOUNT_ID}:secret:bedrock-agentcore-identity*\"}
]
}" >/dev/null 2>&1
tag_iam_role "$GATEWAY_ROLE_NAME"
# Attach CLI caller's managed policies to gateway role
echo " Attaching CLI caller's managed policies to gateway role..."
CLI_MANAGED_POLICIES=$(get_cli_managed_policies)
if [ -n "$CLI_MANAGED_POLICIES" ]; then
for POLICY_ARN in $CLI_MANAGED_POLICIES; do
POLICY_NAME=$(echo "$POLICY_ARN" | awk -F'/' '{print $NF}')
aws iam attach-role-policy --role-name "$GATEWAY_ROLE_NAME" --policy-arn "$POLICY_ARN" --region "$REGION" >/dev/null 2>&1 && \
echo " ✓ Attached $POLICY_NAME" || echo " ⚠️ Failed to attach $POLICY_NAME"
done
else
echo " ⚠️ No managed policies found for CLI caller"
fi
echo " ✓ Gateway execution role ready: $GATEWAY_ROLE_NAME"
echo " Waiting for IAM propagation..."
sleep 10
echo ""
# Pre-build frontend only when the optional UI stack is enabled.
# (Real build with correct env vars happens at Step 12 after CDK outputs are available)
if [ "$ENABLE_FRONTEND" = "true" ] && [ ! -d "frontend/dist" ]; then
echo "Pre-building frontend for CDK asset bundling..."
cd frontend && npm install && npx vite build && cd "$SCRIPT_DIR"
echo "✓ Frontend pre-built"
else
echo "✓ Frontend pre-build skipped (ENABLE_FRONTEND=$ENABLE_FRONTEND)"
fi
# API Gateway requires an account-level CloudWatch Logs role before a stage can
# enable execution logging. CDK also models this, but setting it before deploy
# avoids first-deploy ordering and propagation failures.
echo "Configuring API Gateway CloudWatch Logs role..."
APIGW_LOGS_ROLE_NAME="automatick-apigateway-cloudwatch-logs-role"
APIGW_LOGS_TRUST_POLICY='{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"apigateway.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
APIGW_LOGS_ROLE_ARN=$(aws iam get-role \
--role-name "$APIGW_LOGS_ROLE_NAME" \
--query 'Role.Arn' \
--output text 2>/dev/null || true)
if [ -z "$APIGW_LOGS_ROLE_ARN" ] || [ "$APIGW_LOGS_ROLE_ARN" = "None" ]; then
echo " Creating role: $APIGW_LOGS_ROLE_NAME"
APIGW_LOGS_ROLE_ARN=$(aws iam create-role \
--role-name "$APIGW_LOGS_ROLE_NAME" \
--assume-role-policy-document "$APIGW_LOGS_TRUST_POLICY" \
--query 'Role.Arn' \
--output text)
fi
aws iam wait role-exists --role-name "$APIGW_LOGS_ROLE_NAME"
tag_iam_role "$APIGW_LOGS_ROLE_NAME"
aws iam update-assume-role-policy \
--role-name "$APIGW_LOGS_ROLE_NAME" \
--policy-document "$APIGW_LOGS_TRUST_POLICY" >/dev/null
aws iam attach-role-policy \
--role-name "$APIGW_LOGS_ROLE_NAME" \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs >/dev/null 2>&1 || true
echo " Waiting for IAM role trust/policy propagation..."
sleep 30
aws apigateway update-account \
--patch-operations op=replace,path=/cloudwatchRoleArn,value="$APIGW_LOGS_ROLE_ARN" \
--region "$REGION" >/dev/null
echo "✓ API Gateway CloudWatch Logs role configured: $APIGW_LOGS_ROLE_ARN"
echo " Waiting for API Gateway account setting propagation..."
sleep 10
# Step 5: Deploy CDK stacks (READS outputs.json WITH REAL ARN)
echo -e "${YELLOW}[5/14] Deploying CDK infrastructure...${NC}"
echo ""
echo "CDK will read SupervisorRuntimeARN from outputs.json"
echo "ECS task definition will be created with correct ARN from start"
echo ""
# On redeployments, export FRONTEND_URL from previous outputs so CDK bakes the CloudFront
# URL into API Gateway CORS headers instead of falling back to localhost.
if [ "$ENABLE_FRONTEND" = "true" ] && [ -f "infrastructure/cdk/outputs.json" ]; then
EXISTING_FRONTEND_URL=$(jq -r '.MSPAssistantFrontendStack.FrontendURL // empty' infrastructure/cdk/outputs.json 2>/dev/null)
if [ -n "$EXISTING_FRONTEND_URL" ] && [ "$EXISTING_FRONTEND_URL" != "null" ]; then
export FRONTEND_URL="$EXISTING_FRONTEND_URL"
echo " Re-deploy detected: using existing CloudFront URL for CORS: $FRONTEND_URL"
fi
fi
cd infrastructure/cdk
# Install dependencies
"$CDK_PYTHON" -m pip install -r requirements.txt
# Bootstrap if needed
cdk bootstrap "aws://$ACCOUNT_ID/$REGION"
# Get ALB DNS from previous outputs if this is a redeploy (for SSE streaming CloudFront behavior).
# On a fresh deploy outputs.json doesn't exist yet, so this will be empty — FrontendStack
# handles alb_dns="" gracefully by skipping the ALB origin. We add it in a second pass below.
ALB_DNS_FOR_CDK=""
if [ "$ENABLE_FRONTEND" = "true" ]; then
ALB_DNS_FOR_CDK=$(jq -r '.MSPAssistantBackendStack.ALBEndpoint // empty' outputs.json 2>/dev/null || true)
fi
# Deploy all stacks — pass Supervisor ARN and ALB DNS via context
cdk deploy --all --require-approval never --outputs-file outputs.json \
--context region="$REGION" \
--context account="$ACCOUNT_ID" \
--context supervisor_runtime_arn="$SUPERVISOR_ARN" \
--context enable_frontend="$ENABLE_FRONTEND" \
--context alb_dns="${ALB_DNS_FOR_CDK}"
# On fresh deploy alb_dns was empty above, so FrontendStack was created without the
# ALB SSE origin. Now that BackendStack is deployed we have the ALB DNS — re-deploy
# FrontendStack to add it. On redeployments this is a no-op (ALB origin already set).
ALB_DNS_FROM_NEW_OUTPUTS=$(jq -r '.MSPAssistantBackendStack.ALBEndpoint // empty' outputs.json 2>/dev/null || true)
if [ "$ENABLE_FRONTEND" = "true" ] && [ -n "$ALB_DNS_FROM_NEW_OUTPUTS" ] && [ "$ALB_DNS_FROM_NEW_OUTPUTS" != "$ALB_DNS_FOR_CDK" ]; then
echo " Updating FrontendStack with ALB SSE origin ($ALB_DNS_FROM_NEW_OUTPUTS)..."
cdk deploy MSPAssistantFrontendStack --require-approval never \
--context region="$REGION" \
--context account="$ACCOUNT_ID" \
--context enable_frontend="$ENABLE_FRONTEND" \
--context alb_dns="$ALB_DNS_FROM_NEW_OUTPUTS"
echo " ✓ FrontendStack updated with ALB SSE origin"
fi
# Parse outputs with validation
MEMORY_ID=$(jq -r '.MSPAssistantAgentCoreStack.MemoryId // empty' outputs.json)
GATEWAY_ARN=$(jq -r '.MSPAssistantAgentCoreStack.GatewayARN // empty' outputs.json)
ECR_REPO_URI=$(jq -r '.MSPAssistantBackendStack.ECRRepositoryUri // empty' outputs.json)
# Validate critical outputs
if [ -z "$MEMORY_ID" ] || [ "$MEMORY_ID" = "null" ]; then
echo -e "${RED}Error: Failed to get Memory ID from CDK outputs${NC}"
exit 1
fi
if [ -z "$GATEWAY_ARN" ] || [ "$GATEWAY_ARN" = "null" ]; then
echo -e "${RED}Error: Failed to get Gateway ARN from CDK outputs${NC}"
exit 1
fi
echo "✓ CDK stacks deployed"
echo " Memory ID: $MEMORY_ID"
echo " Gateway ARN: $GATEWAY_ARN"
echo " Supervisor ARN: $(jq -r '.MSPAssistantAgentCoreStack.SupervisorRuntimeARN // empty' outputs.json)"
cd "$SCRIPT_DIR"
# Update backend/.env with all infrastructure values from CDK
echo ""
echo "Updating backend/.env with infrastructure values..."
if [ -f "backend/.env" ]; then
# Helper function for sed (macOS vs Linux)
update_env_var() {
local var_name=$1
local var_value=$2
if grep -q "^${var_name}=" backend/.env 2>/dev/null; then
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' "s|^${var_name}=.*|${var_name}=${var_value}|" backend/.env
else
sed -i "s|^${var_name}=.*|${var_name}=${var_value}|" backend/.env
fi
else
# Ensure file ends with newline before appending
[ -n "$(tail -c1 backend/.env)" ] && echo "" >> backend/.env
echo "${var_name}=${var_value}" >> backend/.env
fi
}
# Get additional values from CDK outputs
GATEWAY_URL_FROM_CDK=$(jq -r '.MSPAssistantAgentCoreStack.GatewayURL // empty' infrastructure/cdk/outputs.json)
USER_POOL_ID_FROM_CDK=$(jq -r '.MSPAssistantBackendStack.CognitoUserPoolId // empty' infrastructure/cdk/outputs.json)
CLIENT_ID_FROM_CDK=$(jq -r '.MSPAssistantBackendStack.CognitoWebClientId // empty' infrastructure/cdk/outputs.json)
# Update all infrastructure values
update_env_var "MEMORY_ID" "$MEMORY_ID"
update_env_var "GATEWAY_ARN" "$GATEWAY_ARN"
[ -n "$GATEWAY_URL_FROM_CDK" ] && update_env_var "GATEWAY_URL" "$GATEWAY_URL_FROM_CDK"
[ -n "$USER_POOL_ID_FROM_CDK" ] && update_env_var "COGNITO_USER_POOL_ID" "$USER_POOL_ID_FROM_CDK"
[ -n "$CLIENT_ID_FROM_CDK" ] && update_env_var "COGNITO_CLIENT_ID" "$CLIENT_ID_FROM_CDK"
echo "✓ All infrastructure values saved to backend/.env"
echo " MEMORY_ID: $MEMORY_ID"
echo " GATEWAY_ARN: $GATEWAY_ARN"
echo " GATEWAY_URL: $GATEWAY_URL_FROM_CDK"
fi
# Step 5b: Create AgentCore OAuth credential provider for Gateway→MCP auth
echo ""
echo -e "${YELLOW}[5b/14] Creating OAuth credential provider (Gateway→MCP)...${NC}"
# Read M2M Cognito outputs from CDK
M2M_CLIENT_ID=$(jq -r '.MSPAssistantBackendStack.CognitoM2MClientId // empty' infrastructure/cdk/outputs.json)
COGNITO_TOKEN_ENDPOINT=$(jq -r '.MSPAssistantBackendStack.CognitoTokenEndpoint // empty' infrastructure/cdk/outputs.json)
USER_POOL_ID_FOR_M2M=$(jq -r '.MSPAssistantBackendStack.CognitoUserPoolId // empty' infrastructure/cdk/outputs.json)
if [ -z "$M2M_CLIENT_ID" ] || [ "$M2M_CLIENT_ID" = "null" ]; then
echo -e "${RED}Error: M2M Client ID not found in CDK outputs${NC}"
exit 1
fi
# Retrieve M2M client secret via AWS CLI (CDK can't output secrets)
M2M_CLIENT_SECRET=$(aws cognito-idp describe-user-pool-client \
--user-pool-id "$USER_POOL_ID_FOR_M2M" \
--client-id "$M2M_CLIENT_ID" \
--region "$REGION" \
--query 'UserPoolClient.ClientSecret' --output text 2>/dev/null)
if [ -z "$M2M_CLIENT_SECRET" ] || [ "$M2M_CLIENT_SECRET" = "None" ]; then
echo -e "${RED}Error: Could not retrieve M2M client secret${NC}"
exit 1
fi
COGNITO_ISSUER="https://cognito-idp.${REGION}.amazonaws.com/${USER_POOL_ID_FOR_M2M}"
# Check if OAuth provider already exists
EXISTING_OAUTH=$(aws bedrock-agentcore-control get-oauth2-credential-provider \
--name msp-gateway-cognito --region "$REGION" --output json 2>/dev/null || true)
if [ -n "$EXISTING_OAUTH" ] && echo "$EXISTING_OAUTH" | jq -e '.name' >/dev/null 2>&1; then
echo "✓ OAuth provider 'msp-gateway-cognito' already exists"
# Check if client ID matches current M2M client
EXISTING_CLIENT_ID=$(echo "$EXISTING_OAUTH" | jq -r '.oauth2ProviderConfigOutput.includedOauth2ProviderConfig.clientId // empty')
if [ "$EXISTING_CLIENT_ID" != "$M2M_CLIENT_ID" ]; then
echo " ⚠️ Client ID mismatch detected (existing: $EXISTING_CLIENT_ID, expected: $M2M_CLIENT_ID)"
echo " Deleting and recreating OAuth provider with correct client..."
# Delete with error suppression
aws bedrock-agentcore-control delete-oauth2-credential-provider \
--name msp-gateway-cognito \
--region "$REGION" >/dev/null 2>&1 || true
echo " Waiting for deletion to propagate (Secrets Manager eventual consistency)..."
sleep 15
echo " Creating OAuth provider with correct M2M client..."
# Retry loop for eventual consistency
OAUTH_CREATED=false
for attempt in 1 2 3 4; do
if aws bedrock-agentcore-control create-oauth2-credential-provider \
--name msp-gateway-cognito \
--region "$REGION" \
--credential-provider-vendor CustomOauth2 \
--oauth2-provider-config-input "{
\"customOauth2ProviderConfig\": {
\"oauthDiscovery\": {
\"discoveryUrl\": \"${COGNITO_ISSUER}/.well-known/openid-configuration\"
},
\"clientId\": \"${M2M_CLIENT_ID}\",
\"clientSecret\": \"${M2M_CLIENT_SECRET}\"
}
}" >/dev/null 2>&1; then
OAUTH_CREATED=true
echo " ✓ OAuth provider recreated with correct client"
break
else
echo " Attempt $attempt failed (Secrets Manager conflict), retrying in 10s..."
sleep 10
fi
done
if [ "$OAUTH_CREATED" = false ]; then
echo -e "${RED}Error: Failed to create OAuth provider after 4 attempts${NC}"
echo " This is likely due to Secrets Manager eventual consistency."
echo " Wait 30 seconds and re-run deploy.sh to continue."
exit 1
fi
else
echo " ✓ Client ID matches, no update needed"
fi
else
echo "Creating OAuth provider 'msp-gateway-cognito'..."
# Retry loop for eventual consistency (in case of previous failed delete)
OAUTH_CREATED=false
for attempt in 1 2 3; do
if aws bedrock-agentcore-control create-oauth2-credential-provider \
--name msp-gateway-cognito \
--region "$REGION" \
--credential-provider-vendor CustomOauth2 \
--oauth2-provider-config-input "{
\"customOauth2ProviderConfig\": {
\"oauthDiscovery\": {
\"discoveryUrl\": \"${COGNITO_ISSUER}/.well-known/openid-configuration\"
},
\"clientId\": \"${M2M_CLIENT_ID}\",
\"clientSecret\": \"${M2M_CLIENT_SECRET}\"
}
}" >/dev/null 2>&1; then
OAUTH_CREATED=true
echo "✓ OAuth provider created"
break
else
if [ $attempt -lt 3 ]; then
echo " Attempt $attempt failed, retrying in 10s..."
sleep 10
fi
fi
done
if [ "$OAUTH_CREATED" = false ]; then
echo -e "${RED}Error: Failed to create OAuth provider after 3 attempts${NC}"
exit 1
fi
fi
echo " Issuer: $COGNITO_ISSUER"
echo " Client ID: $M2M_CLIENT_ID"
# Build JWT authorizer config for MCP runtimes (used during agentcore configure)
DISCOVERY_URL="${COGNITO_ISSUER}/.well-known/openid-configuration"
JWT_AUTH_CONFIG=$(jq -n \
--arg url "$DISCOVERY_URL" \
--arg client "$M2M_CLIENT_ID" \
'{customJWTAuthorizer:{discoveryUrl:$url,allowedClients:[$client],allowedScopes:["mcp-server/invoke"]}}')
echo " JWT authorizer config built for MCP deploys"
echo ""
# Step 6: Deploy MCP Servers to AgentCore Runtime
echo -e "${YELLOW}[6/14] Deploying MCP servers to AgentCore Runtime...${NC}"
echo ""
echo "This will deploy 3 MCP servers (~30-45 minutes total):"
echo " 1. CloudWatch MCP (~10-15 min)"
echo " 2. AWS API MCP (~10-15 min)"
echo " 3. AWS Knowledge MCP (~10-15 min)"
echo ""
# Helper: deploy one MCP server, extract ARN
deploy_mcp_server() {
local MCP_NAME="$1"
local MCP_ENTRY="$2"
local MCP_DIR="$3"
echo " Deploying ${MCP_NAME}..." >&2
cd "$MCP_DIR"
cp "$SCRIPT_DIR/mcp-servers/common/credential_helper.py" . 2>/dev/null || true
rm -f .bedrock_agentcore.yaml env_config.txt
cat > env_config.txt << ENVEOF
# Auto-generated by deploy.sh
AWS_REGION=$REGION
BEDROCK_KNOWLEDGE_BASE_ID=${BEDROCK_KNOWLEDGE_BASE_ID:-}
ENVEOF
agentcore configure -e "$MCP_ENTRY" --protocol MCP --name "$MCP_NAME" \
--idle-timeout 1800 --max-lifetime 14400 --non-interactive \
--requirements-file requirements.txt \
--region "$REGION" \
-ac "$JWT_AUTH_CONFIG" >&2
if [ $? -ne 0 ]; then
echo -e "${RED}Error: ${MCP_NAME} configuration failed${NC}" >&2
cd "$SCRIPT_DIR"; exit 1
fi
agentcore deploy --auto-update-on-conflict >&2
if [ $? -ne 0 ]; then
echo -e "${RED}Error: ${MCP_NAME} deployment failed${NC}" >&2
cd "$SCRIPT_DIR"; exit 1
fi
local ARN=$(agentcore status 2>&1 | grep "Agent ARN:" -A 1 | grep "arn:aws" | grep -oE 'arn:aws:bedrock-agentcore:[^[:space:]]+' | head -1)
if [ -z "$ARN" ]; then
echo -e "${RED}Error: Could not get ${MCP_NAME} Runtime ARN${NC}" >&2
cd "$SCRIPT_DIR"; exit 1
fi
tag_agentcore_resource "$ARN" "${MCP_NAME} runtime" >&2
echo " ✓ ${MCP_NAME} deployed: $ARN" >&2
cd "$SCRIPT_DIR"
echo "$ARN"
}
CLOUDWATCH_ARN=$(deploy_mcp_server "cloudwatch_mcp" "cloudwatch_mcp.py" "$SCRIPT_DIR/mcp-servers/cloudwatch")
AWS_API_ARN=$(deploy_mcp_server "aws_api_mcp" "aws_api_mcp.py" "$SCRIPT_DIR/mcp-servers/aws-api")
KNOWLEDGE_ARN=$(deploy_mcp_server "aws_knowledge_mcp" "knowledge_mcp.py" "$SCRIPT_DIR/mcp-servers/aws-knowledge")
# JWT authorizer is now set during agentcore configure (via -ac flag above)
# No post-deploy patch needed.
echo ""
echo "✓ All MCP servers deployed to AgentCore Runtime"
echo " CloudWatch: $CLOUDWATCH_ARN"
echo " AWS API: $AWS_API_ARN"
echo " Knowledge: $KNOWLEDGE_ARN"
echo ""
# Step 7: Create AgentCore Gateway & Register MCP Targets
echo -e "${YELLOW}[7/14] Creating AgentCore Gateway...${NC}"
echo ""
# Define gateway role variables (used in both new and existing gateway paths)
GATEWAY_ROLE_NAME="msp-gateway-execution-role"
ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' --output text --region "$REGION")
GATEWAY_ROLE_ARN="arn:aws:iam::${ACCOUNT_ID}:role/${GATEWAY_ROLE_NAME}"
# CRITICAL FIX: Create gateway execution role BEFORE checking if gateway exists
# This ensures the role is always present, whether gateway is new or existing
echo "Creating/verifying gateway execution role..."
aws iam create-role \
--role-name "$GATEWAY_ROLE_NAME" \
--assume-role-policy-document '{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Principal":{"Service":"bedrock-agentcore.amazonaws.com"},
"Action":"sts:AssumeRole"
}]
}' >/dev/null 2>&1 || true
aws iam put-role-policy \
--role-name "$GATEWAY_ROLE_NAME" \
--policy-name AgentCoreAccess \
--policy-document "{
\"Version\":\"2012-10-17\",
\"Statement\":[
{\"Sid\":\"InvokeGateway\",\"Effect\":\"Allow\",\"Action\":[\"bedrock-agentcore:InvokeGateway\"],\"Resource\":\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:gateway/*\"},
{\"Sid\":\"InvokeMCPRuntimes\",\"Effect\":\"Allow\",\"Action\":\"bedrock-agentcore:InvokeAgentRuntime\",\"Resource\":\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:runtime/*\"},
{\"Sid\":\"WorkloadIdentity\",\"Effect\":\"Allow\",\"Action\":[\"bedrock-agentcore:GetWorkloadAccessToken\",\"bedrock-agentcore:GetResourceOauth2Token\",\"bedrock-agentcore:GetResourceApiKey\"],\"Resource\":[\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:workload-identity-directory/default\",\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:workload-identity-directory/default/workload-identity/*\"]},
{\"Sid\":\"TokenVault\",\"Effect\":\"Allow\",\"Action\":[\"bedrock-agentcore:GetResourceOauth2Token\",\"bedrock-agentcore:GetResourceApiKey\"],\"Resource\":\"arn:aws:bedrock-agentcore:${REGION}:${ACCOUNT_ID}:token-vault/*\"},
{\"Sid\":\"GetSecretValue\",\"Effect\":\"Allow\",\"Action\":[\"secretsmanager:GetSecretValue\"],\"Resource\":\"arn:aws:secretsmanager:${REGION}:${ACCOUNT_ID}:secret:bedrock-agentcore-identity*\"}
]
}" >/dev/null 2>&1
tag_iam_role "$GATEWAY_ROLE_NAME"
# Attach CLI caller's managed policies to gateway role
echo " Attaching CLI caller's managed policies to gateway role..."
CLI_MANAGED_POLICIES=$(get_cli_managed_policies)
if [ -n "$CLI_MANAGED_POLICIES" ]; then
for POLICY_ARN in $CLI_MANAGED_POLICIES; do
POLICY_NAME=$(echo "$POLICY_ARN" | awk -F'/' '{print $NF}')
aws iam attach-role-policy --role-name "$GATEWAY_ROLE_NAME" --policy-arn "$POLICY_ARN" --region $REGION >/dev/null 2>&1 && \
echo " ✓ Attached $POLICY_NAME" || echo " ⚠️ Failed to attach $POLICY_NAME"
done
else
echo " ⚠️ No managed policies found for CLI caller"
fi
echo " ✓ Gateway execution role ready: $GATEWAY_ROLE_NAME"
sleep 10 # Allow IAM propagation
# Now discover existing gateway from CDK outputs or by listing
GATEWAY_ARN_FROM_CDK=$(jq -r '.MSPAssistantAgentCoreStack.GatewayARN // empty' infrastructure/cdk/outputs.json 2>/dev/null)
if [ -n "$GATEWAY_ARN_FROM_CDK" ] && [ "$GATEWAY_ARN_FROM_CDK" != "null" ]; then
GATEWAY_ID=$(echo "$GATEWAY_ARN_FROM_CDK" | awk -F'/' '{print $NF}')
echo "✓ Found gateway from CDK outputs: $GATEWAY_ID"
else
GATEWAY_ID=$(aws bedrock-agentcore-control list-gateways --region $REGION \
--query "items[?status=='READY'] | [0].gatewayId" --output text 2>/dev/null)
fi
if [ -z "$GATEWAY_ID" ] || [ "$GATEWAY_ID" = "None" ] || [ "$GATEWAY_ID" = "null" ]; then
echo "No existing gateway found. Creating new one..."
GATEWAY_RESPONSE=$(aws bedrock-agentcore-control create-gateway \
--name "msp-assistant-gateway" \
--description "Unified MCP endpoint for MSP Ops agents" \
--role-arn "$GATEWAY_ROLE_ARN" \
--protocol-type MCP \
--authorizer-type AWS_IAM \
--tags "$PROJECT_TAG_MAP" \
--region $REGION --output json 2>&1)
GATEWAY_ID=$(echo "$GATEWAY_RESPONSE" | jq -r '.gatewayId // empty')
if [ -z "$GATEWAY_ID" ]; then
echo -e "${RED}✗ Gateway creation failed: $GATEWAY_RESPONSE${NC}"
else
echo "✓ Gateway created: $GATEWAY_ID"
echo " Waiting for READY status..."
for i in $(seq 1 30); do
GW_STATUS=$(aws bedrock-agentcore-control get-gateway --gateway-identifier $GATEWAY_ID \
--region $REGION --query 'status' --output text 2>/dev/null)
if [ "$GW_STATUS" = "READY" ]; then break; fi
sleep 10
done
fi
else
# Gateway already exists - update its role to use the proper execution role
echo "✓ Gateway already exists: $GATEWAY_ID"
echo " Updating gateway role to: $GATEWAY_ROLE_ARN"
aws bedrock-agentcore-control update-gateway \
--gateway-identifier "$GATEWAY_ID" \
--name "msp-assistant-gateway" \
--protocol-type MCP \
--authorizer-type AWS_IAM \
--role-arn "$GATEWAY_ROLE_ARN" \
--region $REGION >/dev/null 2>&1 && \
echo " ✓ Gateway role updated" || echo " ⚠️ Gateway role update failed"
echo " Waiting for READY status..."
for i in $(seq 1 30); do
GW_STATUS=$(aws bedrock-agentcore-control get-gateway --gateway-identifier $GATEWAY_ID \
--region $REGION --query 'status' --output text 2>/dev/null)
if [ "$GW_STATUS" = "READY" ]; then break; fi
sleep 5
done
fi
if [ -n "$GATEWAY_ID" ] && [ "$GATEWAY_ID" != "None" ]; then
GATEWAY_URL=$(aws bedrock-agentcore-control get-gateway \
--gateway-identifier $GATEWAY_ID --region $REGION \
--query 'gatewayUrl' --output text 2>/dev/null)
GATEWAY_ARN=$(aws bedrock-agentcore-control get-gateway \
--gateway-identifier $GATEWAY_ID --region $REGION \
--query 'gatewayArn' --output text 2>/dev/null)
tag_agentcore_resource "$GATEWAY_ARN" "AgentCore gateway"
echo " Gateway URL: $GATEWAY_URL"
# Discover OAuth credential provider ARN dynamically
MCP_OAUTH_ARN=$(aws bedrock-agentcore-control list-oauth2-credential-providers \
--region $REGION --query "credentialProviders[?name=='msp-gateway-cognito'].credentialProviderArn" \
--output text 2>/dev/null)
if [ -n "$MCP_OAUTH_ARN" ] && [ "$MCP_OAUTH_ARN" != "None" ]; then
echo " OAuth provider: $MCP_OAUTH_ARN"
MCP_CRED_CONFIG=$(jq -n --arg arn "$MCP_OAUTH_ARN" \
'[{credentialProviderType:"OAUTH",credentialProvider:{oauthCredentialProvider:{providerArn:$arn,scopes:["mcp-server/invoke"],grantType:"CLIENT_CREDENTIALS"}}}]')
# Helper: register one MCP runtime as a gateway target
register_mcp_target() {
local TARGET_NAME="$1"
local TARGET_DESC="$2"
local MCP_ARN="$3"
echo ""
echo " Registering $TARGET_NAME..."
local ESCAPED_ARN=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$MCP_ARN', safe=''))")
local ENDPOINT="https://bedrock-agentcore.${REGION}.amazonaws.com/runtimes/${ESCAPED_ARN}/invocations?qualifier=DEFAULT"
local TARGET_CONFIG=$(jq -n --arg ep "$ENDPOINT" '{mcp:{mcpServer:{endpoint:$ep}}}')
# Check if target already exists
local EXISTING_ID=$(aws bedrock-agentcore-control list-gateway-targets \
--gateway-identifier "$GATEWAY_ID" --region "$REGION" \
--query "items[?name=='${TARGET_NAME}'].targetId" --output text 2>/dev/null)
if [ -n "$EXISTING_ID" ] && [ "$EXISTING_ID" != "None" ]; then
# Delete and recreate to ensure clean sync (update doesn't always re-sync)
aws bedrock-agentcore-control delete-gateway-target \
--gateway-identifier "$GATEWAY_ID" --target-id "$EXISTING_ID" \
--region "$REGION" >/dev/null 2>&1
echo " Deleted stale target $EXISTING_ID, recreating..."
sleep 5
fi
aws bedrock-agentcore-control create-gateway-target \
--gateway-identifier "$GATEWAY_ID" \
--name "$TARGET_NAME" \
--description "$TARGET_DESC" \
--target-configuration "$TARGET_CONFIG" \
--credential-provider-configurations "$MCP_CRED_CONFIG" \
--region "$REGION" >/dev/null 2>&1 && echo " ✓ $TARGET_NAME created" || echo " ⚠️ $TARGET_NAME creation failed"
}
register_mcp_target "cloudwatch-mcp" "CloudWatch MCP - Official awslabs package" "$CLOUDWATCH_ARN"
register_mcp_target "aws-api-mcp" "AWS API MCP - Official awslabs package with call_aws and suggest_aws_commands" "$AWS_API_ARN"
register_mcp_target "aws-knowledge-mcp" "AWS Knowledge base search" "$KNOWLEDGE_ARN"
# Wait for all targets to sync
echo ""
echo " Waiting for gateway targets to sync..."
for i in $(seq 1 24); do
TARGETS_JSON=$(aws bedrock-agentcore-control list-gateway-targets \