|
| 1 | +#!/usr/bin/env node |
| 2 | +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; |
| 3 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 4 | +import { |
| 5 | + CallToolRequestSchema, |
| 6 | + ListToolsRequestSchema, |
| 7 | + Tool, |
| 8 | +} from "@modelcontextprotocol/sdk/types.js"; |
| 9 | +import { |
| 10 | + BedrockAgentRuntimeClient, |
| 11 | + RetrieveCommand, |
| 12 | + RetrieveCommandInput, |
| 13 | +} from "@aws-sdk/client-bedrock-agent-runtime"; |
| 14 | + |
| 15 | +// AWS client initialization |
| 16 | +const bedrockClient = new BedrockAgentRuntimeClient({ |
| 17 | + region: process.env.AWS_REGION, |
| 18 | + credentials: { |
| 19 | + accessKeyId: process.env.AWS_ACCESS_KEY_ID!, |
| 20 | + secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!, |
| 21 | + }, |
| 22 | +}); |
| 23 | + |
| 24 | +interface RAGSource { |
| 25 | + id: string; |
| 26 | + fileName: string; |
| 27 | + snippet: string; |
| 28 | + score: number; |
| 29 | +} |
| 30 | + |
| 31 | +async function retrieveContext( |
| 32 | + query: string, |
| 33 | + knowledgeBaseId: string, |
| 34 | + n: number = 3 |
| 35 | +): Promise<{ |
| 36 | + context: string; |
| 37 | + isRagWorking: boolean; |
| 38 | + ragSources: RAGSource[]; |
| 39 | +}> { |
| 40 | + try { |
| 41 | + if (!knowledgeBaseId) { |
| 42 | + console.error("knowledgeBaseId is not provided"); |
| 43 | + return { |
| 44 | + context: "", |
| 45 | + isRagWorking: false, |
| 46 | + ragSources: [], |
| 47 | + }; |
| 48 | + } |
| 49 | + |
| 50 | + const input: RetrieveCommandInput = { |
| 51 | + knowledgeBaseId: knowledgeBaseId, |
| 52 | + retrievalQuery: { text: query }, |
| 53 | + retrievalConfiguration: { |
| 54 | + vectorSearchConfiguration: { numberOfResults: n }, |
| 55 | + }, |
| 56 | + }; |
| 57 | + |
| 58 | + const command = new RetrieveCommand(input); |
| 59 | + const response = await bedrockClient.send(command); |
| 60 | + const rawResults = response?.retrievalResults || []; |
| 61 | + const ragSources: RAGSource[] = rawResults |
| 62 | + .filter((res) => res?.content?.text) |
| 63 | + .map((result, index) => { |
| 64 | + const uri = result?.location?.s3Location?.uri || ""; |
| 65 | + const fileName = uri.split("/").pop() || `Source-${index}.txt`; |
| 66 | + return { |
| 67 | + id: (result.metadata?.["x-amz-bedrock-kb-chunk-id"] as string) || `chunk-${index}`, |
| 68 | + fileName: fileName.replace(/_/g, " ").replace(".txt", ""), |
| 69 | + snippet: result.content?.text || "", |
| 70 | + score: (result.score as number) || 0, |
| 71 | + }; |
| 72 | + }) |
| 73 | + .slice(0, 3); |
| 74 | + |
| 75 | + const context = rawResults |
| 76 | + .filter((res): res is { content: { text: string } } => res?.content?.text !== undefined) |
| 77 | + .map(res => res.content.text) |
| 78 | + .join("\n\n"); |
| 79 | + |
| 80 | + return { |
| 81 | + context, |
| 82 | + isRagWorking: true, |
| 83 | + ragSources, |
| 84 | + }; |
| 85 | + } catch (error) { |
| 86 | + console.error("RAG Error:", error); |
| 87 | + return { context: "", isRagWorking: false, ragSources: [] }; |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +// Define the retrieval tool |
| 92 | +const RETRIEVAL_TOOL: Tool = { |
| 93 | + name: "retrieve_from_aws_kb", |
| 94 | + description: "Performs retrieval from the AWS Knowledge Base using the provided query and Knowledge Base ID.", |
| 95 | + inputSchema: { |
| 96 | + type: "object", |
| 97 | + properties: { |
| 98 | + query: { type: "string", description: "The query to perform retrieval on" }, |
| 99 | + knowledgeBaseId: { type: "string", description: "The ID of the AWS Knowledge Base" }, |
| 100 | + n: { type: "number", default: 3, description: "Number of results to retrieve" }, |
| 101 | + }, |
| 102 | + required: ["query", "knowledgeBaseId"], |
| 103 | + }, |
| 104 | +}; |
| 105 | + |
| 106 | +// Server setup |
| 107 | +const server = new Server( |
| 108 | + { |
| 109 | + name: "aws-kb-retrieval-server", |
| 110 | + version: "0.2.0", |
| 111 | + }, |
| 112 | + { |
| 113 | + capabilities: { |
| 114 | + tools: {}, |
| 115 | + }, |
| 116 | + }, |
| 117 | +); |
| 118 | + |
| 119 | +// Request handlers |
| 120 | +server.setRequestHandler(ListToolsRequestSchema, async () => ({ |
| 121 | + tools: [RETRIEVAL_TOOL], |
| 122 | +})); |
| 123 | + |
| 124 | +server.setRequestHandler(CallToolRequestSchema, async (request) => { |
| 125 | + const { name, arguments: args } = request.params; |
| 126 | + |
| 127 | + if (name === "retrieve_from_aws_kb") { |
| 128 | + const { query, knowledgeBaseId, n = 3 } = args as Record<string, any>; |
| 129 | + try { |
| 130 | + const result = await retrieveContext(query, knowledgeBaseId, n); |
| 131 | + if (result.isRagWorking) { |
| 132 | + return { |
| 133 | + content: [ |
| 134 | + { type: "text", text: `Context: ${result.context}` }, |
| 135 | + { type: "text", text: `RAG Sources: ${JSON.stringify(result.ragSources)}` }, |
| 136 | + ], |
| 137 | + }; |
| 138 | + } else { |
| 139 | + return { |
| 140 | + content: [{ type: "text", text: "Retrieval failed or returned no results." }], |
| 141 | + }; |
| 142 | + } |
| 143 | + } catch (error) { |
| 144 | + return { |
| 145 | + content: [{ type: "text", text: `Error occurred: ${error}` }], |
| 146 | + }; |
| 147 | + } |
| 148 | + } else { |
| 149 | + return { |
| 150 | + content: [{ type: "text", text: `Unknown tool: ${name}` }], |
| 151 | + isError: true, |
| 152 | + }; |
| 153 | + } |
| 154 | +}); |
| 155 | + |
| 156 | +// Server startup |
| 157 | +async function runServer() { |
| 158 | + const transport = new StdioServerTransport(); |
| 159 | + await server.connect(transport); |
| 160 | + console.error("AWS KB Retrieval Server running on stdio"); |
| 161 | +} |
| 162 | + |
| 163 | +runServer().catch((error) => { |
| 164 | + console.error("Fatal error running server:", error); |
| 165 | + process.exit(1); |
| 166 | +}); |
0 commit comments