Token导航 LogoToken导航TokenDH.com
Bedrock MCP Connector logo
运维云端stdio官方级别未说明来源级核验

Bedrock MCP Connector

MCP Server

@juspay/bedrock-mcp-connector

一个用于与AWS Bedrock和MCP服务器交互的TypeScript客户端,支持模型交互、工具注册和事件驱动的响应流。

工具数

0

提示词数

0

GitHub Stars

2

资源数

0
JavaScriptClaude模型交互Claude

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

juspay

提供方

juspay

最后核验

2026/5/17 20:21

运行时

Node.js

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

npx @juspay/bedrock-mcp-connector

详细介绍

基岩MCP连接器

用于与AWS Bedrock和MCP(模型上下文协议)服务器交互的TypeScript客户端。

特性

  • 与AWS Bedrock的Converse API无缝集成
  • 支持Claude和其他基岩模型
  • 连接到MCP服务器以发现和使用可用工具
  • 注册自定义工具处理程序
  • 基于事件的流式响应架构
  • TypeScript支持完整的类型定义
  • 用于交互式使用的命令行界面
  • 模块化设计,便于集成到其他项目中

安装

npm install @juspay/bedrock-mcp-connector

用法

基本用法

import { BedrockMCPClient, LogLevel } from "@juspay/bedrock-mcp-connector";

// Create a client
const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  systemPrompt: "You are a helpful assistant.",
  mcpServerUrl: "http://localhost:5713/sse", // Optional
});

// Set the log level (optional)
// LogLevel.INFO - Default, shows important information
// LogLevel.DEBUG - Shows detailed debugging information
// LogLevel.WARN - Shows only warnings and errors
// LogLevel.ERROR - Shows only errors
// LogLevel.NONE - Suppresses all logs
client.setLogLevel(LogLevel.INFO);

// Connect to MCP server (if URL is provided)
if (client.mcpServerUrl) {
  await client.connect();
}

// Send a prompt
const response = await client.sendPrompt("What is the capital of France?");
console.log("Response:", response);

// Disconnect when done
if (client.isConnectedToMCP()) {
  await client.disconnect();
}

使用Redis进行持久存储

该软件包支持内存和Redis存储对话历史记录:

import { BedrockMCPClient } from "@juspay/bedrock-mcp-connector";

// Using Redis storage for persistent conversations
const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  sessionId: "user-session-123", // Unique session identifier
  userId: "user-456", // Optional user identifier
  storage: {
    type: "redis",
    config: {
      host: "localhost",
      port: 6379,
      password: "your-redis-password", // Optional
      db: 0, // Redis database number
      keyPrefix: "bedrock-mcp:", // Key prefix for Redis keys
      ttl: 86400, // TTL in seconds (24 hours)
      connectionOptions: {
        connectTimeout: 5000,
        lazyConnect: true
      }
    }
  }
});

// Conversations are now persistent across client restarts
const response = await client.sendPrompt("Remember this: my favorite color is blue");
console.log("Response:", response);

// Later, in a new client instance with the same sessionId...
const newClient = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  sessionId: "user-session-123", // Same session ID
  storage: { type: "redis", config: { /* same config */ } }
});

const response2 = await newClient.sendPrompt("What's my favorite color?");
// The model will remember the previous conversation!

存储配置选项

内存存储(默认)

const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  // No storage config = in-memory storage
  // OR explicitly specify:
  storage: { type: "memory" }
});

Redis存储

const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  storage: {
    type: "redis",
    config: {
      host: "localhost",        // Redis host (default: 'localhost')
      port: 6379,              // Redis port (default: 6379)
      password: "password",    // Redis password (optional)
      db: 0,                   // Redis database (default: 0)
      keyPrefix: "myapp:",     // Key prefix (default: 'bedrock-mcp:conversation:')
      ttl: 3600,              // TTL in seconds (default: 86400 - 24 hours)
      connectionOptions: {     // Additional Redis connection options
        connectTimeout: 5000,
        lazyConnect: true,
        retryDelayOnFailover: 100,
        maxRetriesPerRequest: 3
      }
    }
  }
});

