# Directory Structure ``` ├── .gitignore ├── Dockerfile ├── index.ts ├── package.json ├── pnpm-lock.yaml ├── README.md └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` build/ *.log *.pyc *.swp node_modules/ dist/ ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # AWS Knowledge Base Retrieval MCP Server An MCP server implementation for retrieving information from the AWS Knowledge Base using the Bedrock Agent Runtime. ## Features - **RAG (Retrieval-Augmented Generation)**: Retrieve context from the AWS Knowledge Base based on a query and a Knowledge Base ID. - **Supports multiple results retrieval**: Option to retrieve a customizable number of results. ## Tools - **retrieve_from_aws_kb** - Perform retrieval operations using the AWS Knowledge Base. - Inputs: - `query` (string): The search query for retrieval. - `knowledgeBaseId` (string): The ID of the AWS Knowledge Base. - `n` (number, optional): Number of results to retrieve (default: 3). - Response format: - The response now returns two separate content items: - A text item containing the raw context from the knowledge base. - A JSON item containing the structured RAG sources with metadata (id, fileName, snippet, and score). - This separation allows for more flexible processing of the results. ## Configuration ### Setting up AWS Credentials You have two options for configuring AWS credentials: #### Option 1: IAM Access Keys 1. Obtain AWS access key ID, secret access key, and region from the AWS Management Console. 2. Ensure these credentials have appropriate permissions for Bedrock Agent Runtime operations. 3. Set the environment variables as shown in the configuration examples below. 4. For temporary credentials, you can also provide a session token using the `AWS_SESSION_TOKEN` environment variable. #### Option 2: AWS SSO (Single Sign-On) The server now supports AWS SSO credentials: 1. Configure AWS CLI with your SSO profile: `aws configure sso` 2. Set only the AWS_REGION environment variable in the MCP server configuration. 3. The server will use the default credential provider chain, which includes SSO credentials. ### Optional: Configure Default Knowledge Base IDs You can optionally specify one or more knowledge base IDs to use by default: 1. Create an array of knowledge base IDs in JSON format. 2. Set this as the AWS_KB_IDS environment variable in your configuration. 3. When this is configured, the `knowledgeBaseId` parameter becomes optional in the tool. ### Usage with Claude Desktop Add this to your `claude_desktop_config.json`: #### Docker with IAM Access Keys ```json { "mcpServers": { "aws-kb-retrieval": { "command": "docker", "args": [ "run", "-i", "--rm", "-e", "AWS_ACCESS_KEY_ID", "-e", "AWS_SECRET_ACCESS_KEY", "-e", "AWS_REGION", "-e", "AWS_KB_IDS", "mcp/aws-kb-retrieval-server" ], "env": { "AWS_ACCESS_KEY_ID": "YOUR_ACCESS_KEY_HERE", "AWS_SECRET_ACCESS_KEY": "YOUR_SECRET_ACCESS_KEY_HERE", "AWS_SESSION_TOKEN": "YOUR_OPTIONAL_SESSION_ID_FOR_SSO_TEMPORARY_CREDENTIALS_HERE", "AWS_REGION": "YOUR_AWS_REGION_HERE", "AWS_KB_IDS": "[\"kb-12345\", \"kb-67890\"]" } } } } ``` #### Docker with AWS SSO ```json { "mcpServers": { "aws-kb-retrieval": { "command": "docker", "args": [ "run", "-i", "--rm", "-e", "AWS_REGION", "-e", "AWS_KB_IDS", "-v", "${HOME}/.aws:/root/.aws", "mcp/aws-kb-retrieval-server" ], "env": { "AWS_ACCESS_KEY_ID": "YOUR_ACCESS_KEY_HERE", "AWS_SECRET_ACCESS_KEY": "YOUR_SECRET_ACCESS_KEY_HERE", "AWS_SESSION_TOKEN": "YOUR_OPTIONAL_SESSION_ID_FOR_SSO_TEMPORARY_CREDENTIALS_HERE", "AWS_REGION": "YOUR_AWS_REGION_HERE", "AWS_KB_IDS": "[\"kb-12345\", \"kb-67890\"]" } } } } ``` #### NPX with IAM Access Keys ```json { "mcpServers": { "aws-kb-retrieval": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-aws-kb-retrieval" ], "env": { "AWS_ACCESS_KEY_ID": "YOUR_ACCESS_KEY_HERE", "AWS_SECRET_ACCESS_KEY": "YOUR_SECRET_ACCESS_KEY_HERE", "AWS_SESSION_TOKEN": "YOUR_OPTIONAL_SESSION_ID_FOR_SSO_TEMPORARY_CREDENTIALS_HERE", "AWS_REGION": "YOUR_AWS_REGION_HERE", "AWS_KB_IDS": "[\"kb-12345\", \"kb-67890\"]" } } } } ``` #### NPX with AWS SSO ```json { "mcpServers": { "aws-kb-retrieval": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-aws-kb-retrieval" ], "env": { "AWS_ACCESS_KEY_ID": "YOUR_ACCESS_KEY_HERE", "AWS_SECRET_ACCESS_KEY": "YOUR_SECRET_ACCESS_KEY_HERE", "AWS_SESSION_TOKEN": "YOUR_OPTIONAL_SESSION_ID_FOR_SSO_TEMPORARY_CREDENTIALS_HERE", "AWS_REGION": "YOUR_AWS_REGION_HERE", "AWS_KB_IDS": "[\"kb-12345\", \"kb-67890\"]" } } } } ``` #### Local Repository (from cloned/built repo) ```json { "mcpServers": { "aws-kb": { "command": "node", "args": [ "/path/to/mcp-aws-kb/dist/index.js" ], "env": { "AWS_ACCESS_KEY_ID": "YOUR_ACCESS_KEY_HERE", "AWS_SECRET_ACCESS_KEY": "YOUR_SECRET_ACCESS_KEY_HERE", "AWS_SESSION_TOKEN": "YOUR_OPTIONAL_SESSION_ID_FOR_SSO_TEMPORARY_CREDENTIALS_HERE", "AWS_REGION": "YOUR_AWS_REGION_HERE", "AWS_KB_IDS": "[\"kb-12345\", \"kb-67890\"]" }, "disabled": false, "autoApprove": [ "retrieve_from_aws_kb" ], "timeout": 120 } } } ``` ## Building Docker: ```sh docker build -t mcp/aws-kb-retrieval -f src/aws-kb-retrieval-server/Dockerfile . ``` ## License This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository. This README assumes that your server package is named `@modelcontextprotocol/server-aws-kb-retrieval`. Adjust the package name and installation details if they differ in your setup. Also, ensure that your server script is correctly built and that all dependencies are properly managed in your `package.json`. ``` -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- ```dockerfile FROM node:22.12-alpine AS builder COPY src/aws-kb-retrieval-server /app COPY tsconfig.json /tsconfig.json WORKDIR /app RUN --mount=type=cache,target=/root/.npm npm install FROM node:22-alpine AS release WORKDIR /app COPY --from=builder /app/dist /app/dist COPY --from=builder /app/package.json /app/package.json COPY --from=builder /app/package-lock.json /app/package-lock.json ENV NODE_ENV=production RUN npm ci --ignore-scripts --omit-dev ENTRYPOINT ["node", "dist/index.js"] ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json { "compilerOptions": { "target": "ES2020", "module": "NodeNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "outDir": "./dist", "rootDir": ".", "declaration": true, "composite": true, "incremental": true, "tsBuildInfoFile": "./dist/.tsbuildinfo", "lib": ["ES2020", "DOM"] }, "include": [ "./**/*.ts" ], "exclude": [ "node_modules", "dist" ] } ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json { "name": "@modelcontextprotocol/server-aws-kb-retrieval", "version": "0.7.0", "description": "MCP server for AWS Knowledge Base retrieval using Bedrock Agent Runtime", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", "homepage": "https://modelcontextprotocol.io", "bugs": "https://github.com/modelcontextprotocol/servers/issues", "type": "module", "bin": { "mcp-server-aws-kb-retrieval": "dist/index.js" }, "files": [ "dist" ], "scripts": { "build": "tsc && shx chmod +x dist/*.js", "prepare": "npm run build", "watch": "tsc --watch" }, "dependencies": { "@modelcontextprotocol/sdk": "1.7.0", "@aws-sdk/client-bedrock-agent-runtime": "^3.765.0" }, "devDependencies": { "@types/node": "^22.13.10", "shx": "^0.3.4", "typescript": "^5.8.2" }, "packageManager": "[email protected]+sha512.47870716bea1572b53df34ad8647b42962bc790ce2bf4562ba0f643237d7302a3d6a8ecef9e4bdfc01d23af1969aa90485d4cebb0b9638fa5ef1daef656f6c1b" } ``` -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- ```typescript #!/usr/bin/env node import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, Tool, } from "@modelcontextprotocol/sdk/types.js"; import { BedrockAgentRuntimeClient, RetrieveCommand, RetrieveCommandInput, } from "@aws-sdk/client-bedrock-agent-runtime"; // AWS client initialization const clientConfig: Record<string, any> = { region: process.env.AWS_REGION, }; // Only add explicit credentials if access keys are provided // Otherwise use the default credential provider chain (supports SSO) if (process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY) { clientConfig.credentials = { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }; // Add session token if provided (for temporary credentials) if (process.env.AWS_SESSION_TOKEN) { clientConfig.credentials.sessionToken = process.env.AWS_SESSION_TOKEN; } } const bedrockClient = new BedrockAgentRuntimeClient(clientConfig); // Get configured knowledgebase IDs from environment variable const configuredKnowledgeBaseIds = process.env.AWS_KB_IDS ? JSON.parse(process.env.AWS_KB_IDS) : []; interface RAGSource { id: string; fileName: string; snippet: string; score: number; } async function retrieveContext( query: string, knowledgeBaseId: string, n: number = 3 ): Promise<{ context: string; isRagWorking: boolean; ragSources: RAGSource[]; }> { try { if (!knowledgeBaseId) { console.error("knowledgeBaseId is not provided"); return { context: "", isRagWorking: false, ragSources: [], }; } const input: RetrieveCommandInput = { knowledgeBaseId: knowledgeBaseId, retrievalQuery: { text: query }, retrievalConfiguration: { vectorSearchConfiguration: { numberOfResults: n }, }, }; const command = new RetrieveCommand(input); const response = await bedrockClient.send(command); const rawResults = response?.retrievalResults || []; const ragSources: RAGSource[] = rawResults .filter((res) => res?.content?.text) .map((result, index) => { const uri = result?.location?.s3Location?.uri || ""; const fileName = uri.split("/").pop() || `Source-${index}.txt`; return { id: (result.metadata?.["x-amz-bedrock-kb-chunk-id"] as string) || `chunk-${index}`, fileName: fileName.replace(/_/g, " ").replace(".txt", ""), snippet: result.content?.text || "", score: (result.score as number) || 0, }; }) .slice(0, 3); const context = rawResults .filter((res): res is { content: { text: string } } => res?.content?.text !== undefined) .map(res => res.content.text) .join("\n\n"); return { context, isRagWorking: true, ragSources, }; } catch (error) { console.error("RAG Error:", error); return { context: "", isRagWorking: false, ragSources: [] }; } } // Define the retrieval tool const RETRIEVAL_TOOL: Tool = { name: "retrieve_from_aws_kb", description: "Performs retrieval from the AWS Knowledge Base using the provided query and Knowledge Base ID.", inputSchema: { type: "object", properties: { query: { type: "string", description: "The query to perform retrieval on" }, knowledgeBaseId: { type: "string", description: configuredKnowledgeBaseIds.length > 0 ? "The ID of the AWS Knowledge Base (optional if configured via AWS_KB_IDS)" : "The ID of the AWS Knowledge Base" }, n: { type: "number", default: 3, description: "Number of results to retrieve" }, }, required: configuredKnowledgeBaseIds.length > 0 ? ["query"] : ["query", "knowledgeBaseId"], }, }; // Server setup const server = new Server( { name: "aws-kb-retrieval-server", version: "0.2.0", }, { capabilities: { tools: {}, }, }, ); // Request handlers server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [RETRIEVAL_TOOL], })); server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; if (name === "retrieve_from_aws_kb") { const { query, knowledgeBaseId, n = 3 } = args as Record<string, any>; // Determine which knowledge base ID to use let actualKnowledgeBaseId = knowledgeBaseId; // If no ID provided but we have configured IDs, use the first one if (!actualKnowledgeBaseId && configuredKnowledgeBaseIds.length > 0) { actualKnowledgeBaseId = configuredKnowledgeBaseIds[0]; console.error(`Using configured knowledge base ID: ${actualKnowledgeBaseId}`); } // If still no ID available, return an error if (!actualKnowledgeBaseId) { return { content: [{ type: "text", text: "No knowledge base ID provided. Either include a knowledgeBaseId in your request or configure AWS_KB_IDS in the environment." }], isError: true, }; } try { const result = await retrieveContext(query, actualKnowledgeBaseId, n); if (result.isRagWorking) { // Format RAG sources for readability const formattedSources = result.ragSources.map((source, index) => { return `Source ${index + 1}: ${source.fileName} (score: ${source.score.toFixed(3)})\n${source.snippet}`; }).join('\n\n'); return { content: [ { type: "text", text: result.context }, { type: "json", json: { ragSources: result.ragSources } } ], }; } else { return { content: [{ type: "text", text: "Retrieval failed or returned no results." }], }; } } catch (error) { return { content: [{ type: "text", text: `Error occurred: ${error}` }], }; } } else { return { content: [{ type: "text", text: `Unknown tool: ${name}` }], isError: true, }; } }); // Server startup async function runServer() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("AWS KB Retrieval Server running on stdio"); } runServer().catch((error) => { console.error("Fatal error running server:", error); process.exit(1); }); ```