간단한 MCP Server를 Amazon Bedrock에서 사용하기

2025. 4. 4. 16:35개발/AWS

지난 번 포스팅에서 만든 top_song을 aws bedrock에서 사용하는 방법을 알아보도록 하겠습니다.

 

간단한 MCP Server를 만들고 Inspector로 확인하기

MCP 사이트에는 Quickstart로 Server를 만드는 방법을 제공하고 있습니다. For Server Developers - Model Context ProtocolSince this is the US National Weather service, the queries will only work for US locations.modelcontextprotocol.io저

walkthinksleep.tistory.com

MCP Client에 대한 상세한 정보는 MCP 사이트를 참조하시면 되겠습니다.

 

For Client Developers - Model Context Protocol

If you’re continuing the weather tutorial from the server quickstart, your command might look something like this: python client.py .../quickstart-resources/weather-server-python/weather.py

modelcontextprotocol.io

먼저 MCP Client를 만들고 서버에 연결하는 방법을 구현합니다.

async def connect_to_server(self):
    server_script_path = self.command

    server_params = StdioServerParameters(
        command="python",
        args=[server_script_path],
        env=None
    )

    stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
    self.stdio, self.write = stdio_transport
    self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))

    return await self.session.initialize()

 

그리고 AWS Bedrock의 Tool로 쓸 수 있게 사용 가능한 도구를 가져오는 함수도 만들어줍니다.

async def get_available_tools(self):
    response = await self.session.list_tools()

    tools = response.tools

    tool_specs = []
    for tool in tools:
        tool_specs.append({
            'toolSpec': {
                'name': tool.name,
                'description': tool.description or "No Description",
                "inputSchema": {
                    "json": tool.inputSchema
                }
            }
        })

    return tool_specs

 

get_available_tools을 이용해서 Bedrock에 쓸 수 있는 toolConfig를 가져올 수 있습니다.

mcp_file_path = "/Users/seobs/mcp/song.py"

async with MCPClient(mcp_file_path) as mcp_client:
    await mcp_client.connect_to_server()
    tools = await mcp_client.get_available_tools()

response = bedrock_client.converse(
    modelId="anthropic.claude-3-haiku-20240307-v1:0",
    messages=message_list,
    system=[{"text": system_prompt}],
    toolConfig={
        "tools": tools
    },
)

여기까지 해서 실행하면 모델은 tool의 사용을 요구하게 됩니다.
그렇다면 도구를 가져와서 모델에 전달하는 것 까지는 잘 되었다는 소리입니다.

MCP Client에서 도구를 실행하는 코드를 만들어줍니다.

async def execute_tool(self, tool_name: str, arguments: dict):
    result = await self.session.call_tool(tool_name, arguments=arguments)
    return result

이제 다시 Bedrock에서 요청 받은 tool을 실행하는 코드를 작성해봅니다.

message_list.append(response['output']['message'])

if response['stopReason'] == 'tool_use':
    tool_requests = response['output']['message']['content']
    for tool_request in tool_requests:

        if 'toolUse' in tool_request:
            tool = tool_request['toolUse']

            tool_id = tool['toolUseId']
            tool_name = tool['name']
            tool_input = tool['input']

            async with MCPClient(mcp_file_path) as mcp_client:
                await mcp_client.connect_to_server()
                tool_result = await mcp_client.execute_tool(tool_name, tool_input)

            message_list.append({
                "role": "user",
                "content": [{
                    "toolResult": {
                        "toolUseId": tool_id,
                        "content": [{"text": tool_result.content[0].text}]
                    }
                }],
            })

            response = bedrock_client.converse(
                modelId="anthropic.claude-3-haiku-20240307-v1:0",
                messages=message_list,
                system=[{"text": system_prompt}],
                toolConfig={
                    "tools": tools
                },
            )

여기까지 하면 완성입니다.

마지막으로 받은 response의 output의 경우 저는 이렇게 나왔습니다.

답변에 tool을 사용했다는 얘기는 나오지만 잘 작동하는 것을 볼 수 있습니다.

만약 전체 코드를 확인하고 싶으면 아래 Github에서 확인하세요.

 

GitHub - calc2te/mcp-and-amazon-bedrock

Contribute to calc2te/mcp-and-amazon-bedrock development by creating an account on GitHub.

github.com

다음에는 top-song을 npm에 올리고 다른 MCP Server와 함께 사용해보도록 하겠습니다.

 

MCP Server를 npm에 올리고 다른 MCP와 함께 Amazon Bedrock에서 사용하기

지난 번 포스팅에서 사용했던 top_song을 npm에 올리고 다른 MCP Server와 함께 Bedrock에서 사용해보겠습니다. 간단한 MCP Server를 Amazon Bedrock에서 사용하기지난 번 포스팅에서 만든 top_song을 aws bedrock에

walkthinksleep.tistory.com