与活动听众一起

import { BedrockMCPClient, LogLevel } from "@juspay/bedrock-mcp-connector";

// Create a client
const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
});

// Set the log level (optional)
client.setLogLevel(LogLevel.INFO);

// Set up event listeners
const emitter = client.getEmitter();

emitter.on("message", (message) => {
  console.log(`Message: ${message}`);
});

emitter.on("error", (error) => {
  console.error(`Error: ${error.message}`);
});

emitter.on("tool:start", (toolName, input) => {
  console.log(`Tool started: ${toolName}`);
});

emitter.on("tool:end", (toolName, result) => {
  console.log(`Tool completed: ${toolName}`);
});

emitter.on("response:start", () => {
  console.log("Response started");
});

emitter.on("response:chunk", (chunk) => {
  console.log(`Response chunk: ${chunk.substring(0, 50)}...`);
});

emitter.on("response:end", (fullResponse) => {
  console.log("Response completed");
});

// Send a prompt
const response = await client.sendPrompt("What is the capital of France?");

创建和注册工具

工具是一个强大的功能,允许LLM执行操作和访问外部数据。本节提供了如何有效创建和注册工具的详细指导。

工具注册基础知识

registerTool 该方法有四个参数:

client.registerTool(
  name, // String: Unique identifier for the tool
  handler, // Function: Async function that implements the tool
  description, // String: Human-readable description of what the tool does
  inputSchema // Object: JSON Schema defining the tool's parameters
);

工具设计的最佳实践

  1. 单一责任:每个工具都应该做好一件事
  2. 明确命名:使用描述性的、面向行动的名称(例如。, getCurrentTime, searchDatabase)
  3. 综合说明:提供详细的描述,帮助LLM了解何时使用该工具
  4. 彻底的输入验证:始终验证输入以防止错误
  5. 信息性错误消息:出现问题时返回明确的错误消息
  6. 一致的返回格式:始终以相同的格式返回结果
  7. 适当的日志记录:包括日志记录以帮助调试

详细的工具注册示例

import { BedrockMCPClient, LogLevel } from "@juspay/bedrock-mcp-connector";

// Create a client
const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
});

// Set the log level (optional)
client.setLogLevel(LogLevel.INFO);

// Register a custom tool
client.registerTool(
  // Name: Use a clear, descriptive name
  "getCurrentTime",

  // Handler: Implement the tool's functionality
  async (name, input) => {
    // Input validation with default values
    const timezone = input.timezone || "UTC";

    try {
      // Core functionality
      const date = new Date().toLocaleString("en-US", { timeZone: timezone });

      // Return successful result
      return {
        content: [{ text: `The current time is ${date} in ${timezone}` }],
      };
    } catch (error) {
      // Error handling
      return {
        content: [{ text: `Error getting time: ${error.message}` }],
        isError: true,
      };
    }
  },

  // Description: Clearly explain what the tool does
  "Get the current time in the specified timezone. This tool returns the current date and time formatted according to US locale conventions.",

  // Input Schema: Define the parameters using JSON Schema
  {
    type: "object",
    properties: {
      timezone: {
        type: "string",
        description:
          "The timezone to get the time for (e.g., UTC, America/New_York, Europe/London)",
        examples: ["UTC", "America/New_York", "Europe/Paris", "Asia/Tokyo"],
      },
    },
    required: [], // Empty array means no parameters are required
  }
);

// Send a prompt that might use the tool
const response = await client.sendPrompt("What time is it now in Tokyo?");

输入模式设计

输入模式使用JSON模式格式来定义工具接受的参数:

{
  type: "object",
  properties: {
    // Define each parameter
    paramName: {
      type: "string" | "number" | "boolean" | "array" | "object",
      description: "Clear description of the parameter",
      examples: ["example1", "example2"], // Optional but helpful
      enum: ["option1", "option2"],       // For parameters with fixed options
      minimum: 1,                         // For number validation
      maximum: 100,                       // For number validation
      pattern: "^[a-z]+$",                // For string validation with regex
      // Additional JSON Schema properties as needed
    },
    // More parameters...
  },
  required: ["paramName1", "paramName2"],  // List required parameters
  additionalProperties: false              // Prevent extra parameters (optional)
}

