MCP Runtime 标志

MCP Runtime

社区
kyopark2014

It show how to deploy MCP tools using AgentCore.

发布者kyopark2014
代码仓库mcp-runtime
语言Python
复刻数
2
星标数
12
可用工具
0
传输类型stdio, streamable-http
分类
链接
  • 将工具接入 AI 工作流

    MCP Runtime 提供 MCP 功能,可供兼容的 AI 客户端和智能体使用。

  • 0 个可用工具

    浏览下方可调用的操作;如果服务器提供了名称和描述,也会一并显示。

  • 可直接复制的配置

    使用安装配置片段,在您首选的 MCP 客户端中配置此服务器。

  • 开源社区热度

    关联的代码仓库有 12 个 Star 和 2 个 Fork。

MCP Runtime

여기에서는 AgentCore Runtime을 이용하여 streamable HTTP 방식의 MCP 서버를 서버리스 환경에서 배포하고 활용하는 방법에 대해 설명합니다. 전체적인 architecture는 아래와 같습니다. 사용자가 streamlit으로 구현된 생성형 AI application을 통해 질문을 입력하면, LangGraph 또는 Strands agent가 mutli step reasoning을 통해, Kubernetes로 된 중요한 workload를 조회하거나 관리할 수 있고, 사내의 중요한 데이터를 RAG를 이용해 활용할 수 있습니다. 여기에서는 Knowledge base를 조회하는 kb-retriever와 AWS 인프라를 관리할 수 있는 use-aws를 MCP tool로 제공하며, 이 tool들은 AgentCore에 runtime 또는 AgentCore Gateway로 배포됩니다.

MCP tool의 구현

AWS 인프라 관리: use-aws

mcp_server_use_aws.py에서는 아래와 같이 use_aws tool을 등록합니다. use_aws tool은 agent가 전달하는 service_name, operation_name, parameters를 받아서 실행하고 결과를 리턴합니다. service_name은 s3, ec2와 같은 서비스 명이며, operation_name은 list_buckets와 같은 AWS CLI 명령어 입니다. 또한, parameters는 이 명령어를 수행하는데 필요한 값입니다.

python
import use_aws as aws_utils

@mcp.tool()
def use_aws(service_name, operation_name, parameters, region, label, profile_name) -> Dict[str, Any]:
    console = aws_utils.create()
    available_operations = get_available_operations(service_name)

    client = get_boto3_client(service_name, region, profile_name)
    operation_method = getattr(client, operation_name)

    response = operation_method(**parameters)
    for key, value in response.items():
        if isinstance(value, StreamingBody):
            content = value.read()
            try:
                response[key] = json.loads(content.decode("utf-8"))
            except json.JSONDecodeError:
                response[key] = content.decode("utf-8")
    return {
        "status": "success",
        "content": [{"text": f"Success: {str(response)}"}],
    }

use-aws은 use_aws.py의 MCP 버전입니다.

RAG의 활용: kb-retriever

kb-retriever를 이용해 완전관리형 RAG 서비스인 Knowledge base의 정보를 조회할 수 있습니다.mcp_server_retrieve.py에서는 agent가 전달하는 keyword를 이용해 mcp_retrieve의 retrieve를 호출합니다.

python
@mcp.tool()
def retrieve(keyword: str) -> str:
    return mcp_retrieve.retrieve(keyword)    

kb-retriever는 아래와 같이 bedrock-agent-runtime를 이용하여 Knowledge Base를 조회합니다. 이때, number_of_results의 결과를 얻은 후에 content와 reference 정보를 추출하여 활용합니다.

python
bedrock_agent_runtime_client = boto3.client("bedrock-agent-runtime", region_name=bedrock_region)
response = bedrock_agent_runtime_client.retrieve(
    retrievalQuery={"text": query},
    knowledgeBaseId=knowledge_base_id,
        retrievalConfiguration={
            "vectorSearchConfiguration": {"numberOfResults": number_of_results},
        },
    )
retrieval_results = response.get("retrievalResults", [])
json_docs = []
for result in retrieval_results:
    text = url = name = None
    if "content" in result:
        content = result["content"]
        if "text" in content:
            text = content["text"]
    if "location" in result:
        location = result["location"]
        if "s3Location" in location:
            uri = location["s3Location"]["uri"] if location["s3Location"]["uri"] is not None else ""            
            name = uri.split("/")[-1]
            url = uri # TODO: add path and doc_prefix            
        elif "webLocation" in location:
            url = location["webLocation"]["url"] if location["webLocation"]["url"] is not None else ""
            name = "WEB"
    json_docs.append({
        "contents": text,              
        "reference": {
            "url": url,                   
            "title": name,
            "from": "RAG"
        }
    })

