feat: add server_info tool for diagnostics and implement interactive CLI onboarding wizard for easier authentication
CI/CD Pipeline / Lint & Check (push) Successful in 10s
Deploy Website to S3 / deploy (push) Successful in 6s
CI/CD Pipeline / Publish to PyPI (push) Has been skipped
CI/CD Pipeline / Build & Push Docker Image (push) Successful in 1m19s

This commit is contained in:
2026-05-14 21:12:48 +02:00
parent 7c8061eeea
commit 6db9e87f96
7 changed files with 355 additions and 108 deletions
+191 -89
View File
@@ -27,6 +27,101 @@ REDIRECT_URI = "http://localhost:8765/callback"
SCOPES = "profile:read_all,activity:read_all,activity:read,profile:write"
class SetupHandler(BaseHTTPRequestHandler):
setup_done = False
client_id = ""
client_secret = ""
def do_GET(self):
if self.path == "/setup" or self.path == "/":
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(self._get_setup_page().encode("utf-8"))
elif self.path.startswith("/save"):
parsed = urlparse(self.path)
params = parse_qs(parsed.query)
if "id" in params and "secret" in params:
SetupHandler.client_id = params["id"][0].strip()
SetupHandler.client_secret = params["secret"][0].strip()
SetupHandler.setup_done = True
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(
"""
<html>
<head><meta http-equiv="refresh" content="2;url=/callback-wait"></head>
<body style="background:#0A0A0A;color:white;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;">
<div style="text-align:center;">
<h2 style="color:#fc4c02;">Settings Saved!</h2>
<p>Redirecting to Strava Authorization...</p>
</div>
</body>
</html>
""".encode("utf-8")
)
else:
self.send_response(400)
self.end_headers()
self.wfile.write(b"Missing parameters")
else:
self.send_response(404)
self.end_headers()
def _get_setup_page(self):
return """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Strava MCP Setup</title>
<style>
:root { --primary: #FC4C02; --bg: #0A0A0A; --card: #161616; --text: #FFFFFF; --text-dim: #A0A0A0; }
body { font-family: -apple-system, system-ui, sans-serif; background: var(--bg); color: var(--text); margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
.container { max-width: 500px; width: 90%; background: var(--card); padding: 40px; border-radius: 24px; box-shadow: 0 20px 40px rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.1); }
h1 { color: var(--primary); margin-top: 0; font-size: 28px; }
.guide { background: rgba(252, 76, 2, 0.1); padding: 20px; border-radius: 12px; margin-bottom: 30px; font-size: 14px; line-height: 1.5; border-left: 4px solid var(--primary); }
.guide ol { margin: 10px 0 0 20px; padding: 0; }
.guide li { margin-bottom: 8px; }
label { display: block; margin-bottom: 8px; font-weight: 600; font-size: 14px; color: var(--text-dim); }
input { width: 100%; padding: 12px 16px; background: #222; border: 1px solid #333; border-radius: 8px; color: white; margin-bottom: 20px; box-sizing: border-box; font-family: monospace; }
input:focus { border-color: var(--primary); outline: none; }
button { width: 100%; padding: 14px; background: var(--primary); color: white; border: none; border-radius: 8px; font-weight: 700; cursor: pointer; transition: transform 0.2s; font-size: 16px; }
button:hover { transform: translateY(-2px); filter: brightness(1.1); }
code { background: #000; padding: 2px 6px; border-radius: 4px; font-family: monospace; color: var(--primary); }
</style>
</head>
<body>
<div class="container">
<h1>Strava MCP Setup</h1>
<div class="guide">
<strong>How to get your credentials:</strong>
<ol>
<li>Go to <a href="https://www.strava.com/settings/api" target="_blank" style="color:var(--primary);">Strava API Settings</a>.</li>
<li>Create an app (any name/category).</li>
<li>Set <b>"Authorization Callback Domain"</b> to <code>localhost</code>.</li>
<li>Copy your <b>Client ID</b> and <b>Client Secret</b> below.</li>
</ol>
</div>
<form action="/save" method="get">
<label>Client ID</label>
<input type="text" name="id" placeholder="e.g. 123456" required>
<label>Client Secret</label>
<input type="password" name="secret" placeholder="Your Strava Secret" required>
<button type="submit">Save & Authenticate</button>
</form>
</div>
</body>
</html>
"""
def log_message(self, format, *args):
pass
class CallbackHandler(BaseHTTPRequestHandler):
client_id: str = ""
client_secret: str = ""
@@ -51,65 +146,45 @@ class CallbackHandler(BaseHTTPRequestHandler):
},
)
response.raise_for_status()
self.tokens = response.json()
CallbackHandler.tokens = response.json()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
refresh_token = self.tokens.get("refresh_token")
refresh_token = CallbackHandler.tokens.get("refresh_token")
self.wfile.write(
f"""
<html>
<head>
<style>
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 40px auto; padding: 20px; text-align: left; }}
.card {{ background: #f4f7f6; border-radius: 8px; padding: 20px; border-left: 5px solid #fc4c02; margin-top: 20px; }}
pre {{ background: #222; color: #fff; padding: 15px; border-radius: 5px; overflow-x: auto; font-family: "SF Mono", Monaco, Consolas, monospace; font-size: 13px; }}
.success-header {{ text-align: center; margin-bottom: 40px; }}
.success-icon {{ color: #2ecc71; font-size: 48px; display: block; margin-bottom: 10px; }}
h2, h3 {{ color: #fc4c02; }}
.env-label {{ font-weight: bold; color: #666; font-size: 12px; text-transform: uppercase; margin-bottom: 5px; display: block; }}
.copy-hint {{ font-size: 12px; color: #666; font-style: italic; }}
code {{ background: #eee; padding: 2px 4px; border-radius: 4px; }}
body {{ background: #0A0A0A; color: white; font-family: -apple-system, sans-serif; max-width: 600px; margin: 60px auto; padding: 20px; text-align: center; }}
.card {{ background: #161616; border-radius: 16px; padding: 30px; border: 1px solid rgba(255,255,255,0.1); text-align: left; margin-top: 30px; }}
h2 {{ color: #fc4c02; }}
pre {{ background: #000; color: #fc4c02; padding: 20px; border-radius: 8px; overflow-x: auto; font-family: monospace; font-size: 14px; border: 1px solid #333; }}
.success-icon {{ font-size: 64px; margin-bottom: 20px; display: block; }}
</style>
</head>
<body>
<div class="success-header">
<span class="success-icon">&#x2705;</span>
<h2>Authorization successful!</h2>
<p>You have successfully authenticated with Strava. You can now close this window.</p>
</div>
<span class="success-icon">✅</span>
<h2>Setup Complete!</h2>
<p>Your Strava account is now connected to the MCP server.</p>
<h3>1. Local Setup (.env)</h3>
<p>Copy the following block into your <code>.env</code> file in the project root:</p>
<div class="card">
<span class="env-label">Your .env content:</span>
<p style="margin-top:0; color: #A0A0A0; font-size: 14px; font-weight: bold;">UPDATED .ENV CONTENT:</p>
<pre>STRAVA_CLIENT_ID={self.client_id}
STRAVA_CLIENT_SECRET={self.client_secret}
STRAVA_REFRESH_TOKEN={refresh_token}</pre>
<p style="font-size: 13px; color: #666; margin-bottom: 0;">This information has been automatically saved to your .env file.</p>
</div>
<h3>2. Kubernetes Setup (Secret)</h3>
<p>If you are deploying this server to Kubernetes, run the following command to create the required Secret:</p>
<div class="card">
<span class="env-label">Kubectl Command:</span>
<pre>kubectl create secret generic strava-mcp-server-secret \\
--from-literal=STRAVA_CLIENT_ID={self.client_id} \\
--from-literal=STRAVA_CLIENT_SECRET={self.client_secret} \\
--from-literal=STRAVA_REFRESH_TOKEN={refresh_token}</pre>
</div>
<p style="margin-top: 40px; font-size: 14px; color: #666; text-align: center;">
&mdash; Strava MCP Server Authorization Helper &mdash;
</p>
<p style="margin-top: 40px; color: #444;">You can now close this window and restart the server.</p>
</body>
</html>
""".encode("utf-8")
)
except Exception as e:
self.error = str(e)
CallbackHandler.error = str(e)
self.send_response(500)
self.end_headers()
self.wfile.write(f"Error exchanging token: {e}".encode())
@@ -123,11 +198,70 @@ STRAVA_REFRESH_TOKEN={refresh_token}</pre>
pass # Suppress server logs
def main():
if not CLIENT_ID or not CLIENT_SECRET:
print("❌ Missing STRAVA_CLIENT_ID or STRAVA_CLIENT_SECRET in .env")
return
def save_to_env(client_id, client_secret, refresh_token=None):
env_path = ".env"
lines = []
if os.path.exists(env_path):
with open(env_path, "r") as f:
lines = f.readlines()
keys_to_set = {
"STRAVA_CLIENT_ID": client_id,
"STRAVA_CLIENT_SECRET": client_secret,
}
if refresh_token:
keys_to_set["STRAVA_REFRESH_TOKEN"] = refresh_token
new_lines = []
seen_keys = set()
for line in lines:
matched = False
for key, value in keys_to_set.items():
if line.startswith(f"{key}="):
new_lines.append(f"{key}={value}\n")
seen_keys.add(key)
matched = True
break
if not matched:
new_lines.append(line)
for key, value in keys_to_set.items():
if key not in seen_keys:
new_lines.append(f"{key}={value}\n")
with open(env_path, "w") as f:
f.writelines(new_lines)
# Debug output
saved_keys = ", ".join(keys_to_set.keys())
print(f"📝 Updated .env with: {saved_keys}")
def main():
global CLIENT_ID, CLIENT_SECRET
# 1. Start Setup Wizard if credentials missing
if not CLIENT_ID or not CLIENT_SECRET:
print(
"️ Missing credentials. Starting setup wizard at http://localhost:8765 ..."
)
print("Please enter your Client ID and Secret in the browser window.")
webbrowser.open("http://localhost:8765/setup")
HTTPServer.allow_reuse_address = True
setup_server = HTTPServer(("localhost", 8765), SetupHandler)
try:
while not SetupHandler.setup_done:
setup_server.handle_request()
finally:
setup_server.server_close()
CLIENT_ID = SetupHandler.client_id
CLIENT_SECRET = SetupHandler.client_secret
save_to_env(CLIENT_ID, CLIENT_SECRET)
# 2. Proceed to Strava OAuth
auth_url = (
f"https://www.strava.com/oauth/authorize"
f"?client_id={CLIENT_ID}"
@@ -137,69 +271,37 @@ def main():
f"&scope={SCOPES}"
)
# Configure handler
CallbackHandler.client_id = CLIENT_ID
CallbackHandler.client_secret = CLIENT_SECRET
CallbackHandler.tokens = {}
CallbackHandler.error = None
print("=" * 60)
print("\n" + "=" * 60)
print(" Strava OAuth2 Authorization")
print("=" * 60)
print(f"\nRequesting scopes: {SCOPES}\n")
print("Opening Strava in your browser...")
print("If the browser doesn't open, visit this URL manually:\n")
print(f" {auth_url}\n")
print("\nOpening Strava in your browser for final authentication...")
webbrowser.open(auth_url)
print("Waiting for callback on http://localhost:8765 ...")
HTTPServer.allow_reuse_address = True
server = HTTPServer(("localhost", 8765), CallbackHandler)
server.handle_request() # Handle exactly one request (the callback)
if CallbackHandler.error:
print(f"❌ Token exchange failed: {CallbackHandler.error}")
return
if not CallbackHandler.tokens:
print("❌ No tokens received.")
return
data = CallbackHandler.tokens
refresh_token = data["refresh_token"]
athlete = data.get("athlete", {})
print("\n" + "=" * 60)
print(" ✅ Authorization successful!")
print("=" * 60)
print(f"\nAthlete: {athlete.get('firstname')} {athlete.get('lastname')}")
print(f"Scopes granted: {data.get('scope', 'unknown')}\n")
print("Add the following to your .env file:")
print("-" * 40)
print(f"STRAVA_CLIENT_ID={CLIENT_ID}")
print(f"STRAVA_CLIENT_SECRET={CLIENT_SECRET}")
print(f"STRAVA_REFRESH_TOKEN={refresh_token}")
print("-" * 40)
# Optional: Automatically update .env if it exists
try:
env_path = ".env"
if os.path.exists(env_path):
with open(env_path, "r") as f:
lines = f.readlines()
with open(env_path, "w") as f:
found = False
for line in lines:
if line.startswith("STRAVA_REFRESH_TOKEN="):
f.write(f"STRAVA_REFRESH_TOKEN={refresh_token}\n")
found = True
else:
f.write(line)
if not found:
f.write(f"\nSTRAVA_REFRESH_TOKEN={refresh_token}\n")
print("Successfully updated your .env file!")
except Exception as e:
print(f"Could not automatically update .env: {e}")
print("Waiting for Strava callback...")
while not CallbackHandler.tokens and not CallbackHandler.error:
server.handle_request()
finally:
server.server_close()
if not CallbackHandler.error and CallbackHandler.tokens:
data = CallbackHandler.tokens
refresh_token = data.get("refresh_token")
if refresh_token:
save_to_env(CLIENT_ID, CLIENT_SECRET, refresh_token)
print("\n✅ Setup successful! All tokens saved to .env")
else:
print("\n❌ Error: No refresh token in response.")
elif CallbackHandler.error:
print(f"\n❌ Error: {CallbackHandler.error}")
if __name__ == "__main__":