工具中的错误处理

正确的错误处理对工具至关重要:

client.registerTool(
  "divideNumbers",
  async (name, input) => {
    // Parameter validation
    if (typeof input.dividend !== "number") {
      return {
        content: [{ text: "Error: dividend must be a number" }],
        isError: true,
      };
    }

    if (typeof input.divisor !== "number") {
      return {
        content: [{ text: "Error: divisor must be a number" }],
        isError: true,
      };
    }

    // Business logic validation
    if (input.divisor === 0) {
      return {
        content: [{ text: "Error: Cannot divide by zero" }],
        isError: true,
      };
    }

    try {
      // Perform the operation
      const result = input.dividend / input.divisor;

      return {
        content: [
          {
            text: `${input.dividend} divided by ${input.divisor} equals ${result}`,
          },
        ],
      };
    } catch (error) {
      return {
        content: [{ text: `Calculation error: ${error.message}` }],
        isError: true,
      };
    }
  },
  "Divide two numbers",
  {
    type: "object",
    properties: {
      dividend: {
        type: "number",
        description: "The number to be divided",
      },
      divisor: {
        type: "number",
        description: "The number to divide by (cannot be zero)",
      },
    },
    required: ["dividend", "divisor"],
  }
);

不同工具类型的示例

1.数据检索工具

client.registerTool(
  "getWeatherForecast",
  async (name, input) => {
    const { city, days = 3 } = input;

    if (!city) {
      return {
        content: [{ text: "Error: city parameter is required" }],
        isError: true,
      };
    }

    try {
      // In a real implementation, this would call a weather API
      const forecast = await weatherService.getForecast(city, days);

      return {
        content: [
          {
            text: `Weather forecast for ${city} for the next ${days} days:\n\n${forecast}`,
          },
        ],
      };
    } catch (error) {
      return {
        content: [{ text: `Error getting weather forecast: ${error.message}` }],
        isError: true,
      };
    }
  },
  "Get weather forecast for a city",
  {
    type: "object",
    properties: {
      city: {
        type: "string",
        description: "The city to get the weather forecast for",
      },
      days: {
        type: "number",
        description: "Number of days to forecast (default: 3)",
        minimum: 1,
        maximum: 10,
      },
    },
    required: ["city"],
  }
);

2.计算工具

client.registerTool(
  "calculateStatistics",
  async (name, input) => {
    const { numbers } = input;

    if (!Array.isArray(numbers) || numbers.length === 0) {
      return {
        content: [
          { text: "Error: numbers must be a non-empty array of numbers" },
        ],
        isError: true,
      };
    }

    if (!numbers.every((n) => typeof n === "number")) {
      return {
        content: [{ text: "Error: all elements in numbers must be numbers" }],
        isError: true,
      };
    }

    try {
      const sum = numbers.reduce((a, b) => a + b, 0);
      const mean = sum / numbers.length;
      const sortedNumbers = [...numbers].sort((a, b) => a - b);
      const median =
        sortedNumbers.length % 2 === 0
          ? (sortedNumbers[sortedNumbers.length / 2 - 1] +
              sortedNumbers[sortedNumbers.length / 2]) /
            2
          : sortedNumbers[Math.floor(sortedNumbers.length / 2)];

      return {
        content: [
          {
            text: `Statistics for [${numbers.join(
              ", "
            )}]:\n- Sum: ${sum}\n- Mean: ${mean}\n- Median: ${median}\n- Min: ${Math.min(
              ...numbers
            )}\n- Max: ${Math.max(...numbers)}`,
          },
        ],
      };
    } catch (error) {
      return {
        content: [{ text: `Error calculating statistics: ${error.message}` }],
        isError: true,
      };
    }
  },
  "Calculate basic statistics for an array of numbers",
  {
    type: "object",
    properties: {
      numbers: {
        type: "array",
        items: {
          type: "number",
        },
        description: "Array of numbers to calculate statistics for",
      },
    },
    required: ["numbers"],
  }
);

