|Message| WS WS --> API API --> GCP API --> OCI API --> DB GCP -->|Response| SSE OCI -->|Response| SSE DB -->|Response| SSE SSE -->|Broadcast| User 2. Simple Architecture Without Redis Why Remove Redis? Item Redis Usage In-Memory Usage Thread Lock Redis SET NX Python dict Event Distribution Redis Streams Direct SSE State Storage Redis Cache Memory Cache Conclusion: In-Memory is sufficient for single-instance environment.\n">[Discord MCP] Gateway Architecture Design|Message| WS WS --> API API --> GCP API --> OCI API --> DB GCP -->|Response| SSE OCI -->|Response| SSE DB -->|Response| SSE SSE -->|Broadcast| User 2. Simple Architecture Without Redis Why Remove Redis? Item Redis Usage In-Memory Usage Thread Lock Redis SET NX Python dict Event Distribution Redis Streams Direct SSE State Storage Redis Cache Memory Cache Conclusion: In-Memory is sufficient for single-instance environment.\n"> |Message| WS WS --> API API --> GCP API --> OCI API --> DB GCP -->|Response| SSE OCI -->|Response| SSE DB -->|Response| SSE SSE -->|Broadcast| User 2. Simple Architecture Without Redis Why Remove Redis? Item Redis Usage In-Memory Usage Thread Lock Redis SET NX Python dict Event Distribution Redis Streams Direct SSE State Storage Redis Cache Memory Cache Conclusion: In-Memory is sufficient for single-instance environment.\n">

[Discord MCP] Gateway Architecture Design

The Claude Code team designed a Discord Gateway Service for user communication via Discord. This article summarizes the key architecture decisions and user_comm Agent design.


1. Overall Architecture

Components

LayerComponentRole
DiscordBot, Channel, ThreadUser interface
GatewayWebSocket, REST API, SSEMessage routing
MCPgcp-mcp, oci-mcp, db-mcpTool execution
user_commDiscord AgentUser communication

Message Flow


2. user_comm Agent (User Communication Handler)

Role and Responsibilities

The user_comm Agent is a member of the Claude Code team, communicating with users through Discord channels and collaborating with other agents.

FunctionDescription
Input ReceptionReceive Discord messages and route to appropriate agent
Opinion RequestQuery user opinions at other agents’ requests
Notification/ReportSend system status, warnings, reports
Team CommunicationExchange messages with other agents

Internal Structure

Message Types

class MessageType(Enum):
    TASK_REQUEST = "task_request"       # Task request
    NOTIFICATION = "notification"        # Notification
    OPINION_REQUEST = "opinion_request"  # Opinion request
    OPINION_RESPONSE = "opinion_response" # Opinion response
    STATUS_REPORT = "status_report"      # Status report
    ERROR = "error"                      # Error

Key Function Flows

Input Reception (Discord -> Agent)

User: "@gcp-monitor check server status"
  -> DiscordBot.on_message
  -> UserCommAgent._parse_command (target: gcp-monitor)
  -> TeamCommunicator.send_to_agent
  -> Discord: "Request forwarded to gcp-monitor."

Opinion Request (Agent -> Discord)

gcp-monitor: "Clean up disk?" -> user_comm
  -> DiscordBot.ask_opinion (wait for button or reply)
  -> User response
  -> TeamCommunicator.send_to_agent (forward response)

Notification/Report (Agent -> Discord)

oci-monitor: "Disk 92% warning" -> user_comm
  -> DiscordBot.send_message (Embed format)

3. Lightweight Architecture Without Redis

Why Remove Redis?

ItemWith RedisWith In-Memory
Thread LockRedis SET NXPython dict
Event DistributionRedis StreamsDirect SSE
State StorageRedis CacheMemory cache

Conclusion: In-memory is sufficient for single-instance environments

Gateway Structure

Component Details

ModuleRoleFeatures
Discord BotWebSocket connectionAuto-reconnect
Thread LockConcurrency control5min timeout
Message CacheMessage storageMax 1000 items
SSE ManagerReal-time deliveryBroadcast to all MCPs

