Koog로 Bright Data Web MCP 웹 스크래핑하기

·5분 읽기

원문: https://docs.koog.ai/examples/WebMcpClient/

Bright Data의 Web MCP와 Koog로 웹 스크래핑하기

이 튜토리얼에서는 Koog 에이전트를 Bright Data의 Web MCP 서버에 연결하고, 에이전트가 웹 스크래핑과 데이터 수집 작업을 수행하도록 합니다. Model Context Protocol을 통해 Bright Data의 강력한 웹 스크래핑 인프라를 사용하여 Koog.ai에 대한 정보를 검색하는 방법을 보여 줍니다.

자체 웹 스크래핑 요구사항에 맞게 조정할 수 있도록, 간단하고 재현 가능한 최소한의 현실적인 에이전트 + 도구 설정에 집중합니다.

사전 요구사항

  • 환경 변수로 내보낸 OpenAI API 키: OPENAI_API_KEY
  • 환경 변수로 내보낸 Bright Data API 토큰: BRIGHT_DATA_API_TOKEN
  • PATH에서 사용할 수 있는 Node.js와 npx
  • Koog 의존성이 포함된 Kotlin 개발 환경

: Bright Data MCP 서버는 복잡한 웹사이트, CAPTCHA, 안티봇 조치를 처리할 수 있는 엔터프라이즈급 웹 스크래핑 도구에 접근할 수 있게 해 줍니다.

1) API 자격 증명 설정하기

비밀 정보를 안전하게 유지하고 코드 밖에 두기 위해 두 API 키를 모두 환경 변수에서 읽습니다.

1// Get API keys from environment variables
2val openAIApiKey = System.getenv("OPENAI_API_KEY")
3    ?: error("OPENAI_API_KEY environment variable is not set")
4val brightDataToken = System.getenv("BRIGHT_DATA_API_TOKEN")
5    ?: error("BRIGHT_DATA_API_TOKEN environment variable is not set")

2) Bright Data의 Web MCP 서버 시작하기

npx를 사용해 Bright Data의 MCP 서버를 실행하고, API 토큰으로 구성합니다. 이 서버는 Model Context Protocol을 통해 웹 스크래핑 기능을 노출합니다.

1println("Starting Bright Data MCP server...")
2 
3// Start the Bright Data MCP server as a separate process
4val processBuilder = ProcessBuilder("npx", "@brightdata/mcp")
5 
6// Set the API_TOKEN environment variable for the MCP server process
7val environment = processBuilder.environment()
8environment["API_TOKEN"] = brightDataToken
9 
10// Start the process
11val process = processBuilder.start()
12 
13// Give the process a moment to start
14Thread.sleep(2000)

3) Koog에서 연결하고 에이전트 만들기

OpenAI 실행기를 사용하는 Koog AIAgent를 만들고, STDIO 전송을 통해 해당 도구 레지스트리를 Bright Data MCP 서버에 연결합니다. 그런 다음 사용 가능한 도구를 살펴보고 웹 스크래핑 작업을 실행합니다.

1println("Creating STDIO transport...")
2try {
3    // Create the STDIO transport
4    val transport = McpToolRegistryProvider.defaultStdioTransport(process)
5    
6    println("Creating tool registry...")
7    
8    // Create a tool registry with tools from the Bright Data MCP server
9    val toolRegistry = McpToolRegistryProvider.fromTransport(
10        transport = transport,
11        name = "bright-data-client",
12        version = "1.0.0"
13    )
14    
15    // Print available tools (optional - for debugging)
16    println("Available tools from Bright Data MCP server:")
17    toolRegistry.tools.forEach { tool ->
18        println("- ${tool.name}")
19    }
20    
21    // Create the agent with MCP tools
22    val agent = AIAgent(
23        executor = simpleOpenAIExecutor(openAIApiKey),
24        systemPrompt = "You are a helpful assistant with access to web scraping and data collection tools from Bright Data. You can help users gather information from websites, analyze web data, and provide insights.",
25        llmModel = OpenAIModels.Chat.GPT4o,
26        temperature = 0.7,
27        toolRegistry = toolRegistry,
28        maxIterations = 100
29    )
30    
31    val result = agent.run("Please search for Koog.ai and tell me what is it and who invented it")
32    
33    println("\nAgent response:")
34    println(result)
35    
36} catch (e: Exception) {
37    println("Error: ${e.message}")
38    e.printStackTrace()
39} finally {
40    println("Shutting down MCP server...")
41    process.destroyForcibly()
42}

4) 전체 코드 예제

다음은 Bright Data의 Web MCP를 사용한 웹 스크래핑을 보여 주는 완전한 실행 예제입니다.

