@@ -4,6 +4,11 @@ import { UrlParam } from '../types/url-scanner'
44
55import type { RadarMCP } from '../index'
66
7+ const MAX_WAIT_SECONDS = 30
8+ const INTERVAL_SECONDS = 2
9+
10+ const sleep = ( ms : number ) => new Promise ( ( resolve ) => setTimeout ( resolve , ms ) )
11+
712export function registerUrlScannerTools ( agent : RadarMCP ) {
813 agent . server . tool (
914 'scan_url' ,
@@ -13,18 +18,54 @@ export function registerUrlScannerTools(agent: RadarMCP) {
1318 } ,
1419 async ( { url } ) => {
1520 try {
16- const accountId = '' // TODO agent.getActiveAccountId()
1721 const client = getCloudflareClient ( agent . props . accessToken )
18- const scanId = await client . urlScanner . scans . create ( { account_id : accountId , url } )
22+ const account_id = agent . env . ACCOUNT_ID
23+ const headers = {
24+ Authorization : `Bearer ${ agent . env . URL_SCANNER_API_TOKEN } ` ,
25+ }
26+
27+ // TODO investigate why this does not work
28+ // const scan = await (client.urlScanner.scans.create({ account_id, url: "https://www.example.com" }, { headers })).withResponse()
29+
30+ const res = await fetch (
31+ `https://api.cloudflare.com/client/v4/accounts/${ account_id } /urlscanner/v2/scan` ,
32+ {
33+ method : 'POST' ,
34+ headers,
35+ body : JSON . stringify ( { url } ) ,
36+ }
37+ )
38+ if ( ! res . ok ) {
39+ throw new Error ( 'Failed to submit scan' )
40+ }
1941
20- // TODO get scan...
42+ const scan : any = await res . json ( )
43+ const scanId = scan ?. uuid
44+
45+ let r = null
46+ let elapsed = 0
47+ while ( elapsed < MAX_WAIT_SECONDS ) {
48+ try {
49+ r = await client . urlScanner . scans . get ( scanId , { account_id } , { headers } )
50+ } catch {
51+ // Wait
52+ }
53+ if ( r ) break
54+
55+ await sleep ( INTERVAL_SECONDS * 1000 )
56+ elapsed += INTERVAL_SECONDS
57+ }
58+
59+ if ( ! r ) {
60+ throw new Error ( 'Scan timed out or still not ready' )
61+ }
2162
2263 return {
2364 content : [
2465 {
2566 type : 'text' ,
2667 text : JSON . stringify ( {
27- result : scanId ,
68+ result : r ,
2869 } ) ,
2970 } ,
3071 ] ,
0 commit comments