4. MCP Selection: 4-Stage Hybrid

Selection Priority

RankMethodExampleDescription
1Slash Command/gcp statusMost explicit
2@Mention@gcp-monitor statusNatural conversation
3Keyword Detectiongcp server statusAuto keyword recognition
4Channel Assignment#gcp-monitoringChannel default MCP

Fallback Order

Slash Command List

CommandMCPDescription
/gcp status [server]gcp-mcpGCP server status
/gcp listgcp-mcpGCP instance list
/oci status [server]oci-mcpOCI server status
/oci listoci-mcpOCI instance list
/db query <sql>db-mcpExecute DB query
/db listdb-mcpDB list
/alert checkalert-mcpCheck alerts

5. Thread Lock Rules

Lock Behavior

Lock API

MethodEndpointDescription
POST/api/threads/{id}/acquireAcquire lock
POST/api/threads/{id}/releaseRelease lock
GET/api/threads/{id}/lockCheck lock status

Request/Response Example

Lock Acquire Request

POST /api/threads/123456/acquire
{
  "agent_name": "gcp-mcp",
  "timeout": 300
}

Lock Acquire Response

{
  "acquired": true,
  "thread_id": "123456",
  "agent": "gcp-mcp"
}

6. MCP Tools (8)

Tool List

ToolDescriptionKey Parameters
discord_send_messageSend messagechannel_id, content
discord_get_messagesGet messageschannel_id, limit
discord_wait_for_messageWait for messagechannel_id, timeout
discord_create_threadCreate threadchannel_id, message_id
discord_list_threadsList threadschannel_id
discord_archive_threadArchive threadthread_id
discord_acquire_threadAcquire lockthread_id, agent_name
discord_release_threadRelease lockthread_id, agent_name

Tool Relationships

Usage Examples

# Send message
discord_send_message(
    channel_id="123456789",
    content="Server status: OK"
)

# Create thread
discord_create_thread(
    channel_id="123456789",
    message_id="987654321",
    name="Status Check"
)

# Acquire lock
discord_acquire_thread(
    thread_id="111222333",
    agent_name="gcp-mcp",
    timeout=300
)

7. File Structure

Directory Description

PathDescription
gateway/Gateway Service (FastAPI)
user_comm/User Communication Agent
discord_mcp/MCP Server (8 tools)
mcp_shared/Shared MCP tools
docs/Documentation

8. How to Run

Local Execution

# Start Gateway Service
uvicorn gateway.main:app --host 0.0.0.0 --port 8081

# Start user_comm Agent (standalone mode)
python main.py --standalone

# Start user_comm Agent (team mode)
python main.py --team server-monitor

# Health check
curl http://localhost:8081/health

# Response
{"status": "healthy", "discord_connected": true}

Claude Code MCP Configuration

// ~/.claude/settings.json
{
  "mcpServers": {
    "discord-gateway": {
      "command": "python3",
      "args": ["/path/to/discord_mcp/server.py"],
      "env": {
        "GATEWAY_URL": "http://localhost:8081"
      }
    }
  }
}

9. Roadmap

Phase 1: Complete

  • FastAPI Gateway Service
  • Discord WebSocket connection
  • Thread Lock (In-Memory)
  • SSE broadcast
  • MCP Server (8 tools)

Phase 2: In Progress

  • user_comm Agent implementation
  • Slash command implementation
  • Channel default MCP settings
  • Keyword auto-detection
  • Routing configuration file

Phase 3: Optional

  • API authentication (API Key)
  • Rate Limiting
  • Message persistence (SQLite)

Conclusion

We chose a strategy of starting with a lightweight architecture and expanding when needed.

ItemCurrentFuture
State StorageIn-MemorySQLite (if needed)
Distributed LockNot usedRedis (multi-instance)
AuthenticationNoneAPI Key (if needed)
User CommunicationGateway directuser_comm Agent

The current structure is sufficient for single instances, and we plan to expand incrementally as traffic grows. The user_comm Agent systematizes user communication and improves collaboration with other agents on the team.


Korean Version: 한국어 버전

Built with Hugo
Theme Stack designed by Jimmy