1package koog
2 
3import ai.koog.agents.core.agent.AIAgent
4import ai.koog.agents.mcp.McpToolRegistryProvider
5import ai.koog.prompt.executor.clients.openai.OpenAIModels
6import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor
7import kotlinx.coroutines.runBlocking
8 
9/**
10 * The entry point of the program demonstrating AI-driven web scraping and data collection.
11 *
12 * This function initializes a Bright Data MCP server, sets up tool integration,
13 * and defines an AI agent for interacting with web scraping tools. It demonstrates the
14 * following key operations:
15 *
16 * 1. Starts the Bright Data MCP server using a subprocess with proper API token configuration.
17 * 2. Configures a registry of tools from the MCP server via STDIO transport communication.
18 * 3. Creates an AI agent leveraging OpenAI's GPT-4o model with web scraping capabilities.
19 * 4. Runs the agent to perform a specified task (e.g., searching for and analyzing web content
20 *    about Koog.ai).
21 * 5. Cleans up by shutting down the MCP server process after execution.
22 *
23 * This function is intended for tutorial purposes, demonstrating how to integrate
24 * MCP (Model Context Protocol) servers with AI agents for web data collection and analysis.
25 * It requires OPENAI_API_KEY and BRIGHT_DATA_API_TOKEN environment variables to be set.
26 */
27fun main() = runBlocking {
28    // Get API keys from environment variables
29    val openAIApiKey = System.getenv("OPENAI_API_KEY")
30        ?: error("OPENAI_API_KEY environment variable is not set")
31    val brightDataToken = System.getenv("BRIGHT_DATA_API_TOKEN")
32        ?: error("BRIGHT_DATA_API_TOKEN environment variable is not set")
33 
34    println("Starting Bright Data MCP server...")
35 
36    // Start the Bright Data MCP server as a separate process
37    val processBuilder = ProcessBuilder("npx", "@brightdata/mcp")
38 
39    // Set the API_TOKEN environment variable for the MCP server process
40    val environment = processBuilder.environment()
41    environment["API_TOKEN"] = brightDataToken
42 
43    // Start the process
44    val process = processBuilder.start()
45 
46    // Give the process a moment to start
47    Thread.sleep(2000)
48 
49    println("Creating STDIO transport...")
50 
51    try {
52        // Create the STDIO transport
53        val transport = McpToolRegistryProvider.defaultStdioTransport(process)
54        
55        println("Creating tool registry...")
56        
57        // Create a tool registry with tools from the Bright Data MCP server
58        val toolRegistry = McpToolRegistryProvider.fromTransport(
59            transport = transport,
60            name = "bright-data-client",
61            version = "1.0.0"
62        )
63        
64        // Print available tools (optional - for debugging)
65        println("Available tools from Bright Data MCP server:")
66        toolRegistry.tools.forEach { tool ->
67            println("- ${tool.name}")
68        }
69        
70        // Create the agent with MCP tools
71        val agent = AIAgent(
72            executor = simpleOpenAIExecutor(openAIApiKey),
73            systemPrompt = "You are a helpful assistant with access to web scraping and data collection tools from Bright Data. You can help users gather information from websites, analyze web data, and provide insights.",
74            llmModel = OpenAIModels.Chat.GPT4o,
75            temperature = 0.7,
76            toolRegistry = toolRegistry,
77            maxIterations = 100
78        )
79        
80        val result = agent.run("Please search for Koog.ai and tell me what is it and who invented it")
81        
82        println("\nAgent response:")
83        println(result)
84        
85    } catch (e: Exception) {
86        println("Error: ${e.message}")
87        e.printStackTrace()
88    } finally {
89        println("Shutting down MCP server...")
90        process.destroyForcibly()
91    }
92}

문제 해결

  • 연결 문제: 에이전트가 MCP 서버에 연결할 수 없다면 Bright Data MCP 패키지가 npx @brightdata/mcp를 통해 올바르게 설치되어 있는지 확인하세요.
  • API 토큰 오류: BRIGHT_DATA_API_TOKEN이 유효하고 웹 스크래핑에 필요한 권한을 가지고 있는지 다시 확인하세요.
  • OpenAI 인증: OPENAI_API_KEY 환경 변수가 올바르게 설정되어 있고 API 키가 유효한지 확인하세요.
  • 프로세스 시간 초과: 서버 시작에 더 오래 걸린다면 Thread.sleep(2000) 시간을 늘리세요.

다음 단계

  • 다양한 쿼리 탐색: 여러 웹사이트를 스크래핑하거나 다양한 주제를 검색해 보세요.
  • 사용자 지정 도구 통합: Bright Data의 웹 스크래핑 기능과 함께 자체 도구를 추가하세요.
  • 고급 스크래핑: 주거용 프록시, CAPTCHA 해결, JavaScript 렌더링 같은 Bright Data의 고급 기능을 활용하세요.
  • 데이터 처리: 스크래핑한 데이터를 다른 Koog 에이전트와 결합해 분석과 인사이트를 얻으세요.
  • 프로덕션 배포: 자동화된 웹 데이터 수집을 위해 이 패턴을 애플리케이션에 통합하세요.

배운 내용

이 튜토리얼에서는 다음을 수행하는 방법을 보여 주었습니다.

  • Bright Data의 Web MCP를 설정하고 구성하기
  • STDIO 전송을 통해 Koog AI 에이전트를 외부 MCP 서버에 연결하기
  • 자연어 지시를 사용해 AI 주도 웹 스크래핑 작업 수행하기
  • 적절한 리소스 정리와 오류 관리 처리하기
  • 프로덕션 준비가 된 웹 스크래핑 애플리케이션을 위한 코드 구조화하기

Koog의 AI 에이전트 기능과 Bright Data의 엔터프라이즈 웹 스크래핑 인프라를 결합하면 자동화된 데이터 수집 및 분석 워크플로를 위한 강력한 기반을 마련할 수 있습니다.