#!/usr/bin/env python3
"""
Example usage script for Clockify MCP Server
Demonstrates direct API usage without MCP
"""
import asyncio
import os
from datetime import datetime, timedelta
from clockify_mcp.client import ClockifyClient
async def main():
"""Example usage of Clockify client"""
# Get API key from environment
api_key = os.getenv("CLOCKIFY_API_KEY")
if not api_key:
print("Error: CLOCKIFY_API_KEY environment variable not set")
print("Get your API key from: https://clockify.me/user/settings")
return
# Create client
client = ClockifyClient(api_key)
try:
print("=" * 60)
print("Clockify API Client Example")
print("=" * 60)
# Get current user
print("\n1. Getting current user...")
user = await client.get_current_user()
print(f" Logged in as: {user['name']} ({user['email']})")
# Get default workspace
print("\n2. Getting default workspace...")
workspace = await client.get_default_workspace()
workspace_id = workspace['id']
print(f" Workspace: {workspace['name']}")
# Get all users
print("\n3. Getting workspace users...")
users = await client.get_workspace_users(workspace_id, status="ACTIVE")
print(f" Found {len(users)} active users:")
for u in users[:5]:
print(f" - {u['name']}")
# Get all projects
print("\n4. Getting projects...")
projects = await client.get_projects(workspace_id, archived=False)
print(f" Found {len(projects)} active projects:")
for p in projects[:5]:
print(f" - {p['name']}")
# Get time entries for current user (last 7 days)
print("\n5. Getting recent time entries...")
end_date = datetime.utcnow()
start_date = end_date - timedelta(days=7)
entries = await client.get_time_entries(
workspace_id=workspace_id,
user_id=user['id'],
start=start_date,
end=end_date
)
print(f" Found {len(entries)} time entries in the last 7 days")
total_hours = sum(
client.parse_duration_to_hours(
e.get('timeInterval', {}).get('duration', 'PT0S')
)
for e in entries
)
print(f" Total hours: {total_hours:.2f}")
# Show recent entries
if entries:
print("\n Recent entries:")
for entry in entries[:3]:
desc = entry.get('description', 'No description')
project = entry.get('project', {}).get('name', 'No project')
duration = client.parse_duration_to_hours(
entry.get('timeInterval', {}).get('duration', 'PT0S')
)
start = entry.get('timeInterval', {}).get('start', '')[:10]
print(f" {start} | {duration:.2f}h | {project} | {desc[:40]}")
# Check for running timer
print("\n6. Checking for running timer...")
running = await client.get_running_timer(workspace_id, user['id'])
if running:
desc = running.get('description', 'No description')
project = running.get('project', {}).get('name', 'No project')
start = running.get('timeInterval', {}).get('start', '')
print(f" ⏱️ Timer running: {desc} ({project})")
print(f" Started: {start}")
else:
print(" No timer currently running")
# Weekly summary
print("\n7. Weekly summary (past 4 weeks)...")
weekly_start = datetime.utcnow() - timedelta(weeks=4)
weekly_hours = await client.calculate_weekly_hours(
workspace_id=workspace_id,
user_id=user['id'],
start_date=weekly_start
)
if weekly_hours:
for week in sorted(weekly_hours.keys()):
hours = weekly_hours[week]
print(f" Week of {week}: {hours:.2f} hours")
else:
print(" No time entries in the past 4 weeks")
print("\n" + "=" * 60)
print("Example completed successfully!")
print("=" * 60)
except Exception as e:
print(f"\nError: {e}")
import traceback
traceback.print_exc()
finally:
await client.close()
if __name__ == "__main__":
asyncio.run(main())