핵심 구성 요소
- MCP (Model Context Protocol): 표준화된 도구 서비스입니다.
- Tool: 함수, API 또는 플러그인 형태의 기본 기능 단위입니다.
- Nacos: 서비스 등록, 검색 및 상태 확인을 담당하는 레지스트리입니다.
- 원격 호출: 로컬 에이전트가 Nacos를 통해 MCP 주소를 자동으로 탐색하고 연결하여 Tool을 실행합니다.
작동 원리
주요 역할
- MCP 서버
- 독립적으로 실행되는 도구 서비스로 여러 Tool을 제공합니다.
- 시작 시 Nacos에 자동으로 자신을 등록합니다.
- 등록 정보에는 서비스 이름, IP, 포트, 프로토콜 및 Tool 목록 메타데이터가 포함됩니다.
- Nacos
- MCP 서비스 인스턴스를 저장합니다.
- 서비스 발견, 상태 점검 및 하트비트 유지 기능을 제공합니다.
- 에이전트 (소비자)
- MCP 주소를 코드에 하드코딩하지 않습니다.
- Nacos에서 MCP 서비스를 동적으로 검색합니다.
- 검색한 Tool을 Toolkit에 로드하여 마치 로컬 함수처럼 원격 호출합니다.
등록 및 호출 흐름
[MCP 서버 시작] ↓ Nacos에 자동 등록 (서비스명: mcp-service-xxx) ↓ [에이전트 시작] ↓ Nacos에서 MCP 서비스 주소 검색 ↓ MCP 연결 후 Tool 목록 가져오기 ↓ 에이전트는 로컬 함수처럼 Tool 원격 호출
중요 규칙
- MCP는 반드시 Nacos에 서비스로 등록되어야 합니다.
- Tool은 개별적으로 등록되지 않으며 MCP에 속해 있어 MCP와 함께 메타데이터가 노출됩니다.
- 에이전트는 IP가 아닌 MCP 서비스 이름을 통해 서비스를 찾습니다.
- HTTP 기반 MCP 및 양방향 스트림 MCP 모두 지원됩니다.
환경 설정
필수 라이브러리를 설치합니다:
pip install -U agentscope nacos-sdk-python
Nacos 서버를 실행하고 웹 콘솔(http://127.0.0.1:8848/nacos)에 접속합니다. 기본 계정은 nacos/nacos입니다.
MCP 서버 구현 (Nacos 등록)
도구를 제공하는 독립적인 서비스로, 시작 시 Nacos에 자동 등록됩니다.
mcp_server.py 예제
import asyncio
from agentscope.mcp import MCPServer
from agentscope.mcp.server import HTTPServerConfig
from agentscope.a2a import NacosRegistry
from agentscope.tool import BaseTool
# 도구 정의
class Adder(BaseTool):
name: str = "add_numbers"
description: str = "두 숫자를 더한 결과를 반환합니다."
def forward(self, x: int, y: int) -> int:
return x + y
class WeatherChecker(BaseTool):
name: str = "check_weather"
description: str = "지정된 도시의 날씨 정보를 조회합니다."
def forward(self, location: str) -> str:
return f"{location}의 현재 날씨는 맑음이며 기온은 26도입니다."
# MCP 서버 초기화
server = MCPServer(
server_name="mcp-weather-tools",
version="1.0.0",
description="날씨 및 계산 관련 도구 서비스",
)
# 도구 등록
server.register_tool(Adder())
server.register_tool(WeatherChecker())
# Nacos 설정
registry = NacosRegistry(
server_addr="127.0.0.1:8848",
namespace="public",
username="nacos",
password="nacos",
)
# 서버 실행 및 자동 등록
async def launch():
config = HTTPServerConfig(host="0.0.0.0", port=9010)
await server.run_async(server_config=config, registry=registry)
if __name__ == "__main__":
asyncio.run(launch())
에이전트 구현 (MCP 탐색 및 원격 호출)
도구를 사용하는 클라이언트로, IP를 직접 지정하지 않고 Nacos에서 동적으로 MCP를 탐색합니다.
agent_consumer.py 예제
import asyncio
from agentscope import Agent
from agentscope.a2a import NacosRegistry
from agentscope.mcp import NacosMCPResolver
from agentscope.tool import Toolkit
from agentscope.agents import ReActAgent
# Nacos 연결
registry = NacosRegistry(
server_addr="127.0.0.1:8848",
namespace="public",
username="nacos",
password="nacos",
)
# MCP 탐색 및 도구 로드
async def load_remote_tools():
resolver = NacosMCPResolver(service_name="mcp-weather-tools", registry=registry)
client = await resolver.resolve()
remote_tools = await client.list_tools()
kit = Toolkit()
for tool in remote_tools:
kit.register_tool(tool)
print(f"✅ {len(remote_tools)}개의 도구를 Nacos에서 로드했습니다.")
print(f"🧰 사용 가능한 도구: {[t.name for t in remote_tools]}")
return kit
# 에이전트 생성 및 도구 호출
async def run_agent():
toolkit = await load_remote_tools()
assistant = ReActAgent(
name="helper",
toolkit=toolkit,
sys_prompt="도구를 활용해 질문에 답변하세요."
)
print("\n==== 덧셈 계산 테스트 ====")
result1 = await assistant.areply("10과 25를 더해줘")
print(result1)
print("\n==== 날씨 조회 테스트 ====")
result2 = await assistant.areply("서울의 날씨는?")
print(result2)
if __name__ == "__main__":
asyncio.run(run_agent())
실행 결과
✅ 2개의 도구를 Nacos에서 로드했습니다. 🧰 사용 가능한 도구: ['add_numbers', 'check_weather'] ==== 덧셈 계산 테스트 ==== 도구 add_numbers(x=10, y=25) 호출됨, 결과: 35 ==== 날씨 조회 테스트 ==== 도구 check_weather(location=서울) 호출됨, 결과: 서울의 현재 날씨는 맑음이며 기온은 26도입니다.
핵심 API 요약
- MCP 등록
await server.run_async(server_config=config, registry=registry)
- MCP 탐색
resolver = NacosMCPResolver(service_name="mcp-weather-tools", registry=registry) client = await resolver.resolve()
- 도구 목록 조회
tools = await client.list_tools()
자주 발생하는 문제
- MCP가 Nacos에 보이지 않는 경우:
run_async()에registry파라미터가 올바르게 전달되었는지 확인하세요. - 도구를 찾을 수 없는 경우: MCP 서버가 먼저 실행 중인지 확인하고,
NacosMCPResolver를 사용했는지 점검하세요. - 호출 시간 초과: 방화벽에서 MCP 포트(예: 9010)가 열려 있는지 확인하고 네트워크 연결 상태를 점검하세요.
- 도구는 별도로 등록해야 하나요?: 아니요. 도구는 MCP에 포함되며 MCP가 등록될 때 함께 등록됩니다.
요약
- MCP는 도구 서비스로서 시작 시 자동으로 Nacos에 등록됩니다.
- 에이전트는
NacosMCPResolver를 사용해 Nacos에서 MCP를 동적으로 탐색합니다. - 도구는 MCP에 종속되어 있으므로 별도로 등록할 필요가 없습니다.
- 원격 호출 코드는 로컬 호출과 동일하게 작성됩니다.
- 운영 환경에서는 MCP를 확장할 수 있으며 Nacos가 자동으로 부하 분산을 처리합니다.