1- import { callTool } from '../call-tool.js' ;
1+ import { getClient , extractResult , type ToolResult } from '../call-tool.js' ;
22import chalk from 'chalk' ;
3+ import ora from 'ora' ;
34
45const SERVER = 'image.mcp.atxp.ai' ;
5- const TOOL = 'image_create_image' ;
6+ const POLL_INTERVAL_MS = 3000 ;
67
78export async function imageCommand ( prompt : string ) : Promise < void > {
89 if ( ! prompt || prompt . trim ( ) . length === 0 ) {
@@ -11,6 +12,73 @@ export async function imageCommand(prompt: string): Promise<void> {
1112 process . exit ( 1 ) ;
1213 }
1314
14- const result = await callTool ( SERVER , TOOL , { prompt : prompt . trim ( ) } ) ;
15- console . log ( result ) ;
15+ const client = await getClient ( SERVER ) ;
16+
17+ // Initiate async generation
18+ const initResult = ( await client . callTool ( {
19+ name : 'image_create_image_async' ,
20+ arguments : { prompt : prompt . trim ( ) } ,
21+ } ) ) as ToolResult ;
22+
23+ const initText = extractResult ( initResult ) ;
24+ let taskId : string | undefined ;
25+ try {
26+ const parsed = JSON . parse ( initText ) ;
27+ taskId = parsed . taskId ;
28+ } catch {
29+ // If the response isn't JSON with a taskId, it may have completed synchronously
30+ console . log ( initText ) ;
31+ return ;
32+ }
33+
34+ if ( ! taskId ) {
35+ console . log ( initText ) ;
36+ return ;
37+ }
38+
39+ // Poll for completion
40+ const spinner = ora ( 'Generating image...' ) . start ( ) ;
41+ try {
42+ while ( true ) {
43+ await new Promise ( ( r ) => setTimeout ( r , POLL_INTERVAL_MS ) ) ;
44+
45+ const pollResult = ( await client . callTool ( {
46+ name : 'image_get_image_async' ,
47+ arguments : { taskId } ,
48+ } ) ) as ToolResult ;
49+
50+ const pollText = extractResult ( pollResult ) ;
51+ let parsed : any ;
52+ try {
53+ parsed = JSON . parse ( pollText ) ;
54+ } catch {
55+ // Non-JSON response — treat as final
56+ spinner . stop ( ) ;
57+ console . log ( pollText ) ;
58+ return ;
59+ }
60+
61+ if ( parsed . status === 'completed' || parsed . status === 'success' ) {
62+ spinner . succeed ( 'Image generated' ) ;
63+ // Remove status field to show just the result
64+ delete parsed . status ;
65+ console . log ( JSON . stringify ( parsed , null , 2 ) ) ;
66+ return ;
67+ } else if ( parsed . status === 'failed' || parsed . error ) {
68+ spinner . fail ( 'Image generation failed' ) ;
69+ console . error ( chalk . red ( parsed . error || JSON . stringify ( parsed ) ) ) ;
70+ process . exit ( 1 ) ;
71+ }
72+
73+ // Still in progress — update spinner
74+ if ( parsed . status ) {
75+ spinner . text = `Generating image... (${ parsed . status } )` ;
76+ }
77+ }
78+ } catch ( error ) {
79+ spinner . fail ( 'Image generation failed' ) ;
80+ const errorMessage = error instanceof Error ? error . message : String ( error ) ;
81+ console . error ( chalk . red ( `Error: ${ errorMessage } ` ) ) ;
82+ process . exit ( 1 ) ;
83+ }
1684}
0 commit comments