main.py•2.9 kB
from fastmcp.server import FastMCP
from fastmcp.server.auth import BearerAuthProvider
from fastmcp.server.auth.providers.bearer import RSAKeyPair
import slack_client
import slack_endpoints
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Read RSA key pair from environment variables or generate a new one if not available
import base64
private_key_b64 = os.getenv("RSA_PRIVATE_KEY")
public_key_b64 = os.getenv("RSA_PUBLIC_KEY")
if private_key_b64 and public_key_b64:
from pydantic import SecretStr
# Decode from base64 to PEM string
private_key = base64.b64decode(private_key_b64.encode()).decode("utf-8")
public_key = base64.b64decode(public_key_b64.encode()).decode("utf-8")
key_pair = RSAKeyPair(private_key=SecretStr(private_key), public_key=public_key)
print("Using RSA keys from environment variables (base64 decoded)")
else:
# Generate new keys for development or if keys are not provided
print("WARNING: RSA keys not found in environment variables, generating temporary keys")
key_pair = RSAKeyPair.generate()
# Print keys to be added to .env file (only in development)
if os.getenv("ENV", "development") == "development":
print("\033[93m")
print("Add these keys to your .env file to avoid generating new keys each time:")
print(f"RSA_PRIVATE_KEY='{key_pair.private_key.get_secret_value()}'")
print(f"RSA_PUBLIC_KEY='{key_pair.public_key}'")
print("\033[0m")
# Configure bearer token authentication with the public key
auth_provider = BearerAuthProvider(
public_key=key_pair.public_key # Use the public key for JWT validation
)
# Create FastMCP application with authentication
mcp = FastMCP(name="slack", auth=auth_provider)
# Initialize Slack client
slack_client_instance = slack_client.SlackClient(token=os.getenv("SLACK_BOT_TOKEN"))
# Setup endpoints with the app and client
slack_endpoints.setup_endpoints(mcp, slack_client_instance)
# Generate a JWT token for clients to use
def generate_client_token():
# Create a token with the API_TOKEN as subject for easy identification
return key_pair.create_token(
subject="slack-mcp-server",
issuer="slack-mcp-server",
audience="slack-mcp-client",
scopes=["read"], # Only read permissions
expires_in_seconds=3600 * 24 # 24 hours
)
# Generate a sample token for client use
client_token = generate_client_token()
print(f"Server starting on port with JWT bearer token authentication enabled")
print("\033[93m")
print("Use the following token for authentication:")
print(f"Bearer {client_token}")
print("\033[0m")
if __name__ == "__main__":
# Get port from environment variable or use default 8000
port = int(os.getenv("PORT", "8000"))
# Run the server with SSE transport on the specified port
mcp.run(transport="sse", port=port)