AgentCore Runtime

AgentCore Runtime을 이용하면, container로 동작하는 Streamable HTTP 방식의 MCP 서버를 생성하여 활용할 수 있습니다.

Runtime 배포 준비

AgentCore로 배포하기 위해서는 MCP 설정시 mcp_server_retrieve.py와 같이 host를 "0.0.0.0"으로 설정하고 외부로는 Dockerfile와 같이 8000 포트를 expose 합니다.

python
mcp = FastMCP(
    name = "mcp-retrieve",
    instructions=(
        "You are a helpful assistant. "
        "You retrieve documents in RAG."
    ),
    host="0.0.0.0",
    stateless_http=True
)

AgentCore의 runtime으로 MCP를 배포한 후에 활용할 때에는 bearer token을 이용해 인증을 수행합니다. bearer token은 Cognito와 같은 서비스를 통해 생성할 수 있습니다. 아래와 같이 Cognito에 정의한 username/password를 이용해 access token를 생성합니다.

python
client = boto3.client('cognito-idp', region_name=region)
response = client.initiate_auth(
    ClientId=client_id,
    AuthFlow='USER_PASSWORD_AUTH',
    AuthParameters={
        'USERNAME': username,
        'PASSWORD': password
    }
)
auth_result = response['AuthenticationResult']
access_token = auth_result['AccessToken']

AgentCore에 MCP runtime을 배포하면 agent_arn을 얻을 수 있습니다. 이 값은 AgentCore에서 생성할 때 알 수 있으며, 아래와 같이 agent_runtime_name을 가지고 검색할 수도 있습니다.

python
client = boto3.client('bedrock-agentcore-control', region_name='us-west-2')
response = client.list_agent_runtimes()
agentRuntimes = response['agentRuntimes']
for agentRuntime in agentRuntimes:
    if agentRuntime["agentRuntimeName"] == agent_runtime_name:
        return agentRuntime["agentRuntimeArn"]

Agent의 arn을 url encoding해서 아래와 같이 mcp_url을 생성합니다. 이때 header의 Authorization에 Cognito를 이용해 생성한 bearer token을 입력합니다.

python
encoded_arn = agent_arn.replace(':', '%3A').replace('/', '%2F')    
mcp_url = f"https://bedrock-agentcore.{region}.amazonaws.com/runtimes/{encoded_arn}/invocations?qualifier=DEFAULT"
headers = {
    "Authorization": f"Bearer {bearer_token}",
    "Content-Type": "application/json",
    "Accept": "application/json, text/event-stream"
}

이제 mcp_url, headers는 아래와 같이 MCP server의 설정 정보로 활용됩니다.

python
"mcpServers": {
    "kb-retriever": {
        "type": "streamable_http",
        "url": f"https://bedrock-agentcore.{region}.amazonaws.com/runtimes/{encoded_arn}/invocations?qualifier=DEFAULT",
        "headers": {
            "Authorization": f"Bearer {bearer_token}",
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream"
        }
    }
}

Runtime 배포 방법

AgentCore runtime으로 배포할 때에는 Boto3 API나, AgentCore CLI를 활용할 수 있습니다.

Boto3 API

생성된 policy의 이름은 BedrockAgentCoreMCPRoleFor에 project name을 합한 형태입니다. config.json.sample을 config.json으로 변경한 후에 필요한 값들을 채워줍니다. 이후 아래와 같이 IAM policy를 생성합니다. 상세코드는 create_iam_policies.py을 참조합니다.

text
python create_iam_policies.py

MCP server 인증시 사용할 bearer token을 등록합니다. 여기서는 Cognito의 access token으로 bearer token을 생성하고 secret manager에 등록합니다. 상세 코드는 create_bearer_token.py를 참조합니다.

text
python create_bearer_token.py

MCP runtime을 생성하기 위해 ECR에 이미지를 푸쉬합니다. 상세 배치파일 내용은 push-to-ecr.sh을 참조합니다.

text
./push-to-ecr.sh

이제 AgentCore에 MCP runtime을 생성합니다. 상세 코드는 create_mcp_runtime.py을 참조합니다.

text
python create_mcp_runtime.py

배포가 정상적으로 되었는지 아래와 같이 확인할 수 있습니다. 상세 코드는 test_mcp_remote.py을 참조합니다.

text
python test_mcp_remote.py

이때의 결과는 아래와 같습니다.

AgentCore CLI 활용 방법

Boto3를 이용한 API 이외에도 AgentCore Toolkit을 이용해 배포할 수 있습니다.

text
pip install bedrock-agentcore-starter-toolkit

이후 아래와 설치를 준비합니다. 아래 명령어로 Dockerfile과 .bedrock_agentcore.yaml이 생성됩니다.