3.外部API工具

client.registerTool(
  "searchWikipedia",
  async (name, input) => {
    const { query, limit = 3 } = input;

    if (!query || typeof query !== "string") {
      return {
        content: [
          { text: "Error: query parameter is required and must be a string" },
        ],
        isError: true,
      };
    }

    try {
      // In a real implementation, this would call the Wikipedia API
      const searchUrl = `https://en.wikipedia.org/w/api.php?action=opensearch&search=${encodeURIComponent(
        query
      )}&limit=${limit}&namespace=0&format=json`;
      const response = await fetch(searchUrl);
      const [searchTerm, titles, descriptions, urls] = await response.json();

      let resultText = `Wikipedia search results for "${query}":\n\n`;

      for (let i = 0; i            AWS Bedrock model ID (default: anthropic.claude-3-sonnet-20240229-v1:0)
  -r, --region       AWS region (default: us-east-1)
  -s, --system-prompt  System prompt for the model
  -u, --mcp-url         MCP server URL
  -n, --name           Client name
  -v, --version     Client version
  -h, --help                 Show this help message

会话管理和多用户支持

该软件包支持多用户应用程序的复杂会话管理:

会话隔离

// User 1's conversation
const user1Client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  sessionId: "session-user1-chat1",
  userId: "user1",
  storage: { type: "redis", config: { /* redis config */ } }
});

// User 2's conversation (completely isolated)
const user2Client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  sessionId: "session-user2-chat1",
  userId: "user2",
  storage: { type: "redis", config: { /* redis config */ } }
});

存储健康监控

// Check if storage is healthy
const isHealthy = await client.isStorageHealthy();
if (!isHealthy) {
  console.log("Storage connection issues detected");
}

// Get storage information
const storageInfo = client.getStorageInfo();
console.log("Storage type:", storageInfo.type); // 'memory' or 'redis'

Redis密钥管理

使用Redis存储时,密钥的结构如下:

  • 图案: {keyPrefix}{userId}:{sessionId}{keyPrefix}{sessionId}
  • 默认前缀: bedrock-mcp:conversation:
  • 示例密钥:

- bedrock-mcp:conversation:user123:session456 - bedrock-mcp:conversation:anonymous-session789

存储迁移

您可以通过复制对话历史记录在存储类型之间迁移:

// Get history from in-memory client
const memoryClient = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  storage: { type: "memory" }
});

const history = await memoryClient.getConversationHistory();

// Create Redis client and restore history
const redisClient = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  storage: { type: "redis", config: { /* config */ } }
});

// Note: Direct history restoration requires custom implementation
// The storage layer handles this automatically for same-session clients

api参考

基岩MCP客户端

构造函数

new BedrockMCPClient(config: {
  modelId: string;
  region?: string;
  systemPrompt?: string;
  mcpServerUrl?: string;
  clientName?: string;
  clientVersion?: string;
  maxTokens?: number;
  temperature?: number;
  responseOutputTags?: [string, string];
  storage?: StorageConfig;
  sessionId?: string;
  userId?: string;
})

方法

  • connect(): Promise -连接到MCP服务器
  • disconnect(): Promise -断开与MCP服务器的连接并关闭存储
  • isConnectedToMCP(): boolean -检查客户端是否连接到MCP服务器
  • sendPrompt(prompt: string): Promise -向代理发送提示
  • registerTool(name: string, handler: ToolHandler, description?: string, inputSchema?: Record): void -注册自定义工具
  • getTools(): Array -获取所有已注册的工具
  • getEmitter(): BedrockMCPClientEmitter -获取事件发射器
  • getAgent(): ConverseAgent -找代理人
  • getConversationHistory(): Promise -获取对话历史记录
  • clearConversationHistory(): Promise -清除对话历史记录
  • setLogLevel(level: LogLevel): void -为客户端及其组件设置日志级别
  • isStorageHealthy(): Promise -检查存储是否正常
  • getStorageInfo(): { type: string; isHealthy?: boolean } -获取存储类型信息

