iTranslated by AI
Running Local MCP in the Cloud: Insights from stdio to HTTP Conversion
Introduction
In my previous article "Integrating MCP Servers with AgentCore Gateway and Utilizing Semantic Search", I introduced a method for integrating multiple MCP servers using AgentCore Gateway. In that article, as an example of a private MCP server, I converted an AWS CDK MCP Server implemented as a stdio type to an HTTP type and built it as an endpoint with OAuth2 authentication.
In this article, I will explain the technical choices and details of the implementation, focusing on the conversion from stdio type to HTTP type.
Background: Why We Chose This Configuration
Requirement: Making a Practical stdio-type MCP Server HTTP
When verifying AgentCore Gateway, we had a requirement to confirm the operation of a private MCP server. While we could have created a simple HTTP endpoint ourselves, we wanted to use an actually usable MCP server to make the example more practical.
For this purpose, we chose the AWS CDK MCP Server. This is a practical MCP server that provides CDK best practices and code generation support, but it is implemented as a stdio-type MCP server. stdio-type MCP servers communicate JSON-RPC messages via standard input/output, which is convenient for local use.
However, AgentCore Gateway requires an HTTP endpoint accessible at a public address. Therefore, to use a stdio-type MCP server as a target for AgentCore Gateway, conversion to an HTTP-type MCP server was necessary.
Technical Choices: Lambda and OAuth2 Authentication
Since this implementation was for a proof of concept, we prioritized cost efficiency. Lambda functions are billed only for execution time, making them ideal for verification purposes. The advantage is that there are no costs during idle periods, compared to always-running EC2 instances or containers.
Additionally, a solution called run-model-context-protocol-servers-with-aws-lambda provided by AWS Labs was a decisive factor. This solution offers a wrapper to run stdio-type MCP servers in Lambda functions, eliminating the need to build one from scratch.
Regarding authentication, AgentCore Gateway imposes the following choices:
- OAuth 2.0 authentication
- No authentication
Since the goal was to simulate a private MCP server, OAuth 2.0 authentication was essential. However, Lambda function URLs only support IAM authentication, which cannot be used with AgentCore Gateway.
An alternative was to implement authentication within the Lambda function itself, but considering the purpose of a proof of concept, we wanted to avoid excessive custom implementation. Therefore, we adopted the following configuration:
- API Gateway (HTTP API) as the frontend
- OAuth 2.0 authentication delegated to API Gateway
- Token issuance using Cognito, a managed service
Cognito supports the Client Credentials flow required by AgentCore Gateway, making it the optimal choice for efficient implementation.
Architecture Overview
The architecture implemented in this project is as follows:
Legend:
- Solid line: Flow of HTTP requests
- Dashed line: Acquisition/reference of authentication information
Main Components:
- AgentCore Gateway: A gateway service that integrates multiple MCP servers
- Credential Provider: Manages OAuth2 authentication information (Client ID, Client Secret, Token Endpoint)
- Cognito User Pool: Issues OAuth 2.0 tokens
- API Gateway (HTTP API): Provides an HTTP endpoint and performs token validation
- Lambda Function: Wrapper for the stdio-type MCP server (handler.py + AWS CDK MCP Server)
Processing Flow
The following is the detailed sequence of how a request is processed:
Characteristics of the process:
Authentication Flow (Steps 2-5):
- AgentCore Gateway retrieves authentication information from the Credential Provider
- The Credential Provider centralizes management of authentication information, enabling reuse across multiple targets
- A token is obtained via the Client Credentials flow (no user intervention required for server-to-server authentication)
Access via API Gateway (Steps 6-8):
- At step 7, API Gateway validates the JWT token without querying Cognito
- The reason for using API Gateway instead of a Lambda function URL is the support for OAuth 2.0 authentication
Starting the stdio Server (Step 9):
- A new subprocess is started as the stdio-type MCP server for each request
- It is terminated after processing to ensure safe operation in a multi-tenant environment
Lambda Function Implementation
Using run-mcp-servers-with-aws-lambda, the Lambda function implementation is very simple:
import sys
from mcp.client.stdio import StdioServerParameters
from mcp_lambda import APIGatewayProxyEventV2Handler, StdioServerAdapterRequestHandler
## stdio server parameter settings
server_params = StdioServerParameters(
command=sys.executable,
args=[
"-m",
"awslabs.cdk_mcp_server.server",
],
)
## Initialize request handler and event handler
request_handler = StdioServerAdapterRequestHandler(server_params)
event_handler = APIGatewayProxyEventV2Handler(request_handler)
def handler(event, context):
return event_handler.handle(event, context)
This code performs the following:
Server Parameter Settings:
-
command: The Python interpreter to execute (sys.executablespecifies the current environment's Python) -
args: Startsawslabs.cdk_mcp_server.serveras a Python module- The
-moption runs the module - This executes the entry point of the AWS CDK MCP Server
- The
Request Handler Configuration:
-
StdioServerAdapterRequestHandler: Wraps the stdio server in a request/response format -
APIGatewayProxyEventV2Handler: Converts the API Gateway event format into a format the handler can understand
With this simple implementation, the stdio-type MCP server can process HTTP requests.
About Subprocess Launch per Request
stdio-type MCP servers have the following characteristics:
- Design assumes a single user: stdio type is designed to be used by a single user from startup to shutdown.
- State isolation is not considered: It is not designed to isolate or manage data and state for each user.
- Risks when shared: In HTTP-type MCP servers, multiple users share the same server (instance). If the same stdio process is shared, there is a risk of data mixing or unintended state changes between users.
Therefore, run-mcp-servers-with-aws-lambda adopts a design that launches and stops a subprocess for each request as the simplest and safest way to use it.
Startup Time Optimization
The AWS CDK MCP Server is intended to be run using uv, but using uv in Lambda would require downloading and installing dependency libraries at runtime, significantly increasing startup time.
To address this issue, we pre-install the dependency libraries into the Lambda execution environment to reduce startup time. This sacrifices some of uv's benefits (automatic dependency management), but is a necessary measure for practical use.
CDK Implementation:
const lambdaFunction = new lambda.Function(parent, 'Function', {
functionName: `${props.serverName}-mcp-server-${environmentName}`,
runtime: lambda.Runtime.PYTHON_3_12,
handler: 'handler.handler',
code: lambda.Code.fromAsset(props.codePath, {
bundling: {
image: lambda.Runtime.PYTHON_3_12.bundlingImage,
command: [
'bash', '-c',
'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output'
],
},
}),
timeout: cdk.Duration.seconds(60),
memorySize: 1024,
// ... other settings
});
Key points:
- Using the
bundlingoption to install dependencies before deployment -
pip install -r requirements.txt -t /asset-outputinstalls dependency libraries into the output directory -
cp -au . /asset-outputalso copies the source code
Dependency Definition:
requirements.txt explicitly lists the required packages:
mcp>=1.0.0
run-mcp-servers-with-aws-lambda>=0.4.0
awslabs-cdk-mcp-server>=1.0.0
With this approach, the Lambda function starts with the dependency libraries already installed, significantly reducing the subprocess startup time for each request.
OAuth2 Authentication Implementation
This section explains the OAuth2 authentication implementation in the following order:
- Cognito User Pool Setup
- Credential Provider Creation
- API Gateway Integration
- Gateway Target Registration
Cognito User Pool Setup:
Define the Cognito User Pool and resource server using CDK:
// User Pool
const userPool = new cognito.UserPool(this, 'McpUserPool', {
userPoolName: 'mcp-gateway-user-pool',
// ... other settings
});
// Define resource server
const resourceServer = userPool.addResourceServer('McpResourceServer', {
identifier: 'mcp-server',
scopes: [
{
scopeName: 'access',
scopeDescription: 'Access to MCP server',
},
],
});
// Create app client for Client Credentials
const userPoolClient = userPool.addClient('McpClient', {
generateSecret: true,
authFlows: {
userPassword: false,
userSrp: false,
custom: false,
},
oAuth: {
flows: {
clientCredentials: true,
},
scopes: [
cognito.OAuthScope.resourceServer(resourceServer,
resourceServer.scopes[0] // 'access' scope
),
],
},
});
Credential Provider Creation:
Create the OAuth2 Credential Provider that AgentCore Gateway will use. This allows the Gateway to automatically obtain and refresh tokens.
export function createOauth2CredentialProvider(
scope: Construct,
id: string,
props: CognitoOauth2CredentialProviderProps
): CognitoOauth2CredentialProviderResult {
const parent = new Construct(scope, id);
const providerName = props.name ?? 'OAuth2CredentialProvider';
// Build Cognito Discovery URL
const userPoolId = props.userPool.userPoolId;
const region = Stack.of(scope).region;
const discoveryUrl = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/openid-configuration`;
// Credential Provider creation parameters
const createParameters: any = {
name: providerName,
credentialProviderVendor: 'CustomOauth2',
oauth2ProviderConfigInput: {
customOauth2ProviderConfig: {
oauthDiscovery: {
discoveryUrl: discoveryUrl // OpenID Connect Discovery endpoint
},
clientId: props.userPoolClient.userPoolClientId, // OAuth2 client ID
clientSecret: props.userPoolClient.userPoolClientSecret.unsafeUnwrap(), // OAuth2 client secret (not embedded in CloudFormation template, referenced during deployment)
},
}
};
const onCreate: AwsSdkCall = {
service: 'bedrock-agentcore-control',
action: 'CreateOauth2CredentialProvider',
parameters: createParameters,
physicalResourceId: PhysicalResourceId.of(providerName),
};
// Create with AwsCustomResource
const customResource = new AwsCustomResource(parent, 'Resource', {
installLatestAwsSdk: true,
onCreate: onCreate,
onUpdate: { /* Update logic */ },
onDelete: { /* Delete logic */ },
policy: /* Required permissions */,
});
return {
customResource,
credentialProviderArn: customResource.getResponseField('credentialProviderArn'),
// ...
};
}
API Gateway Integration:
In API Gateway (HTTP API), the Cognito authorizer performs JWT validation on the token.
// Specify userPoolClients to enable proper token validation
const userPoolAuthorizer = new HttpUserPoolAuthorizer(
'CognitoAuthorizer',
userPool, // Cognito User Pool
{
userPoolClients: [userPoolClient], // Specify the client to validate
}
);
// HttpApi with default authorizer
const httpApi = new HttpApi(this, 'HttpApi', {
apiName: 'MCP Server HTTP API',
description: 'HTTP API for MCP Servers',
defaultAuthorizer: userPoolAuthorizer, // Apply authentication to all routes
});
// Lambda integration and route addition
const integration = new HttpLambdaIntegration(
'McpIntegration',
lambdaFunction // Lambda function wrapping the stdio MCP server
);
httpApi.addRoutes({
path: '/{proxy+}', // Proxy all paths
methods: [HttpMethod.ANY], // Allow all HTTP methods
integration: integration,
});
Gateway Target Registration:
Finally, register the Gateway Target using the created OAuth2 Credential Provider and API Gateway endpoint.
export function createMcpGatewayTarget(
scope: Construct,
id: string,
props: McpServerGatewayTargetProps
): McpServerGatewayTargetResult {
const parent = new Construct(scope, id);
const createParameters: any = {
gatewayIdentifier: props.gateway.attrGatewayIdentifier,
name: props.name,
targetConfiguration: {
mcp: {
mcpServer: {
endpoint: props.endpoint
}
}
},
};
// Add credential configuration
if (props.credentialConfig) {
createParameters.credentialProviderConfigurations = [{
credentialProviderType: 'OAUTH',
credentialProvider: {
oauthCredentialProvider: {
providerArn: props.credentialConfig.providerArn,
scopes: [props.credentialConfig.scope],
}
}
}];
}
const onCreate: AwsSdkCall = {
service: 'bedrock-agentcore-control',
action: 'CreateGatewayTarget',
parameters: createParameters,
physicalResourceId: PhysicalResourceId.fromResponse('targetId'),
};
// Create with AwsCustomResource
const customResource = new AwsCustomResource(parent, 'GatewayTarget', {
installLatestAwsSdk: true,
onCreate: onCreate,
onUpdate: { /* Update logic */ },
onDelete: { /* Delete logic */ },
policy: /* Required permissions */,
});
return {
customResource,
targetId: customResource.getResponseField('targetId'),
};
}
Summary:
In this article, we explained how to expose a stdio-type AWS CDK MCP server as an HTTP endpoint and implement OAuth2 authentication.
Key Points:
-
Converting stdio type to HTTP type: Using
run-mcp-servers-with-aws-lambda, launching it as a subprocess per request enables multi-tenant support -
Startup Time Optimization: Pre-installing dependency libraries, sacrificing some of
uv's convenience for performance - OAuth2 Authentication: Implementing the Client Credentials flow with Cognito and validating it via API Gateway
-
Token Validation Method: Validation via API Gateway's Cognito authorizer (since Client Credentials tokens lack the
audclaim)
This implementation allows converting a stdio-type MCP server to HTTP type and securely integrating it with AgentCore Gateway.
Outlook: Possibility of Migration from stdio Type to HTTP Type
In this article, we implemented the HTTP conversion of a stdio-type MCP server as a proof of concept, but this approach may become increasingly important in the future.
Challenges of stdio-type Servers in Local Environments:
As MCP servers become more widespread, the situation where multiple stdio-type MCP server processes are constantly running in local environments is increasing. Each MCP server operates as an independent process, exposing the following issues:
Resource Consumption Issues:
- Memory and CPU usage due to multiple server processes running residently
- Especially in development environments, scenarios where 10 or more MCP servers are running simultaneously can be expected
Management Complexity:
- Process startup, shutdown, and version management become cumbersome
- Conflicts between Python environments and library versions across different MCP servers
- As each server's dependencies increase, environment setup becomes more difficult
Cloud Offloading with HTTP Implementation:
The conversion method from stdio type to HTTP type implemented in this article can be one solution to these issues:
Resource Offloading:
- Running MCP servers on the cloud instead of the local environment
- Freeing up the development machine's resources for actual work
On-Demand Execution:
- The server starts only when needed and costs nothing when not in use (in the case of Lambda)
- Multiple developers can share the same HTTP-type MCP server
Centralized Management:
- Unified management and updates on the cloud
- The entire team can use the same version of the MCP server
Key to HTTP Type Adoption: Session Management
For the widespread adoption of HTTP-type MCP, it is important that AI agents also support the session management mechanism included in the MCP specification. With stdio type, state can be maintained within a single process, but with HTTP type, a stateless design is the norm, so a mechanism to maintain state across multiple requests is necessary. If AI agents can properly manage session IDs and maintain the same context across consecutive operations, complex workflows can be realized even with HTTP-type MCP servers.
Proposal for MCP Server Developers:
When developing and providing stdio-type MCP servers, offering an HTTP-type implementation as well can give users options:
- Lightweight local use: Easy trial and development with stdio type
- Full-scale use and integration: Deploy to the cloud with HTTP type and integrate with AgentCore Gateway
By combining with AgentCore Gateway's semantic search functionality, tools can be efficiently discovered and executed even in environments with hundreds of registered tools. The conversion method from stdio type to HTTP type will be an important option supporting the scalability of the MCP ecosystem.
Discussion