text
python setup.py

AgentCore의 상태는 아래 명령어로 확인할 수 있습니다.

text
agentcore status

생성된 Docker 파일을 배포합니다.

text
agentcore launch

이후 아래와 같이 동작을 확인할 수 있습니다.

text
# Invoke your deployed agent
agentcore invoke '{"prompt": "Hello from Bedrock AgentCore!"}'

Local Test

MCP 서버는 아래와 같이 실행합니다.

text
python mcp_server_use_aws.py

기본 Client의 실행은 아래와 같습니다. 아래 test_mcp_local.py은 streamable http로 "http://localhost:8000/mcp" 로 연결할 수 있는 MCP 서버의 정보를 가져와 사용할 수 있는 tool에 대한 정보를 제공합니다.

text
python test_mcp_local.py

실행 결과

Streamlit app을 아래와 같이 실행합니다.

python
streamlit run application/app.py

이때 아래와 같이 LangGraph와 Strand agent를 선택할 수 있고, use-aws와 kb-retriever를 이용할 수 있습니다. Streamable HTTP 방식 MCP를 배포하기 전에 docker를 선택해서 로컬에서 테스트 할 수 있으며, 다양한 언어 모델을 선택할 수 있습니다.

왼쪽 메뉴의 MCP Config에서 "use_aws (streamable)"을 선택한 후에 "내 EKS 현황은?"라고 질문하면, 아래와 같이 use-aws tool을 이용하여 EKS의 상황을 조회할 수 있습니다.

또한, "kb-retriever (remote)"을 선택한 후에 "보일러 에러 코드?"로 입력하면, Streamable HTTP를 지원하는 knowledge base MCP에 접속하여 관련된 문서를 아래와 같이 가져와서 답변할 수 있습니다.

Reference

Hosting MCP Server on Amazon Bedrock AgentCore Runtime

Bedrock AgentCore Starter Toolkit

LangChain MCP Adapters

Strands Agents

安装

TypingMind
{
  "mcpServers": {
    "mcp-runtime": {
      "command": "agentcore",
      "args": [
        "invoke",
        "{\"prompt\": \"Hello from Bedrock AgentCore!\"}"
      ]
    }
  }
}

将 MCP Runtime MCP 与多个 AI 模型配合使用

TypingMind 在工作区级别连接 MCP 工具,因此连接 MCP Runtime 后,您就可以在 TypingMind 中搭配不同的 AI 模型使用,无需为每个模型单独设置。 您可以在自己的设备上本地运行 MCP,也可以通过 URL 连接远程 MCP 服务器。

方式 1:使用本地连接器

如果 MCP 服务器需要访问您电脑上的本地文件、应用或私有资源,请选择此方式。

1

打开 MCP 设置

在 TypingMind 中,依次前往“设置”、“高级设置”和“模型上下文协议”,然后选择“设置连接器”。

  1. 在您的浏览器中打开 TypingMind。
  2. 点击“设置”图标。
  3. 进入“高级设置”。
  4. 打开“模型上下文协议”部分。
  5. 点击“设置连接器”,然后选择“此设备”。
TypingMind MCP 连接器设置界面,已选择“此设备”
2

运行连接器命令

选择“此设备”,从 TypingMind 复制命令并在终端中运行。使用 MCP 时,请保持该进程运行。

  1. 复制 TypingMind 显示的设置命令。
  2. 在 macOS 上打开“终端”,或在 Windows 上打开 Windows Terminal。
  3. 粘贴并运行命令。
  4. 如果终端询问您是否继续,请确认安装软件包。
  5. 使用 MCP 工具时,请保持终端窗口及其中的进程运行。
3

将 MCP Runtime 添加为服务器

当连接器状态为“就绪”时,点击“编辑服务器”,然后粘贴 MCP 服务器配置。

  1. 等待连接器状态显示为“就绪”。
  2. 点击“编辑服务器”。
  3. 粘贴 MCP Runtime MCP 服务器配置。
  4. 保存服务器列表。
  5. 如需确认连接器是否仍处于就绪状态,请刷新。