存储类型

存储配置

type StorageConfig =
  | { type: 'memory' }
  | { type: 'redis'; config: RedisStorageConfig };

重新存储配置

interface RedisStorageConfig {
  host?: string;                    // Redis host (default: 'localhost')
  port?: number;                    // Redis port (default: 6379)
  password?: string;                // Redis password
  db?: number;                      // Redis database number (default: 0)
  keyPrefix?: string;               // Key prefix (default: 'bedrock-mcp:conversation:')
  ttl?: number;                     // TTL in seconds (default: 86400)
  connectionOptions?: {             // Additional Redis connection options
    connectTimeout?: number;
    lazyConnect?: boolean;
    retryDelayOnFailover?: number;
    maxRetriesPerRequest?: number;
    [key: string]: any;
  };
}

会话标识符

interface SessionIdentifier {
  sessionId: string;                // Unique session ID
  userId?: string;                  // Optional user ID for multi-user scenarios
}

事件

  • message -记录消息时触发
  • error -发生错误时发出
  • tool:start -当工具开始执行时触发
  • tool:end -当工具执行完毕时触发
  • response:start -响应开始时发出
  • response:chunk -收到响应块时发出
  • response:end -响应结束时发出
  • connected -连接到MCP服务器时发出
  • disconnected -与MCP服务器断开连接时发出

记录系统

该软件包包括一个全面的日志记录系统,允许您控制日志和调试信息的详细程度。

日志级别

以下日志级别可用(从最详细到最不详细):

  • LogLevel.DEBUG (0)-详细的调试信息
  • LogLevel.INFO (1) -一般信息消息(默认)
  • LogLevel.WARN (2) -警告信息
  • LogLevel.ERROR (3) -错误消息
  • LogLevel.NONE (4) -无日志记录

设置日志级别

您可以为客户端及其所有组件设置日志级别:

import { BedrockMCPClient, LogLevel } from "@juspay/bedrock-mcp-connector";

// Create a client
const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
});

// Set the log level
client.setLogLevel(LogLevel.INFO); // Default level
// or
client.setLogLevel(LogLevel.DEBUG); // For detailed debugging

每个级别记录的内容

  • 调试:所有消息,包括详细的API响应、工具执行详细信息和内部状态更改
  • 信息:一般操作信息、工具请求、连接状态和重要事件
  • 警告:不妨碍操作但可能需要注意的潜在问题
  • 错误:影响操作但不一定导致应用程序崩溃的错误
  • :不会输出日志(未处理的异常除外)

用例

开发和调试(LogLevel.DEBUG)

在以下情况下使用DEBUG级别:

  • 开发新功能或工具
  • API响应的疑难解答问题
  • 调试工具执行问题
  • 了解系统中的数据流
// Enable detailed debugging
client.setLogLevel(LogLevel.DEBUG);

// Now you'll see detailed information about:
// - Full API responses from Bedrock
// - Tool input and output details
// - Message content and processing

生产使用情况(LogLevel.INFO或LogLevel.WARN)

对于生产环境:

  • 使用INFO跟踪正常操作
  • 使用警告仅查看潜在问题
// For normal operation with important information
client.setLogLevel(LogLevel.INFO);

// Or for minimal logging (only warnings and errors)
client.setLogLevel(LogLevel.WARN);

审计和监控(LogLevel.INFO)

当您需要跟踪工具使用和交互时:

client.setLogLevel(LogLevel.INFO);

// This will log:
// - When tools are requested and executed
// - Connection events
// - Response start/end events

静音操作(LogLevel.NONE)

当您想要抑制所有日志时:

client.setLogLevel(LogLevel.NONE);

会话管理

