---
title: "AG2"
description: "트윗 검색, 프로필, 타임라인 및 위임된 연구 워크플로를 위해 AG2 다중 에이전트 시스템을 TwexAPI에 연결하세요."
---

[AG2](https://github.com/ag2ai/ag2)는 다중 에이전트 시스템을 위한 오픈 소스 Python 프레임워크입니다. TwexAPI는 아직 기본 AG2 검색 도구 키트를 제공하지 않습니다. `MCPToolkit`을 사용하여 AG2 에이전트를 [TwexAPI MCP 서버](/mcp/overview)에 연결하면 에이전트가 인프라 내부에 API 자격 증명을 유지하면서 `explore` 및 `twexapi_request`를 호출할 수 있습니다.

API가 반환하는 모든 트윗 ID, 사용자 ID 및 커서를 유지합니다.

## TwexAPI와 함께 AG2를 사용하는 이유는 무엇입니까?

AG2는 도구 노출, 위임 및 미들웨어에 대한 명시적인 제어를 제공합니다. 모든 REST 경로를 하드코딩하지 않고도 다중 에이전트 연구를 원할 때 TwexAPI MCP와 함께 사용하세요.

| 경계 | AG2 제어 | 혜택 |
| ----------------- | ------------------------- | ---------------------------------------------------------------------- |
| 도구 구성 | `MCPToolkit(...)` | `explore` 및 `twexapi_request`로 제한하거나 추가로 필터링하세요. |
| 모델 입력 | MCP 도구 스키마 | 모델은 검색된 엔드포인트에서만 경로를 선택합니다. |
| 런타임 범위 | `Variable` | 실행 시 사용자별 또는 테넌트별 헤더 확인 |
| 대표단 | `Agent.as_tool()` | 코디네이터의 컨텍스트에서 검색자의 도구 호출 기록을 유지합니다. |
| 수송 | `MCPServerConfig` | `x-api-key`를 사용하여 `https://api.twexapi.io/mcp`를 가리킵니다. |

이는 연구, 모니터링 및 보고 상담원에게 적합합니다. 모델 결정이 필요하지 않은 결정적 작업에는 [Python SDK](/sdks/python) 또는 [Prefect 컬렉션](/guides/prefect)을 사용하세요.

## 전제조건

* 파이썬 3.10 이상
* A [TwexAPI API 키](https://twexapi.io/dashboard)
* AG2에서 지원하는 LLM 공급자 키

공개 X 읽기에는 X 개발자 자격 증명이 필요하지 않습니다. TwexAPI로 인증하세요.

## AG2 설치

```bash
python -m pip install "ag2>=1.0.0" python-dotenv
```

모델 공급자도 추가로 설치하세요.

```bash
python -m pip install "ag2[anthropic]>=1.0.0"
```

소스 제어 외부에 비밀을 저장합니다.

```bash
export TWEXAPI_API_KEY="YOUR_API_KEY"
export ANTHROPIC_API_KEY="YOUR_ANTHROPIC_KEY"
```

## MCPToolkit으로 TwexAPI MCP 연결

자격 증명이 인프라에 유지되어야 하는 경우 클라이언트 측 'MCPToolkit'을 사용하세요. TwexAPI MCP는 'explore' 및 'twexapi_request'를 노출합니다.

```python
import asyncio
import os

from ag2 import Agent
from ag2.config import AnthropicConfig
from ag2.tools import MCPToolkit, MCPServerConfig
from dotenv import load_dotenv

load_dotenv()
config = AnthropicConfig(model="claude-sonnet-4-20250514")

twexapi_mcp = MCPToolkit(
    MCPServerConfig(
        server_url="https://api.twexapi.io/mcp",
        server_label="twexapi",
        headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
        allowed_tools=["explore", "twexapi_request"],
    )
)

agent = Agent(
    "x-researcher",
    prompt=(
        "Search X for evidence before answering. "
        "Always call explore before twexapi_request. "
        "Quote tweet text verbatim and keep every tweet ID you receive. "
        "Ask for confirmation before read_only: false actions."
    ),
    config=config,
    tools=[twexapi_mcp],
)


async def main() -> None:
    reply = await agent.ask(
        "What are developers saying about AI agents on X this week? "
        "Return tweet IDs, authors, and a 5-bullet summary."
    )
    print(reply.body)


asyncio.run(main())
```

`x-api-key`가 있는 `헤더`가 필요합니다. `https://api.twexapi.io/mcp`에 대한 인증되지 않은 요청은 `401`을 반환합니다.

## 상담원 역할별로 도구 제한

검색 전용 에이전트에 '탐색' 액세스 권한을 부여하세요. 실행 에이전트에 두 도구를 모두 제공합니다.

```python
catalog_agent_tools = [
    MCPToolkit(
        MCPServerConfig(
            server_url="https://api.twexapi.io/mcp",
            headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
            allowed_tools=["explore"],
            server_label="twexapi-catalog",
        )
    )
]

execution_agent_tools = [
    MCPToolkit(
        MCPServerConfig(
            server_url="https://api.twexapi.io/mcp",
            headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
            allowed_tools=["explore", "twexapi_request"],
            server_label="twexapi-execute",
        )
    )
]
```

## 다중 에이전트 팀에서 검색 위임

`Agent.as_tool()`은 에이전트를 다른 에이전트의 도구로 노출합니다. 코디네이터는 내부 도구 호출 내역이 아닌 대리인의 최종 답변을 받습니다.

```python
searcher = Agent(
    "searcher",
    prompt=(
        "Use TwexAPI MCP to search public X posts. "
        "Call explore first. Return tweet text with IDs. Do not summarise away IDs."
    ),
    config=config,
    tools=[twexapi_mcp],
)

analyst = Agent(
    "analyst",
    prompt="Turn tweet records into a factual brief. Keep every tweet ID.",
    config=config,
)

coordinator = Agent(
    "coordinator",
    prompt="Delegate the search, then pass the tweets to the analyst.",
    config=config,
    tools=[
        searcher.as_tool(description="Search public X posts and return raw tweet records."),
        analyst.as_tool(description="Analyse tweet records. Pass them in the context parameter."),
    ],
)

reply = await coordinator.ask("Brief me on this week's discussion of AI agents on X.")
print(reply.body)
```

## 핸드오프 체크리스트

이후 워크플로 단계가 채팅 기록에 의존하지 않도록 MCP 응답의 지속성 필드를 저장합니다.

| 데이터 유형 | 가게 |
| --- | --- |
| 트윗 | `tweet_id`, `text`, `author_username`, `created_at`, `has_more`, `next_cursor`, original query |
| 프로필 | `user_id`, `username`, `name`, `description`, `followers_count`, source lookup |
| 동향 | 국가, 주제, 콘텐츠 태그, 트윗 행, 요청된 필터 |
| 쓰기 | `tweet_id`, route name, status, confirmation record |

전체 체크리스트는 [에이전트 MCP 핸드오프](/mcp/agent-handoff)를 참조하세요.

## 쪽수 매기기

`explore`가 페이지가 매겨진 경로를 반환하면 문서화된 커서 필드를 `twexapi_request`를 통해 변경 없이 다시 전달하세요. 커서를 불투명한 문자열로 처리합니다. `tweet_id` 또는 `user_id`에서 중복된 행을 삭제합니다.

```python
checkpoint = {
    "route_used": "/twitter/advanced_search/page",
    "query": "AI agents",
    "has_more": True,
    "next_cursor": "cursor_123",
}
```

## Docs MCP와 결합

에이전트가 경로를 선택하기 전에 TwexAPI 문서를 검색해야 하는 경우 [Docs MCP 서버](/mcp/docs-mcp)를 추가하세요.

```python
tools=[
    MCPToolkit(
        MCPServerConfig(
            server_url="https://docs.twexapi.io/mcp",
            server_label="twexapi-docs",
        )
    ),
    twexapi_mcp,
]
```

## 실패 처리

MCP 및 REST 오류는 툴킷을 통해 HTTP 오류로 나타납니다. 재시도하기 전에 상태에 따라 분기하세요.

| 상태 | 행동 |
| ------ | ------ |
| `400` | 요청을 수정하세요. 변경하지 않고 다시 시도하지 마세요. |
| `401` | `x-api-key` 헤더 또는 Bearer 토큰을 확인하세요. |
| `403` | 계정 액세스, 크레딧, 쓰기 권한을 확인하세요. |
| `429` | 뒤로 물러나서 커서를 유지하십시오. |
| `5xx` | 제한된 백오프로 다시 시도하세요. |

모든 호출에 대해 재시도, 승인 게이트 또는 감사 로깅이 필요한 경우 'MCPToolkit'을 AG2 도구 미들웨어로 래핑하세요.

## 제공자 측 MCP(Anthropic에만 해당)

Anthropic을 대상으로 하고 공급자에게 자격 증명 전달을 허용하는 경우 `MCPToolkit` 대신 `MCPServerTool`을 사용하세요. 공급자에 구애받지 않는 배포와 API 키가 인프라에 유지되어야 하는 경우 'MCPToolkit'을 선호합니다.

## 관련 가이드

* [AG2 MCP 서버 설명서](https://docs.ag2.ai/docs/user-guide/tools/mcp_servers/)
* [MCP 서버](/mcp/개요)
* [MCP 도구](/mcp/tools)
* [랭체인](/guides/langchain)
* [CrewAI](/guides/crewai)
* [파이썬 SDK](/sdks/python)
