Skip to content

Commit 5c96dcc

Browse files
committed
feat: add maximum polling attempts for async tasks
1 parent fedeb8e commit 5c96dcc

3 files changed

Lines changed: 22 additions & 2 deletions

File tree

src/modelscope_mcp_server/constants.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,6 @@
1414

1515
# Task polling interval (seconds)
1616
DEFAULT_TASK_POLL_INTERVAL_SECONDS = 5
17+
18+
# Maximum number of polling attempts for async tasks
19+
DEFAULT_MAX_POLL_ATTEMPTS = 60 # 60 attempts * 5 seconds = 5 minutes max

src/modelscope_mcp_server/settings.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
DEFAULT_API_TIMEOUT_SECONDS,
88
DEFAULT_IMAGE_GENERATION_TIMEOUT_SECONDS,
99
DEFAULT_IMAGE_TO_IMAGE_MODEL,
10+
DEFAULT_MAX_POLL_ATTEMPTS,
1011
DEFAULT_MODELSCOPE_API_INFERENCE_DOMAIN,
1112
DEFAULT_MODELSCOPE_DOMAIN,
1213
DEFAULT_TASK_POLL_INTERVAL_SECONDS,
@@ -63,6 +64,10 @@ class Settings(BaseSettings):
6364
default=DEFAULT_TASK_POLL_INTERVAL_SECONDS,
6465
description="Polling interval in seconds when waiting for async tasks",
6566
)
67+
max_poll_attempts: int = Field(
68+
default=DEFAULT_MAX_POLL_ATTEMPTS,
69+
description="Maximum number of polling attempts for async tasks",
70+
)
6671

6772
# Logging settings
6873
log_level: str = Field(default="INFO", description="Logging level")

src/modelscope_mcp_server/tools/aigc.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,15 @@ async def generate_image(
105105
# Step 2: poll task result until succeed/failed or timeout
106106
start_time = time.time()
107107
task_url = f"{settings.api_inference_domain}/v1/tasks/{task_id}"
108-
while True:
108+
attempt_count = 0
109+
110+
while attempt_count < settings.max_poll_attempts:
109111
# timeout check
110112
if time.time() - start_time > settings.default_image_generation_timeout_seconds:
111113
raise TimeoutError("Image generation timed out - please try again later")
112114

115+
attempt_count += 1
116+
113117
task_result = default_client.get(
114118
task_url,
115119
timeout=settings.default_api_timeout_seconds,
@@ -138,5 +142,13 @@ async def generate_image(
138142
f"Image generation failed: {error_msg}. Task ID: {task_id}, Request ID: {request_id}"
139143
)
140144

141-
logger.info(f"Image generation task {task_id} is {status}, waiting for next poll...")
145+
logger.info(
146+
f"Image generation task {task_id} is {status}, waiting for next poll... "
147+
f"(attempt {attempt_count}/{settings.max_poll_attempts})"
148+
)
142149
time.sleep(settings.task_poll_interval_seconds)
150+
151+
# If we exit the loop without success or failure, max attempts exceeded
152+
raise TimeoutError(
153+
f"Image generation exceeded maximum polling attempts ({settings.max_poll_attempts}). Task ID: {task_id}"
154+
)

0 commit comments

Comments
 (0)