该包自动维护对话历史,允许与模型进行自然的来回交互。这使模型能够记住以前消息的上下文,并在整个对话中提供连贯的响应。

对话历史如何运作

  1. 发送到模型和从模型接收的每条消息都存储在内存中
  2. 对模型的每个新请求都包含完整的对话历史记录
  3. 这允许模型引用以前的消息并维护上下文

管理对话历史记录

您可以使用以下方法访问和管理对话历史记录:

// Get the current conversation history
const history = client.getConversationHistory();
console.log("Current conversation:", history);

// Clear the conversation history to start a new conversation
client.clearConversationHistory();
console.log("Started a new conversation");

示例:多回合对话

import { BedrockMCPClient } from "@juspay/bedrock-mcp-connector";

const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
});

// First message
let response = await client.sendPrompt("What are the three primary colors?");
console.log("Response 1:", response);

// Follow-up question (model remembers the context)
response = await client.sendPrompt(
  "And what colors do you get when you mix them?"
);
console.log("Response 2:", response);

// Start a new conversation
client.clearConversationHistory();

// This is now a completely new conversation with no memory of the previous exchange
response = await client.sendPrompt("What's the tallest mountain in the world?");
console.log("New conversation response:", response);

多个API调用的工具结果

该包维护多个API调用的工具结果,确保所有工具结果都包含在最终响应中。当模型需要使用多种工具来回答复杂问题时,这尤其有用。

处理缺少的必需参数

当使用需要特定参数的工具时,您可以实现一个交互式流程,模型会要求提供缺失的信息。处理缺失参数有两种关键方法:

1.使用专门的系统提示

您可以通过一个专门的系统提示来指导模型的行为,该提示指示它如何处理缺失的参数:

const client = new BedrockMCPClient({
  modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
  region: "us-east-1",
  systemPrompt: `You are a helpful assistant with access to external tools.
                  - Use available tools **only when necessary** to provide accurate or up-to-date information.
                  - If a question can be answered based on your knowledge, respond directly **without using tools**.
                  - If a tool is required:
                      1. **Check if all necessary parameters are available.** If they are, use the tool directly.
                      2. **If any parameters are missing, do not proceed.** Instead, ask the user for the required information, explaining why it is needed.
                      3. **Wait for the user's response before using the tool.**
                  - If the user asks multiple questions, **handle them one by one**.
                  - If some questions require tools and others don't, **answer what you can immediately**, then use tools as needed.
                  - After using a tool, continue answering any remaining questions.
                  `,
});

此系统提示指示模型:

  • 不要尝试使用参数不完整的工具
  • 清楚地解释哪些参数缺失以及为什么需要它们
  • 向用户询问缺失的信息
  • 只有在所有必需的参数都可用时才能使用该工具

2.在工具中实现参数验证

在工具处理程序中实现彻底的参数验证,以确保它们能够优雅地处理缺失的参数:

client.registerTool(
  "calculator",
  async (name, input) => {
    const { operation, a, b } = input;

    // Validate required parameters
    if (!operation) {
      return {
        content: [
          { text: `Error: Operation parameter is required for calculator` },
        ],
        isError: true,
      };
    }

    if (a === undefined || a === null) {
      return {
        content: [
          { text: `Error: First operand (a) is required for calculator` },
        ],
        isError: true,
      };
    }

    if (b === undefined || b === null) {
      return {
        content: [
          { text: `Error: Second operand (b) is required for calculator` },
        ],
        isError: true,
      };
    }

    // Tool implementation...
    let result;
    switch (operation) {
      case "add":
        result = a + b;
        break;
      case "subtract":
        result = a - b;
        break;
      case "multiply":
        result = a * b;
        break;
      case "divide":
        if (b === 0) throw new Error("Division by zero");
        result = a / b;
        break;
      default:
        throw new Error(`Unknown operation: ${operation}`);
    }

    return {
      content: [{ text: `The result of ${a} ${operation} ${b} is ${result}` }],
    };
  },
  "Perform basic arithmetic operations",
  {
    type: "object",
    properties: {
      operation: {
        type: "string",
        description:
          "The operation to perform (add, subtract, multiply, divide)",
        enum: ["add", "subtract", "multiply", "divide"],
      },
      a: { type: "number", description: "The first operand" },
      b: { type: "number", description: "The second operand" },
    },
    required: ["operation", "a", "b"],
  }
);

