Ch6. MCP 서버 연동
Model Context Protocol 설정, 서버 추가, 도구/리소스 관리
MCP(Model Context Protocol)는 Kiro를 외부 도구·데이터베이스·API에 연결하는 표준 프로토콜입니다. GitHub, 데이터베이스, 사내 도구 등을 Kiro에서 직접 사용할 수 있습니다.
v0.10~v0.11 MCP 업데이트
- v0.11: MCP Registry Governance — 엔터프라이즈 관리자가 허용 MCP 서버를 중앙 관리
- v0.10: MCP Prompts 지원 — MCP 서버가 프롬프트/템플릿/elicitation을 채팅에 직접 노출
- v0.10+: Remote MCP 서버 네이티브 지원
MCP 개념
Kiro는 MCP 클라이언트로서 여러 MCP 서버에 동시에 연결합니다. 각 서버는 도구(tools), 리소스(resources), 프롬프트(prompts)를 제공합니다.
MCP 서버 설정
설정 파일 위치
- 워크스페이스:
.kiro/settings/mcp.json - 사용자 전역:
~/.kiro/settings/mcp.json
기본 설정 구조
{
"mcpServers": {
"github": {
"command": "uvx",
"args": ["mcp-server-github"],
"env": {
"GITHUB_TOKEN": "ghp_your_token_here"
},
"disabled": false,
"autoApprove": ["search_repositories", "get_file_contents"]
},
"postgres": {
"command": "uvx",
"args": ["mcp-server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost/db"
},
"disabled": false,
"autoApprove": []
}
}
}인기 MCP 서버들
GitHub 서버
{
"github": {
"command": "uvx",
"args": ["mcp-server-github"],
"env": {
"GITHUB_TOKEN": "ghp_your_personal_access_token"
},
"autoApprove": [
"search_repositories",
"get_file_contents",
"list_issues",
"create_issue"
]
}
}제공 도구:
search_repositories: 리포지토리 검색get_file_contents: 파일 내용 조회list_issues: 이슈 목록 조회create_issue: 새 이슈 생성create_pull_request: PR 생성
데이터베이스 서버 (PostgreSQL)
{
"postgres": {
"command": "uvx",
"args": ["mcp-server-postgres"],
"env": {
"DATABASE_URL": "postgresql://username:password@localhost:5432/database_name"
},
"autoApprove": ["query", "list_tables"]
}
}제공 도구:
query: SQL 쿼리 실행list_tables: 테이블 목록 조회describe_table: 테이블 스키마 조회
Slack 서버
{
"slack": {
"command": "uvx",
"args": ["mcp-server-slack"],
"env": {
"SLACK_BOT_TOKEN": "xoxb-your-bot-token",
"SLACK_APP_TOKEN": "xapp-your-app-token"
},
"autoApprove": ["list_channels"]
}
}제공 도구:
send_message: 메시지 전송list_channels: 채널 목록 조회get_channel_history: 채널 히스토리 조회
파일 시스템 서버
{
"filesystem": {
"command": "uvx",
"args": ["mcp-server-filesystem", "/allowed/path"],
"autoApprove": ["read_file", "list_directory"]
}
}MCP 서버 관리
VS Code 명령어
Ctrl/Cmd + Shift + P
> Kiro: Configure MCP Servers
> Kiro: List MCP Servers
> Kiro: Restart MCP Server서버 상태 확인
Kiro 채팅에서 MCP 서버 상태를 확인할 수 있습니다:
현재 연결된 MCP 서버들을 보여주세요autoApprove 설정
자주 사용하는 안전한 도구들은 autoApprove에 추가하여 매번 승인하지 않도록 할 수 있습니다.
{
"github": {
"autoApprove": [
"search_repositories", // 리포지토리 검색 (읽기 전용)
"get_file_contents", // 파일 내용 조회 (읽기 전용)
"list_issues" // 이슈 목록 조회 (읽기 전용)
]
}
}보안 주의
create_issue, delete_file 등 쓰기 작업은 autoApprove에 추가하지 않는 것을 권장합니다.
커스텀 MCP 서버 작성
간단한 MCP 서버 예시
# custom_server.py
import asyncio
from mcp.server import Server
from mcp.types import Tool, TextContent
app = Server("custom-tools")
@app.list_tools()
async def list_tools():
return [
Tool(
name="get_weather",
description="Get current weather for a city",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "get_weather":
city = arguments["city"]
# 실제 날씨 API 호출 로직
weather_data = f"Sunny, 25°C in {city}"
return TextContent(type="text", text=weather_data)
if __name__ == "__main__":
asyncio.run(app.run())커스텀 서버 설정
{
"custom-weather": {
"command": "python",
"args": ["custom_server.py"],
"cwd": "/path/to/your/server",
"env": {
"WEATHER_API_KEY": "your_api_key"
}
}
}실전 활용 사례
1. GitHub 이슈 관리 자동화
"GitHub에서 'bug' 라벨이 있는 열린 이슈들을 조회하고,
각 이슈에 대해 우선순위를 분석해서 정리해주세요."Kiro가 자동으로:
- GitHub MCP 서버를 통해 이슈 검색
- 각 이슈 내용 분석
- 우선순위 매트릭스 생성
2. 데이터베이스 스키마 분석
"현재 데이터베이스의 모든 테이블을 조회하고,
각 테이블 간의 관계를 분석해서 ERD를 그려주세요."Kiro가 자동으로:
- PostgreSQL MCP 서버로 테이블 목록 조회
- 각 테이블의 스키마 분석
- 외래키 관계 파악
- Mermaid ERD 생성
3. 팀 커뮤니케이션 자동화
"오늘 배포 완료되면 개발팀 Slack 채널에
배포 완료 메시지를 전송해주세요."Hooks와 연동하여:
- 배포 완료 이벤트 감지
- Slack MCP 서버로 메시지 전송
문제 해결
연결 실패
# MCP 서버 로그 확인
tail -f ~/.kiro/logs/mcp-server-*.log
# 서버 재시작
Ctrl/Cmd + Shift + P > Kiro: Restart MCP Server권한 오류
{
"github": {
"env": {
"GITHUB_TOKEN": "ghp_새로운_토큰"
}
}
}성능 최적화
{
"database": {
"env": {
"MAX_QUERY_RESULTS": "100",
"QUERY_TIMEOUT": "30"
}
}
}고급 MCP 활용 패턴
1. 체인형 MCP 서버 구성
여러 MCP 서버를 연결하여 복잡한 워크플로우를 구성할 수 있습니다:
{
"mcpServers": {
"data-source": {
"command": "uvx",
"args": ["mcp-server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost/db"
}
},
"data-processor": {
"command": "uvx",
"args": ["mcp-server-python"],
"env": {
"PYTHON_PATH": "./scripts"
}
},
"notification": {
"command": "uvx",
"args": ["mcp-server-slack"],
"env": {
"SLACK_TOKEN": "xoxb-your-token"
}
}
}
}2. 조건부 MCP 서버 활성화
프로젝트 타입이나 환경에 따라 다른 MCP 서버를 활성화:
{
"mcpServers": {
"development-tools": {
"command": "uvx",
"args": ["mcp-server-dev-tools"],
"disabled": false,
"env": {
"NODE_ENV": "development"
}
},
"production-monitoring": {
"command": "uvx",
"args": ["mcp-server-monitoring"],
"disabled": true,
"env": {
"NODE_ENV": "production"
}
}
}
}3. 커스텀 MCP 서버 개발 팁
효율적인 MCP 서버 개발을 위한 모범 사례:
# 에러 처리와 로깅
import logging
from mcp.server import Server
logger = logging.getLogger(__name__)
app = Server("custom-server")
@app.call_tool()
async def call_tool(name: str, arguments: dict):
try:
logger.info(f"Tool called: {name} with args: {arguments}")
if name == "process_data":
# 입력 검증
if not arguments.get("data"):
raise ValueError("Data parameter is required")
# 실제 처리 로직
result = await process_data_async(arguments["data"])
logger.info(f"Tool {name} completed successfully")
return TextContent(type="text", text=result)
except Exception as e:
logger.error(f"Tool {name} failed: {str(e)}")
return TextContent(
type="text",
text=f"Error: {str(e)}"
)참고 문서
- MCP 프로토콜 스펙: https://modelcontextprotocol.io/
- Kiro 공식 사이트: https://kiro.dev
- MCP 서버 목록: https://github.com/modelcontextprotocol/servers
엔터프라이즈급 MCP 아키텍처
🏗️ 마이크로서비스 MCP 패턴
대규모 시스템에서 MCP 서버를 마이크로서비스처럼 구성:
{
"mcpServers": {
"user-service": {
"command": "docker",
"args": ["run", "--rm", "company/mcp-user-service"],
"env": {
"DATABASE_URL": "${USER_DB_URL}",
"REDIS_URL": "${REDIS_URL}"
}
},
"payment-service": {
"command": "docker",
"args": ["run", "--rm", "company/mcp-payment-service"],
"env": {
"STRIPE_KEY": "${STRIPE_SECRET_KEY}",
"WEBHOOK_SECRET": "${STRIPE_WEBHOOK_SECRET}"
}
},
"analytics-service": {
"command": "kubernetes",
"args": ["exec", "analytics-pod", "--", "python", "mcp_server.py"],
"env": {
"BIGQUERY_CREDENTIALS": "${GCP_CREDENTIALS}"
}
}
}
}🔐 보안 강화 MCP 설정
프로덕션 환경에서의 보안 고려사항:
{
"mcpServers": {
"secure-database": {
"command": "uvx",
"args": ["mcp-server-postgres"],
"env": {
"DATABASE_URL": "${ENCRYPTED_DB_URL}",
"SSL_MODE": "require",
"CONNECTION_TIMEOUT": "30",
"MAX_CONNECTIONS": "10"
},
"security": {
"allowedOperations": ["read", "insert", "update"],
"deniedTables": ["users_sensitive", "payment_details"],
"auditLog": true,
"rateLimiting": {
"requestsPerMinute": 100,
"burstLimit": 20
}
}
}
}
}📊 MCP 성능 모니터링
실시간 성능 추적 및 최적화:
# mcp-performance-monitor.py
import asyncio
import time
from mcp.server import Server
from prometheus_client import Counter, Histogram, start_http_server
# 메트릭 정의
REQUEST_COUNT = Counter('mcp_requests_total', 'Total MCP requests', ['tool_name', 'status'])
REQUEST_DURATION = Histogram('mcp_request_duration_seconds', 'MCP request duration', ['tool_name'])
app = Server("performance-monitored-server")
@app.call_tool()
async def call_tool(name: str, arguments: dict):
start_time = time.time()
try:
# 실제 도구 실행
result = await execute_tool(name, arguments)
# 성공 메트릭 기록
REQUEST_COUNT.labels(tool_name=name, status='success').inc()
REQUEST_DURATION.labels(tool_name=name).observe(time.time() - start_time)
return result
except Exception as e:
# 실패 메트릭 기록
REQUEST_COUNT.labels(tool_name=name, status='error').inc()
REQUEST_DURATION.labels(tool_name=name).observe(time.time() - start_time)
raise e
# Prometheus 메트릭 서버 시작
start_http_server(8000)🔄 자동 복구 및 헬스체크
MCP 서버의 안정성을 위한 자동 복구 메커니즘:
{
"mcpServers": {
"resilient-service": {
"command": "uvx",
"args": ["mcp-server-api"],
"healthCheck": {
"enabled": true,
"interval": 30,
"timeout": 10,
"retries": 3,
"endpoint": "/health"
},
"autoRestart": {
"enabled": true,
"maxRestarts": 5,
"restartDelay": 5,
"backoffMultiplier": 2
},
"circuitBreaker": {
"enabled": true,
"failureThreshold": 5,
"recoveryTimeout": 60,
"halfOpenMaxCalls": 3
}
}
}
}MCP Registry Governance (v0.11, 엔터프라이즈)
v0.11부터 엔터프라이즈 관리자가 조직에서 허용하는 MCP 서버를 JSON 레지스트리로 중앙 관리할 수 있습니다.
// mcp-registry.json (HTTPS 호스팅)
{
"allowedServers": [
{ "name": "github", "version": ">=1.0.0", "approved": true },
{ "name": "postgres", "version": ">=0.5.0", "approved": true }
],
"blockedServers": ["untrusted-server"],
"requireApproval": true
}- IAM Identity Center를 통한 인증
- HTTPS 호스팅으로 레지스트리 파일 관리
- 개별 개발자는 레지스트리에 등록된 서버만 사용 가능
Remote MCP 서버 (v0.10+)
로컬 프로세스가 아닌 원격 서버에 직접 연결할 수 있습니다.
{
"mcpServers": {
"remote-api": {
"url": "https://mcp.company.com/api",
"headers": {
"Authorization": "Bearer ${MCP_TOKEN}"
}
}
}
}