|
| 1 | +# resume_tokens.py |
| 2 | +"""MCP Server demonstrating resume tokens.""" |
| 3 | + |
| 4 | +import logging |
| 5 | +import asyncio |
| 6 | +import uuid |
| 7 | +from typing import Dict, Optional, Any, List |
| 8 | +from pydantic import BaseModel |
| 9 | + |
| 10 | +from mcp.server import fastmcp |
| 11 | + |
| 12 | +# --- Basic Setup --- |
| 13 | +logging.basicConfig(level=logging.INFO) |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class OrderData(BaseModel): |
| 18 | + total_amount: float |
| 19 | + |
| 20 | +class OrderResult(BaseModel): |
| 21 | + order_id: str |
| 22 | + total_amount: float |
| 23 | + |
| 24 | +class OrderProgress(BaseModel): |
| 25 | + order_id: str |
| 26 | + status: str |
| 27 | + progress_percentage: int |
| 28 | + current_step: str |
| 29 | + result: Optional[OrderResult] = None |
| 30 | + error: Optional[str] = None |
| 31 | + |
| 32 | +# Global steps definition |
| 33 | +ORDER_STEPS: List[OrderProgress] = [ |
| 34 | + OrderProgress(order_id="", status="processing", progress_percentage=15, current_step="Validating order data"), |
| 35 | + OrderProgress(order_id="", status="processing", progress_percentage=30, current_step="Checking inventory"), |
| 36 | + OrderProgress(order_id="", status="processing", progress_percentage=50, current_step="Processing payment"), |
| 37 | + OrderProgress(order_id="", status="processing", progress_percentage=70, current_step="Allocating resources"), |
| 38 | + OrderProgress(order_id="", status="processing", progress_percentage=85, current_step="Preparing shipment"), |
| 39 | + OrderProgress(order_id="", status="completed", progress_percentage=100, current_step="Finalizing order") |
| 40 | +] |
| 41 | + |
| 42 | +# Global storage for order operations (in production, use proper database/cache) |
| 43 | +order_operations: Dict[str, OrderProgress] = {} |
| 44 | + |
| 45 | +# Map resume tokens to order IDs |
| 46 | +resume_token_to_order_id: Dict[str, str] = {} |
| 47 | +order_id_to_latest_token: Dict[str, str] = {} |
| 48 | +# Store original order data for validation |
| 49 | +order_id_to_order_data: Dict[str, OrderData] = {} |
| 50 | + |
| 51 | +# --- MCP Server Setup --- |
| 52 | +mcp = fastmcp.FastMCP("OrderCreation", port=8090, stateless_http=True) |
| 53 | + |
| 54 | + |
| 55 | +# --- Async Order Creation Workflow --- |
| 56 | +async def fake_order_creation_workflow(order_id: str, order_data: OrderData) -> None: |
| 57 | + """ |
| 58 | + Simulated async order creation workflow using global steps. |
| 59 | + Each step takes 10 seconds. |
| 60 | + """ |
| 61 | + for step in ORDER_STEPS: |
| 62 | + # Update progress |
| 63 | + order_operations[order_id].status = step.status |
| 64 | + order_operations[order_id].progress_percentage = step.progress_percentage |
| 65 | + order_operations[order_id].current_step = step.current_step |
| 66 | + |
| 67 | + # Set result if this is the completion step |
| 68 | + if step.status == "completed": |
| 69 | + order_operations[order_id].result = OrderResult( |
| 70 | + order_id=order_id, |
| 71 | + total_amount=order_data.total_amount |
| 72 | + ) |
| 73 | + |
| 74 | + logger.info(f"Order {order_id}: {step.current_step} ({step.progress_percentage}%)") |
| 75 | + |
| 76 | + # Wait 10 seconds for each step |
| 77 | + await asyncio.sleep(10) |
| 78 | + |
| 79 | + |
| 80 | +def start_order_creation(order_data: OrderData) -> str: |
| 81 | + """Start a new order creation process and return the order ID.""" |
| 82 | + order_id = str(uuid.uuid4()) |
| 83 | + |
| 84 | + # Initialize progress tracking |
| 85 | + progress = OrderProgress( |
| 86 | + order_id=order_id, |
| 87 | + status="started", |
| 88 | + progress_percentage=0, |
| 89 | + current_step="Initializing order creation" |
| 90 | + ) |
| 91 | + |
| 92 | + # Store in global storage |
| 93 | + order_operations[order_id] = progress |
| 94 | + order_id_to_order_data[order_id] = order_data |
| 95 | + |
| 96 | + # Start the async workflow in a new task |
| 97 | + asyncio.create_task(fake_order_creation_workflow(order_id, order_data)) |
| 98 | + |
| 99 | + return order_id |
| 100 | + |
| 101 | + |
| 102 | +def generate_new_resume_token(order_id: str) -> str: |
| 103 | + """Generate a new resume token for an order and update mappings.""" |
| 104 | + new_token = str(uuid.uuid4()) |
| 105 | + |
| 106 | + # Clean up old token mapping if exists |
| 107 | + old_token = order_id_to_latest_token.get(order_id) |
| 108 | + if old_token and old_token in resume_token_to_order_id: |
| 109 | + del resume_token_to_order_id[old_token] |
| 110 | + |
| 111 | + # Set up new mapping |
| 112 | + resume_token_to_order_id[new_token] = order_id |
| 113 | + order_id_to_latest_token[order_id] = new_token |
| 114 | + |
| 115 | + return new_token |
| 116 | + |
| 117 | +# --- Tool Definitions --- |
| 118 | +@mcp.tool( |
| 119 | + name="create_order", |
| 120 | + description="Create an order in the database. Can start a new order or check status with resume token.", |
| 121 | +) |
| 122 | +def create_order(order_data: Optional[dict] = None, resume_token: Optional[str] = None) -> dict: |
| 123 | + """ |
| 124 | + Create an order in the database or check status of existing order. |
| 125 | + |
| 126 | + Args: |
| 127 | + order_data: Dictionary containing order information (required for new orders) |
| 128 | + resume_token: UUID token to check status of existing order (optional) |
| 129 | + |
| 130 | + Returns: |
| 131 | + Dictionary with order status and optional resume token |
| 132 | + """ |
| 133 | + if resume_token: |
| 134 | + # Get order ID from resume token |
| 135 | + order_id = resume_token_to_order_id.get(resume_token) |
| 136 | + |
| 137 | + # Validate order data if provided |
| 138 | + if order_data: |
| 139 | + current_order_data = OrderData(**order_data) |
| 140 | + original_order_data = order_id_to_order_data.get(order_id) |
| 141 | + |
| 142 | + if original_order_data and current_order_data.model_dump_json() != original_order_data.model_dump_json(): |
| 143 | + return { |
| 144 | + "error": "Order data mismatch. The provided order data does not match the original request.", |
| 145 | + "order_id": order_id, |
| 146 | + } |
| 147 | + |
| 148 | + else: |
| 149 | + # Create new order |
| 150 | + order_data_model = OrderData(**order_data) if order_data else OrderData(total_amount=0.0, items=[]) |
| 151 | + order_id = start_order_creation(order_data_model) |
| 152 | + |
| 153 | + # Get progress and convert to dict |
| 154 | + progress = order_operations[order_id] |
| 155 | + result = progress.model_dump() |
| 156 | + |
| 157 | + # Add resume token if still in progress |
| 158 | + if progress.status in ["started", "processing"]: |
| 159 | + result["next_resume_token"] = generate_new_resume_token(order_id) |
| 160 | + |
| 161 | + return result |
| 162 | + |
| 163 | + |
| 164 | +if __name__ == "__main__": |
| 165 | + mcp.run(transport="streamable-http") |
0 commit comments