3.互动对话流程

实现一个交互式对话流,处理用户和模型之间的来回对话:

import { BedrockMCPClient } from "@juspay/bedrock-mcp-connector";
import * as readline from "readline";

// Create a readline interface for user input
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// Function to get user input
const getUserInput = (question) =>
  new Promise((resolve) => {
    rl.question(question, (answer) => resolve(answer));
  });

async function runInteractiveSession() {
  const client = new BedrockMCPClient({
    modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
    region: "us-east-1",
    systemPrompt: `You are a helpful assistant with access to external tools.
                  - Use available tools **only when necessary** to provide accurate or up-to-date information.
                  - If a question can be answered based on your knowledge, respond directly **without using tools**.
                  - If a tool is required:
                      1. **Check if all necessary parameters are available.** If they are, use the tool directly.
                      2. **If any parameters are missing, do not proceed.** Instead, ask the user for the required information, explaining why it is needed.
                      3. **Wait for the user's response before using the tool.**
                  - If the user asks multiple questions, **handle them one by one**.
                  - If some questions require tools and others don't, **answer what you can immediately**, then use tools as needed.
                  - After using a tool, continue answering any remaining questions.
                  `,
  });

  // Register tools (calculator, weather forecast, etc.)
  // ...

  // Start the conversation
  console.log("Ask me anything! (Type 'exit' to quit)");

  while (true) {
    // Get user input
    const userInput = await getUserInput("> ");

    if (userInput.toLowerCase() === "exit") break;

    // Send to the model
    const response = await client.sendPrompt(userInput);
    console.log("\nAssistant:", response);
  }

  rl.close();
}

runInteractiveSession().catch(console.error);

4.在对话之间管理工具结果

在实施多回合对话时,重要的是在单独的对话之间清除累积的工具结果,以防止之前的对话结果影响新的对话:

// After completing a conversation or when starting a new one
client.clearConversationHistory();
client.getAgent().clearAccumulatedToolResults();

这确保了以前对话的工具结果不会出现在新对话中。

示例:完整的对话流程

以下是一个完整的对话流示例,其中模型要求缺少参数:

  1. 用户提出了一个参数不完整的问题:
   User: "Can you calculate something for me? I want to multiply 42 by something."
  1. 模型响应,询问缺少的参数:
   Assistant: "I'd be happy to help you with that calculation. To use the calculator tool,
   I need two operands (numbers) and the operation. You've provided one number (42) and
   mentioned you want to multiply, but I'm missing the second operand.
   Could you please tell me what number you want to multiply 42 by?"
  1. 用户提供缺少的参数:
   User: "The second number is 7."
  1. 模型使用具有完整参数的工具:
   Assistant: "I've calculated that 42 multiplied by 7 equals 294."

这种模式允许自然对话,模型可以请求缺失的信息,然后使用这些信息来完成工具执行。

创建自定义记录器

您可以为应用程序的其他部分创建自己的记录器:

import { createDefaultLogger, LogLevel } from "@juspay/bedrock-mcp-connector";

// Create a logger with a custom prefix
const logger = createDefaultLogger("MyComponent");

// Set the log level
logger.setLevel(LogLevel.INFO);

// Use the logger
logger.info("Application started");
logger.debug("This won't be shown unless log level is DEBUG");
logger.warn("Something might be wrong");
logger.error("An error occurred", errorObject);

许可证

麻省理工学院

目录标签

目录标签

JavaScriptClaude模型交互AWSBedrock本地部署MCP协议TypeScript客户端工具扩展

支持客户端

Claude

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

session

运行时(runtime,运行环境)

Node.js

来源包(packageName,安装包名)

@juspay/bedrock-mcp-connector

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdiosession部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP