Skip to main content
Glama
Manojbonthu

notifications-mcp

by Manojbonthu

Streamable HTTP + SSE MCP 서버

프로덕션 준비 완료 Model Context Protocol (MCP) 서버 – Streamable HTTP + SSE, Bearer 인증, 엄격한 세션-신원 바인딩, 프롬프트 인젝션 가드레일, 수신자 허용 목록, 속도 제한 지원


👥 업무 분담 및 책임

기여자

영역 및 산출물

@Vinod

서버 스캐폴딩, Streamable HTTP(POST + GET SSE) 전송, Mcp-Session-Id 세션 관리, Last-Event-ID 재개 가능성, 호스팅 및 터널 설정(scripts/run_tunnel.py), Bearer 토큰 인증, Origin 검사, JSON-RPC 오류 처리 계층

@Vishal

도구 핸들러(get_current_datetime, send_email), 입력 검증 및 Pydantic 스키마, 프롬프트 인젝션 탐지 및 감사 로깅, 수신자 허용 목록 및 슬라이딩 윈도우 속도 제한, 6가지 라이브 데모 검증 테스트 케이스(scripts/test_demo_cases.py)


Related MCP server: Gmail MCP Server

🌟 핵심 기능 및 표준

  1. 공식 MCP 사양 표준: Streamable HTTP(POST /mcp 및 GET /mcp)를 통한 JSON-RPC 2.0 전송

  2. 세션 보안 및 재개 가능성:

    • Mcp-Session-Id: 인증된 호출자 신원에 엄격히 연결된 UUID 세션

    • Last-Event-ID: 재연결 시 이벤트 재생을 위한 SSE 이벤트 링 버퍼

  3. 보안 가드레일:

    • 인증 강제: 모든 /mcp 요청은 유효한 Bearer 토큰 또는 API 키 필요

    • 세션 하이재킹 방어: 세션 ID는 서로 다른 신원 간에 공유 불가

    • 프롬프트 인젝션 방어: 이메일 필드를 스캔하는 정규식 및 휴리스틱 분석기, 보안 감사 로깅 포함

    • 수신자 허용 목록 및 속도 제한: 승인되지 않은 이메일 유출 및 대량 전송 방지

    • 깔끔한 오류 정제: 일반적인 안전한 JSON-RPC 오류(스택 추적 누출 없음)

  4. 모의 도구:

    • get_current_datetime(timezone?): IANA 시간대 검증을 포함한 시스템 날짜/시간

    • send_email(to, subject, body): 서버 SMTP, 안전한 시뮬레이션 데모 모드 포함


📁 저장소 구조

Custom_MCP_Server/
├── config.yaml                    # Server, auth tokens, allowlists, rate limits, and SMTP config
├── pyproject.toml                 # Package definition & dependencies
├── requirements.txt               # Dependencies
├── README.md                      # Documentation & demo checklist
├── scripts/
│   ├── run_tunnel.py              # Hosting / tunnel launcher (Cloudflared, Ngrok, Localtunnel, Local)
│   └── test_demo_cases.py         # Automated verification suite for the 6 Live Demo test cases
├── src/
│   ├── __init__.py
│   ├── config.py                  # Typed configuration models
│   ├── server.py                  # Starlette Streamable HTTP + SSE application
│   ├── registry.py                # MCP tools registration & dispatcher
│   ├── auth/
│   │   ├── __init__.py
│   │   ├── middleware.py          # Auth, Origin, and session validation middleware
│   │   └── session_manager.py     # UUID session manager with Last-Event-ID buffer
│   ├── security/
│   │   ├── __init__.py
│   │   ├── injection_detector.py  # Prompt injection detector & audit logger
│   │   ├── allowlist.py           # Email recipient & domain allowlist validator
│   │   └── rate_limiter.py        # Sliding-window rate limiter per caller
│   ├── common/
│   │   ├── __init__.py
│   │   ├── errors.py              # JSON-RPC 2.0 error codes and builders
│   │   └── logging.py             # Structured JSON logger with security tags
│   └── tools/
│       ├── __init__.py
│       ├── datetime_tool.py       # get_current_datetime tool handler
│       └── email_tool.py          # send_email tool handler with SMTP/demo mode
└── tests/
    ├── __init__.py
    ├── conftest.py
    ├── test_datetime_tool.py      # Datetime unit tests
    ├── test_email_tool.py         # Email & security guardrail tests
    ├── test_security_auth.py      # Auth & session isolation tests
    └── test_streamable_http.py    # Streamable HTTP / SSE transport tests

🚀 빠른 시작 가이드

1. 사전 요구 사항

  • Python 3.10+

  • Node.js (선택 사항, MCP Inspector용)

2. 종속성 설치

pip install -r requirements.txt

3. 서버 시작

python -m src.server

다음과 같은 출력이 표시됩니다:

{"timestamp": "...", "level": "INFO", "message": "Starting Streamable MCP Server | host=0.0.0.0 | port=8100"}
{"timestamp": "...", "level": "INFO", "message": "MCP POST/GET endpoint  → http://localhost:8100/mcp"}
{"timestamp": "...", "level": "INFO", "message": "Health check probe     → http://localhost:8100/health"}

⚙️ 구성 (config.yaml)

server:
  host: "0.0.0.0"
  port: 8100
  allowed_origins:
    - "http://localhost:8100"
    - "*"

auth:
  enabled: true
  tokens:
    "agent-token-alpha": "agent_alpha"
    "agent-token-beta": "agent_beta"
    "vishal-test-token": "vishal_engineer"
    "vinod-test-token": "vinod_engineer"

security:
  email:
    allowlist:
      - "ops@company.com"
      - "manager@company.com"
      - "vishal@company.com"
      - "vinod@company.com"
      - "*@trusteddomain.com"
    rate_limit:
      max_calls: 10
      window_seconds: 60
    prompt_injection_guard:
      enabled: true

smtp:
  mode: "simulation"  # "simulation" (safe for testing/demos) or "smtp" (live server)
  host: "smtp.example.com"
  port: 587
  sender_address: "notifications@company.com"

🛠️ 도구 스키마

도구 1: get_current_datetime

  • 설명: 선택적 IANA 시간대 변환을 포함하여 현재 호스트 시스템 날짜 및 시간을 반환합니다.

  • 매개변수:

    {
      "type": "object",
      "properties": {
        "timezone": {
          "type": "string",
          "description": "Optional IANA timezone name (e.g. 'UTC', 'America/New_York', 'Asia/Kolkata')."
        }
      },
      "required": []
    }

도구 2: send_email

  • 설명: 엄격한 보안 가드레일과 함께 서버 SMTP를 통해 이메일 알림을 전송합니다.

  • 매개변수:

    {
      "type": "object",
      "properties": {
        "to": {
          "type": "string",
          "description": "Recipient email address. Must be in the authorized allowlist."
        },
        "subject": {
          "type": "string",
          "description": "Email subject line."
        },
        "body": {
          "type": "string",
          "description": "Email body content."
        }
      },
      "required": ["to", "subject", "body"]
    }

🔌 MCP Inspector 및 cURL로 연결하기

MCP Inspector를 통해 연결:

npx @modelcontextprotocol/inspector

URL: http://localhost:8100/mcp에 연결하고 사용자 정의 헤더: Authorization: Bearer vishal-test-token을 추가합니다.

샘플 cURL 호출:

1. get_current_datetime 호출:

curl -X POST http://localhost:8100/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer vishal-test-token" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "get_current_datetime",
      "arguments": {"timezone": "Asia/Kolkata"}
    }
  }'

2. send_email 호출:

curl -X POST http://localhost:8100/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer vishal-test-token" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "send_email",
      "arguments": {
        "to": "ops@company.com",
        "subject": "System Status",
        "body": "All services operating normally."
      }
    }
  }'

🌐 호스팅 및 터널 설정

MCP 서버를 공개 URL/클라우드 데모에 노출하려면:

# Option 1: Direct Local / VM binding
python scripts/run_tunnel.py --mode local --port 8100

# Option 2: Cloudflare Tunnel (Free, no port-forwarding needed)
python scripts/run_tunnel.py --mode cloudflared --port 8100

# Option 3: Ngrok
python scripts/run_tunnel.py --mode ngrok --port 8100

# Option 4: Localtunnel
python scripts/run_tunnel.py --mode localtunnel --port 8100

🧪 라이브 데모 체크리스트 (6개 테스트 케이스)

자동화된 테스트 실행기를 실행하여 한 번의 명령으로 6개의 데모 케이스를 모두 확인하세요:

python scripts/test_demo_cases.py

또는 pytest로 실행:

pytest -v

확인된 테스트 케이스:

  • 케이스 1: 인증된 호출자가 각 도구 호출 성공 (get_current_datetime 및 send_email 모두)

  • 케이스 2: 인증되지 않은 호출자에게 일반 오류 반환 (HTTP 401, 오류 코드 -32001)

  • 케이스 3: 잘못된 입력에 대해 깔끔한 검증 오류 반환 (잘못된 시간대 또는 스키마 필드 누락)

  • 케이스 4: 이메일 내 프롬프트 인젝션 시도 차단 및 로깅 (예: 시스템 프롬프트 재정의)

  • 케이스 5: 허용 목록에 없는 이메일로 전송 거부 (외부/승인되지 않은 주소 차단)

  • 케이스 6: 서로 다른 신원 간 세션 ID 재사용 거부 (HTTP 403, 오류 코드 -32005)

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    An MCP server that provides AI applications with a toolset for an Artificial Virtual Assistant (AVA) integrated with the Gmail API. It enables users to automate email management and personal tasks through secure Google OAuth authentication.
    1
    Apache 2.0
  • A
    license
    Not graded
    quality
    D
    maintenance
    A Node.js server that connects MCP to Gmail, enabling LLMs to send, read, and manage emails securely using the Gmail API.
    184 npm
    2
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Production-ready MCP server for Gmail, enabling AI agents to search, read, send, draft, and manage emails, labels, and attachments via the Google Gmail API.
    -