TypingMind MCP 设置界面,显示正在运行的服务器和“编辑服务器”按钮
{
  "mcpServers": {
    "mcp-runtime": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

在不同模型中使用同一连接

保存服务器列表,打开“插件”,启用 MCP Runtime MCP 工具,然后在 TypingMind 中选择任意受支持的 AI 模型,即可在聊天中使用这些工具,或将其分配给智能体。

  1. 在 TypingMind 中打开“插件”页面。
  2. 启用 MCP Runtime MCP 工具。
  3. 开始聊天并选择您想使用的 AI 模型。
  4. 在聊天中使用 MCP 工具,或将其分配给 AI 智能体。
  5. 根据需要随时切换到其他 AI 模型,无需重新连接 MCP。
在 TypingMind 聊天中使用已启用的 MCP 工具和选定的 AI 模型
您能使用 MCP Runtime 帮我完成这项任务吗?
MCP Runtime
当然。我已阅读。
以下是我使用 MCP Runtime 得到的结果。

方式 2:添加 MCP 服务器 URL

如果 MCP Runtime 已托管在远程服务器上,或您的团队希望让多个用户共用一个连接器,请选择此方式。

1

打开 MCP 连接器

在 TypingMind 中,前往“插件”,打开“MCP 连接器”,然后选择“添加 URL”。

  1. 在您的浏览器中打开 TypingMind。
  2. 进入“插件”。
  3. 打开“MCP 连接器”。
  4. 点击“添加 URL”。
TypingMind 的“添加自定义 MCP 服务器 URL”表单
2

粘贴服务器 URL

在“服务器 URL”字段中输入 提供商提供的 MCP 服务器 URL。根据服务器要求,添加连接名称、描述、图标、自定义 HTTP 请求头或 OAuth 客户端设置。

  1. 将 提供商提供的 MCP 服务器 URL 粘贴到“服务器 URL”字段中。
  2. 为 MCP Runtime 输入连接名称。
  3. 您可以添加描述和图标,以便更容易识别此连接。
  4. 如果服务器需要身份验证,请添加自定义 HTTP 请求头或 OAuth 客户端信息。
3

创建连接

点击“创建连接”,然后返回插件列表,确认新的 MCP 连接显示为“有效”。

  1. 点击“创建连接”。
  2. 返回 MCP 连接器列表。
  3. 确认 MCP Runtime 连接显示为“有效”。
  4. 如果连接未立即出现,请刷新插件列表。
4

切换模型,无需重新连接

使用您偏好的模型开始聊天,在“插件”中启用 MCP Runtime 工具,并根据需要随时切换到其他模型。该 MCP 连接在 TypingMind 工作区中仍然可用。

  1. 在 TypingMind 中开始新聊天。
  2. 选择您想使用的 AI 模型。
  3. 在“插件”中启用 MCP Runtime 工具。
  4. 需要时,请让模型使用该工具。
  5. 切换到其他 AI 模型,继续使用同一个 MCP 连接。
在 TypingMind 聊天中使用已启用的 MCP 工具和选定的 AI 模型
您能使用 MCP Runtime 帮我完成这项任务吗?
MCP Runtime
当然。我已阅读。
以下是我使用 MCP Runtime 得到的结果。

常见问题

MCP Runtime MCP 服务器有什么用途?

MCP Runtime 是一个 MCP 服务器,可让兼容的 AI 客户端连接外部工具并获取上下文。在 TypingMind 中,只需添加一次此 MCP 服务器,即可在您的 AI 工作区中使用其工具。

可以在 TypingMind 中让多个 AI 模型使用 MCP Runtime MCP 吗?

可以。TypingMind 在工作区层面连接 MCP 工具,因此您可以让 Claude、ChatGPT、Gemini 等不同 AI 模型,或您在 TypingMind 中配置的其他模型使用 MCP Runtime,而无需为每个模型单独配置 MCP 服务器。

为什么在 TypingMind 中使用 MCP Runtime MCP?

TypingMind 将多个 AI 模型、提示词、插件、AI 智能体、API 密钥和 MCP 工具整合到同一个工作区中,是优秀的大语言模型聊天前端之一。连接 MCP Runtime 后,您可以在偏好的不同模型中使用其 MCP 工具,同时在 TypingMind 中井然有序地管理聊天工作流程。

如何将 MCP Runtime MCP 连接到 TypingMind?

您可以通过本地 MCP 连接器,或添加远程 MCP 服务器 URL,在 TypingMind 中连接 MCP Runtime。当服务器需要访问您设备上的文件、应用或私有资源时,请使用本地连接器;当 MCP 服务器托管在远程时,请使用服务器 URL。

MCP Runtime MCP 在 TypingMind 中提供哪些工具?

MCP Runtime 提供 MCP 功能,您可以在 TypingMind 的插件页面启用这些功能,然后在聊天中使用,或将其分配给 AI 智能体。

使用 MCP Runtime MCP 需要向 TypingMind 提供我的 API 密钥吗?

不需要。TypingMind 采用本地优先的设计,让您自行掌控模型提供商、API 密钥、提示词和 MCP 配置。如果 MCP Runtime 需要身份验证,请在创建连接时,为该 MCP 服务器添加所需的请求头、OAuth 设置或本地配置。

相关 MCP 服务器

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