What is MCP? MCP (Model Context Protocol) is a open-source standard for connecting AI application to external systems such as APIs, databases, software and etc.
But how to create and deploy MCP server so that we can access MCP server using MCP client? Here it is using AgentCore Runtime and AgentCore Gateway. This tutorial blog explained how to create and deploy receipt extraction MCP server on AgentCore Runtime then integrate with AgentCore Gateway.
This MCP server help you extract receipt photo information such as store name, purchase date and total/amount then write output of extract information to Amazon DynamoDB table and send email of output of extract information using Amazon SNS. Then test this MCP server with Langchain.
REQUIREMENTS :
- AWS account (or AWS credentials), you can sign up/sign in here
- Google Gemini account, you can sign up/sign in here
- Langchain.
The AWS services used by this MCP server such as :
| AWS service | Description |
|---|---|
| Amazon S3 | upload file from local to S3 and download file from S3 to receipt extraction MCP server processes. |
| AWS Secret Manager | store Gemini API Key and LLM inference in receipt extraction MCP server. |
| AgentCore Runtime, AgentCore Gateway and AgentCore Identity. | |
| AgentCore Starter Toolkit | quickly configure and deploy MCP server with several AWS services such as Amazon ECR, AWS CodeBuild, and AWS IAM. |
| Amazon Cognito | Authentication and authorization for AgentCore Identity. |
| Amazon DynamoDB | Write result of receipt extraction to NoSQL database. |
| Amazon SNS | Send email notification about result of receipt extraction. |
STEP-BY-STEP :
A. Creating Amazon S3 bucket, store Gemini API key in AWS Secret Manager, creating Amazon DynamoDB table and creating Amazon SNS topic/subs.
!pip install python-dotenv boto3
from google.colab import userdata
from dotenv import load_dotenv
import boto3
import json
import os
os.environ["AWS_ACCESS_KEY_ID"] = userdata.get('AWSACCESSKEY')
os.environ["AWS_SECRET_ACCESS_KEY"] = userdata.get('AWSSECRETKEY')
# Get Gemini API Key and email address
load_dotenv("geminiapikey.txt")
gemini = os.getenv("GEMINI_API_KEY")
gmail = os.getenv("EMAIL")
secret_name = "geminiapikey"
table_name = "receiptsExtraction"
topic_name = "receiptsExtractionEmail"
region = "us-west-2"
Use this code to create a Amazon S3 bucket.
s3 = boto3.client('s3', region)
s3.create_bucket(
Bucket="receipts-extraction",
CreateBucketConfiguration={
'LocationConstraint': region
}
)
print("This bucket is now available.")
Use this code to create Gemini API Key in AWS Secret Manager.
apikey = boto3.client('secretsmanager', region)
secret_dict = {"GEMINI_API_KEY": gemini}
response = apikey.create_secret(
Name=secret_name,
Description="Gemini API Key",
SecretString=json.dumps(secret_dict)
)
print("Gemini API Key is now stored.")
Use this code to create result of receipt extraction table in Amazon DynamoDB.
dynamodb = boto3.client('dynamodb', region)
table = dynamodb.create_table(
TableName=table_name,
KeySchema=[{'AttributeName': 'storeName', 'KeyType': 'HASH'}],
AttributeDefinitions=[{'AttributeName': 'storeName', 'AttributeType': 'S'}],
BillingMode='PAY_PER_REQUEST',
OnDemandThroughput={'MaxReadRequestUnits': 200,'MaxWriteRequestUnits': 200}
)
print("Receipt extraction table is now available and save output from MCP server.")
Use this code to create email notification about result of receipt extraction using Amazon SNS.
sns = boto3.client('sns', region)
topic = sns.create_topic(Name=topic_name)
topic_arn = topic['TopicArn']
# Subscribe email to topic but must open your inbox email and click 'Confirm Subscription'
sns.subscribe(
TopicArn=topic_arn,
Protocol="email",
Endpoint=gmail
)
print("Open your inbox with subject AWS Notification - Subscription Confirmation and click Confirm Subscription.")
B. MCP Server Development
This structure is very important for creating MCP server. Write Python code for MCP server receipt extraction with detailed explanation :
- receiptExtraction : Extract store name, purchase date and total/amount based this receipt photo with structure output using Google Gemini 2.5 Flash based ReceiptExtractionResult class format like this
class ReceiptExtractionResult(BaseModel):
"""Extracted receipt information."""
storeName: str = Field(description="Name of store or store name. Must uppercase.")
purchaseDate: str = Field(description="Purchase date with \"DD-MM-YYYY\" format date.")
total: float = Field(description="Total or amount. Number and (.) only without any such as $ or other currency.")
writeOutput : Write receipt extraction results to Amazon DynamoDB table.
sendEmail : Send email notification with receipt extraction results using Amazon SNS.
Create Amazon Cognito User Pool, Domain, Resource Server and User Pool Client for AgentCore Gateway and AgentCore Runtime Inbound Authentication. This step is so that user/application can access agent/tool in AgentCore Runtime or AgentCore Gateway.
Use this code to configure the AgentCore Runtime.
from bedrock_agentcore_starter_toolkit import Runtime
agentcore_runtime = Runtime()
region = "us-west-2"
agent_name = "gemini-mcp-server"
runtime = agentcore_runtime.configure(
entrypoint="mcp_server.py",
auto_create_execution_role=True,
auto_create_ecr=True,
requirements_file="requirements.txt",
region=region,
agent_name=agent_name,
protocol="MCP",
authorizer_configuration={
"customJWTAuthorizer": {
"allowedClients": [runtime_cognito_client_id],
"discoveryUrl": f"https://cognito-idp.{region}.amazonaws.com/{runtime_cognito_pool_id}/.well-known/openid-configuration",
}
}
)
runtime
Explaining the above code:
- from first row until second row means import and initialize AgentCore Runtime.
-
agentcore_runtime.configuremeans configure the AgentCore Runtime with entry point (MCP server Python code), create IAM role for Runtime, create ECR image, requirements (install libraries), region and agent name.
Use this code to launch AI agent to AgentCore Runtime. Wait up to one minute.
launch_result = agentcore_runtime.launch()
C. TROUBLESHOOTING / VERY IMPORTANT INFORMATION
After AgentCore Runtime is available then invoke MCP server and get error like this screenshot below.
Open CloudWatch Logs or AgentCore Observability to see what happened with this error.
Go to Amazon Bedrock AgentCore -> Agent runtime then click your agent name that already created. Click "Observability dashboard" or "Cloudwatch logs" to see this error.
This error is happened because DynamoDB and SNS action is not allowed in IAM role for Runtime.
Go to Amazon Bedrock AgentCore -> Agent runtime then click your agent name that already created.
Click "Version 1" then click IAM service role of Permissions (e.g. AmazonBedrockAgentCoreSDKRuntime-{region-name}-{random-number-letter}) like above screenshot.
Click IAM policy name that related (e.g. BedrockAgentCoreRuntimeExecutionPolicy-{your-agent-name}) like above screenshot.
Go to AWS Secret Manager, click secret name then copy Secret ARN of Gemini API Key.
Add your Secret ARN of Gemini API Key in resource of "secretsManager:GetSecretValue" action with this code :
arn:aws:secretsmanager:us-west-2:{aws_account_id}:secret:geminiapikey-{random-number-letter}
Then click Add new statement -> Write AWS services (S3, DynamoDB and SNS) -> Checklist All actions -> Add resource -> Click Next, click Save and and view the IAM policy after changing it.
OR Edit permission in this IAM policy and write this permission after Sid": "AwsJwtFederation row -> Click Next, click Save and view the IAM policy after changing it.
{
"Sid": "DynamoDB",
"Effect": "Allow",
"Action": [
"dynamodb:*"
],
"Resource": [
"arn:aws:dynamodb:us-west-2:{aws_account_id}:table/*"
]
},
{
"Sid": "AmazonSNS",
"Effect": "Allow",
"Action": [
"sns:*"
],
"Resource": [
"*"
]
},
{
"Sid": "S3",
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": [
"*"
]
}
D. AgentCore Gateway
Based AgentCore Gateway documentation, MCP server target type only support OAuth (client credentials) or M2M (machine-to-machine) auth. Based AgentCore Identity documentation, to using M2M auth need create a user pool, resource server, client credentials, and discovery URL configuration.
Create AgentCore Identity for Runtime Outbound Auth. This step is so that agent/tool can access Gateway target such as MCP server, OpenAPI/REST API, API Gateway, Lambda function.
Create AgentCore Gateway using Gateway User Pool. This step is to integrate MCP server on AgentCore Runtime to AgentCore Gateway.
Create MCP Server on AgentCore Runtime as a AgentCore Gateway target. This step is to invoke MCP server via Gateway target to Runtime.
Try invoke MCP Server using Langchain MCP Client.
CONCLUSION : Amazon Bedrock AgentCore Runtime can create MCP server and AgentCore Gateway can integrate between MCP server to gateway.
DOCUMENTATION :
GITHUB REPOSITORY : https://github.com/budionosanai/amazon-bedrock-agentcore-one-to-one/tree/main/mcp-server
Thank you,
Budi :)
Top comments (0)