mcp-bedrock-client
v1.1.0
Published
A TypeScript SDK that implements a Model Context Protocol (MCP) client using AWS Bedrock models for tool orchestration
Maintainers
Readme
MCP Bedrock Client
A robust TypeScript SDK that implements a Model Context Protocol (MCP) client using AWS Bedrock models for intelligent tool orchestration and multi-turn conversations.
🚀 Features
- 🔌 MCP Protocol Support: Connect to any MCP server using WebSocket or stdio transport
- 🤖 AWS Bedrock Integration: Use any Bedrock model as the reasoning engine with automatic API detection
- 🔄 Multi-Turn Orchestration: Automatically chain multiple tool calls to answer complex queries
- 🛡️ Smart Iteration Control: Prevents infinite loops with tool call limits, repeated call detection, and token management
- 🔧 TypeScript First: Full TypeScript support with comprehensive type definitions
- 📝 Comprehensive Logging: Built-in logging system with configurable levels
- 🛠️ Enhanced Error Handling: Robust error handling with detailed error messages and parameter validation
- 🌳 Tree-Shaking Support: Optimized for bundle size with tree-shaking support
- 🔒 Security: Secure credential handling and connection management
📦 Installation
npm install mcp-bedrock-client🔧 Prerequisites
- AWS Account: You need an AWS account with Bedrock access
- AWS Credentials: Configure your AWS credentials (access key and secret key)
- MCP Server: A running MCP server to connect to
- Node.js: Version 18 or higher
🛠️ Quick Start
1. Environment Setup
Create a .env file in your project root:
# AWS Configuration
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=your_access_key_here
AWS_SECRET_ACCESS_KEY=your_secret_key_here
BEDROCK_MODEL_ID=anthropic.claude-3-5-sonnet-20240620-v1:0
# MCP Server Configuration
MCP_SERVER_URL=ws://localhost:30002. Basic Usage
import { MCPBedrockClient } from 'mcp-bedrock-client';
import dotenv from 'dotenv';
dotenv.config();
async function main() {
// Create client instance with debug logging
const client = new MCPBedrockClient('DEBUG');
try {
// Initialize with configuration
await client.initialize({
bedrock: {
region: process.env.AWS_REGION!,
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
modelId: process.env.BEDROCK_MODEL_ID!,
// Optional: Configure generation parameters
temperature: 0.1,
maxTokens: 2048,
responseFormat: 'json',
},
mcp: {
serverUrl: process.env.MCP_SERVER_URL!,
clientId: 'my-client',
},
});
// Connect to MCP server
await client.connect();
// Check available tools
const tools = client.getAvailableTools();
console.log('Available tools:', tools.map(t => t.name));
// Ask questions and get answers
const answer = await client.ask('What is the current weather in New York?');
console.log('Answer:', answer);
} catch (error) {
console.error('Error:', error);
} finally {
// Clean up
await client.disconnect();
}
}
main();📚 API Reference
MCPBedrockClient
The main client class for interacting with MCP servers using AWS Bedrock.
Constructor
new MCPBedrockClient(logLevel?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR')Methods
initialize(config: SDKConfig): Promise<void>
Initialize the client with AWS Bedrock and MCP server configuration.
interface SDKConfig {
bedrock: {
region: string;
accessKeyId: string;
secretAccessKey: string;
modelId: string;
// Optional generation parameters
temperature?: number;
topP?: number;
maxTokens?: number;
stopSequences?: string[];
seed?: number;
responseFormat?: 'json' | 'text';
};
mcp: {
serverUrl: string;
clientId?: string;
};
}connect(): Promise<void>
Connect to the MCP server and retrieve available tools.
ask(query: string): Promise<string>
Send a query to the Bedrock model and orchestrate tool calls to get a final answer.
disconnect(): Promise<void>
Disconnect from the MCP server with error handling.
getAvailableTools(): Tool[]
Get the list of available tools from the MCP server.
getToolInfo(toolName: string): Tool | null
Get detailed information about a specific tool, including its schema.
isClientConnected(): boolean
Check if the client is currently connected to the MCP server.
🔄 How It Works
- Initialization: Configure AWS Bedrock credentials and MCP server details
- Connection: Connect to the MCP server and retrieve available tools
- Query Processing:
- Send user query to Bedrock model with tool context
- Model decides whether to use tools or provide direct answer
- If tool call needed, execute tool and send results back to model
- Repeat until model provides final answer
- Response: Return the final answer to the user
🎯 Examples
Basic Example
import { MCPBedrockClient } from 'mcp-bedrock-client';
const client = new MCPBedrockClient();
await client.initialize({
bedrock: {
region: 'us-east-1',
accessKeyId: 'your-key',
secretAccessKey: 'your-secret',
modelId: 'anthropic.claude-3-5-sonnet-20240620-v1:0',
},
mcp: {
serverUrl: 'ws://localhost:3000',
},
});
await client.connect();
const answer = await client.ask('What time is it in Tokyo?');
console.log(answer);Advanced Example with Error Handling
import { MCPBedrockClient } from 'mcp-bedrock-client';
class AdvancedClient {
private client: MCPBedrockClient;
constructor() {
this.client = new MCPBedrockClient('DEBUG');
}
async setup() {
await this.client.initialize({
bedrock: {
region: process.env.AWS_REGION!,
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
modelId: process.env.BEDROCK_MODEL_ID!,
temperature: 0.1,
maxTokens: 4096,
responseFormat: 'json',
},
mcp: {
serverUrl: process.env.MCP_SERVER_URL!,
clientId: 'advanced-client',
},
});
await this.client.connect();
}
async askWithRetry(query: string, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await this.client.ask(query);
} catch (error) {
if (attempt === maxRetries) throw error;
console.warn(`Attempt ${attempt} failed, retrying...`);
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
async debugToolInfo(toolName: string) {
const toolInfo = this.client.getToolInfo(toolName);
if (toolInfo) {
console.log('Tool schema:', toolInfo.inputSchema);
} else {
console.log('Tool not found');
}
}
}Tree-Shaking Example
// Import only what you need for smaller bundles
import { MCPBedrockClient } from 'mcp-bedrock-client/mcp-bedrock-client';
import type { SDKConfig } from 'mcp-bedrock-client/types';🔧 Configuration
Supported Bedrock Models
The SDK automatically detects the required API format and handles model-specific parameter names:
Anthropic Claude Models:
anthropic.claude-3-sonnet-20240229-v1:0(Invoke API)anthropic.claude-3-haiku-20240307-v1:0(Invoke API)anthropic.claude-3-opus-20240229-v1:0(Invoke API)anthropic.claude-3-5-sonnet-20240620-v1:0(Messages API)- Parameter Mapping:
max_tokens_to_sample(Invoke API) ormax_tokens(Messages API) - Stop Sequences:
stop_sequencesfor both APIs - Response Format: Only Claude models support
response_format: { type: "json_object" }
Amazon Titan Models:
amazon.titan-text-express-v1- Parameter Mapping:
maxTokenCount,stopSequences
Meta Llama Models:
meta.llama2-13b-chat-v1meta.llama2-70b-chat-v1- Parameter Mapping:
max_gen_len,stop
MCP Server Transport
The SDK supports both WebSocket and stdio transport:
- WebSocket:
ws://localhost:3000orwss://your-server.com - stdio:
stdio://(for local MCP servers)
Logging Levels
DEBUG: Detailed debug information including tool calls and responsesINFO: General information (default)WARN: Warning messagesERROR: Error messages only
🚨 Error Handling
The SDK includes comprehensive error handling with detailed error messages:
Connection Errors
- Automatic retry with exponential backoff
- Fallback for older MCP servers that don't support all protocol methods
- Graceful handling of connection failures
Tool Execution Errors
- Detailed error messages with MCP error codes
- Parameter validation using tool schemas
- Graceful handling of tool failures with retry logic
Model Response Errors
- Fallback to treating response as final answer
- JSON parsing error handling
- Support for wrapped JSON responses
Debugging Tool Issues
If you encounter tool execution errors, the SDK provides several ways to debug:
// Check available tools
const tools = client.getAvailableTools();
console.log('Available tools:', tools.map(t => t.name));
// Get tool details and schema
const toolInfo = client.getToolInfo('getUserTraits');
if (toolInfo) {
console.log('Tool schema:', toolInfo.inputSchema);
}
// Enhanced error messages include:
// - MCP error codes and data
// - Parameter validation errors
// - Tool schema information🔒 Security
- AWS credentials are stored securely in memory
- No credentials are logged or exposed
- Supports AWS IAM roles and temporary credentials
- MCP server connections use secure WebSocket when available
- Input validation and sanitization
📝 Development
Building from Source
git clone https://github.com/yourusername/mcp-bedrock-client.git
cd mcp-bedrock-client
npm install
npm run buildRunning Examples
# Basic example
npm run example:basic
# Advanced example
npm run example:advancedTesting
npm testDevelopment Scripts
# Build the project
npm run build
# Watch mode for development
npm run dev
# Lint the code
npm run lint
# Fix linting issues
npm run lint:fix
# Format code
npm run format
# Type checking
npm run type-check
# Clean build artifacts
npm run clean🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Run
npm run lintandnpm run build - Submit a pull request
📄 License
MIT License - see LICENSE file for details.
🆘 Support
- Issues: GitHub Issues
- Documentation: GitHub Wiki
- Discussions: GitHub Discussions
🔗 Related Projects
📈 Changelog
v1.2.0
- ✅ Fixed type safety issues (replaced
anywithunknown) - ✅ Enhanced error handling for tool execution
- ✅ Added tool argument validation using schemas
- ✅ Improved disconnect error handling
- ✅ Fixed conversation history formatting
- ✅ Added better MCP error type definitions
- ✅ Enhanced documentation and examples
v1.1.0
- ✅ Added smart iteration control
- ✅ Enhanced tool error handling
- ✅ Added tree-shaking support
- ✅ Improved Claude 3.5 Messages API support
- ✅ Added optional Bedrock parameters
v1.0.0
- ✅ Initial release with core MCP client functionality
- ✅ AWS Bedrock integration
- ✅ Multi-turn orchestration
- ✅ TypeScript support
🚀 Roadmap
- [ ] Support for streaming responses
- [ ] Batch processing capabilities
- [ ] Custom prompt templates
- [ ] Tool result caching
- [ ] Metrics and monitoring
- [ ] Plugin system for custom transports
- [ ] WebSocket reconnection handling
- [ ] Rate limiting and throttling
