npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

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

  1. AWS Account: You need an AWS account with Bedrock access
  2. AWS Credentials: Configure your AWS credentials (access key and secret key)
  3. MCP Server: A running MCP server to connect to
  4. 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:3000

2. 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

  1. Initialization: Configure AWS Bedrock credentials and MCP server details
  2. Connection: Connect to the MCP server and retrieve available tools
  3. 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
  4. 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) or max_tokens (Messages API)
  • Stop Sequences: stop_sequences for 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-v1
  • meta.llama2-70b-chat-v1
  • Parameter Mapping: max_gen_len, stop

MCP Server Transport

The SDK supports both WebSocket and stdio transport:

  • WebSocket: ws://localhost:3000 or wss://your-server.com
  • stdio: stdio:// (for local MCP servers)

Logging Levels

  • DEBUG: Detailed debug information including tool calls and responses
  • INFO: General information (default)
  • WARN: Warning messages
  • ERROR: 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 build

Running Examples

# Basic example
npm run example:basic

# Advanced example
npm run example:advanced

Testing

npm test

Development 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

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Run npm run lint and npm run build
  6. Submit a pull request

📄 License

MIT License - see LICENSE file for details.

🆘 Support

🔗 Related Projects

📈 Changelog

v1.2.0

  • ✅ Fixed type safety issues (replaced any with unknown)
  • ✅ 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