---
title: "Microsoft Agent Framework"
description: "TwexAPI MCP를 통해 트윗 검색, 프로필 및 검토된 X 쓰기 작업을 위한 Python 또는 .NET Microsoft Agent Framework 워크플로를 구축합니다."
---

TwexAPI MCP 서버를 통해 Microsoft Agent Framework Twitter API 에이전트를 구축합니다. 트윗을 검색하고, 프로필을 조회하며, 트렌드를 읽고, 쓰기 작업을 검토합니다. 채팅 기록 외부에 트윗 ID, 커서 및 경로 이름을 영속 저장합니다.

## TwexAPI와 함께 Microsoft Agent Framework를 사용하는 이유

프레임워크는 Python 또는 .NET에서 도구 호출 에이전트를 호스팅합니다. TwexAPI는 Streamable HTTP를 통해 `explore` 및 `twexapi_request`를 제공합니다.

| 에이전트 작업 | TwexAPI 경로 | 다음 단계를 위해 보존 |
| --- | --- | --- |
| 트윗 검색 | `POST /twitter/advanced_search/page` | 쿼리, 트윗 ID, 작성자, `created_at`, 커서 |
| 프로필 조회 | `GET /twitter/{screen_name}/about` | 사용자 ID, 사용자명, 약력, 팔로워 수 |
| 팔로워 목록 | `POST /v3/twitter/users/followers` | 사용자명, 팔로워 행, `next_cursor` |
| 게시 또는 답글 | `POST /twitter/tweets/create` | 트윗 ID, 경로, 사람 승인, 쿠키 확인 |

이미 Microsoft 에이전트 호스트를 실행 중이면 이 프레임워크를 사용하세요. 모델 없는 결정적 작업에는 [Python SDK](/sdks/python) 또는 [C# SDK](/sdks/csharp)를 사용하세요.

## 전제조건

- Python 3.10 이상, 또는 MCP Streamable HTTP 지원이 있는 .NET 8+ 호스트
- [TwexAPI API 키](https://twexapi.io/dashboard)
- 에이전트 런타임용 구성된 모델
Public docs focus on API-key reads.

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

## 설치

Python:

```bash
python -m pip install "agent-framework>=0.2" mcp python-dotenv pydantic
```

```txt .env
TWEXAPI_API_KEY=YOUR_API_KEY
OPENAI_API_KEY=sk-...
```

## TwexAPI MCP 연결

```python
import os

from agent_framework import MCPStreamableHTTPTool

mcp_tool = MCPStreamableHTTPTool(
    name="twexapi",
    url="https://api.twexapi.io/mcp",
    headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
    description="TwexAPI X/Twitter tools through MCP",
)
```

동등한 호스트 JSON:

```json
{
  "name": "twexapi",
  "transport": "streamable-http",
  "url": "https://api.twexapi.io/mcp",
  "headers": {
    "x-api-key": "YOUR_API_KEY"
  }
}
```

인증되지 않은 MCP 요청은 `401`을 반환합니다.

## 전체 예제 (Python)

```python
import asyncio
import os
from pathlib import Path
from typing import Literal

from agent_framework import ChatAgent, MCPStreamableHTTPTool
from agent_framework.openai import OpenAIChatClient
from dotenv import load_dotenv
from pydantic import BaseModel


class TweetRow(BaseModel):
    tweet_id: str
    text: str
    author_username: str | None = None
    created_at: str | None = None


class TweetSearchHandoff(BaseModel):
    query: str
    route_used: str
    tweets: list[TweetRow]
    has_more: bool
    next_cursor: str | None = None
    stop_reason: Literal[
        "complete",
        "requested_limit",
        "cursor_stalled",
        "page_cap",
    ]


async def main() -> None:
    load_dotenv()

    mcp_tool = MCPStreamableHTTPTool(
        name="twexapi",
        url="https://api.twexapi.io/mcp",
        headers={"x-api-key": os.environ["TWEXAPI_API_KEY"]},
        description="TwexAPI X/Twitter tools through MCP",
    )

    async with mcp_tool:
        agent = ChatAgent(
            chat_client=OpenAIChatClient(model_id="gpt-4o"),
            name="twexapi_agent",
            instructions=(
                "Use TwexAPI MCP. Call explore before twexapi_request. "
                "Preserve exact IDs and cursors. Never invent missing fields. "
                "Ask for confirmation before read_only: false actions. "
                "Return only JSON for TweetSearchHandoff."
            ),
            tools=[mcp_tool],
        )

        response = await agent.run(
            "Search 25 recent tweets about Microsoft Agent Framework MCP. "
            "Return query, route_used, tweets, has_more, next_cursor, and stop_reason as JSON."
        )

        handoff = TweetSearchHandoff.model_validate_json(response.text)
        Path("twexapi-agent-framework-handoff.json").write_text(
            handoff.model_dump_json(indent=2),
            encoding="utf-8",
        )


asyncio.run(main())
```

모델이 JSON을 Markdown 펜스로 감싸면 제거하세요. 대화 상태 외부에 파일을 영속 저장합니다.

## .NET 호스트 스케치

```csharp
var mcp = new McpStreamableHttpTool
{
    Name = "twexapi",
    Url = new Uri("https://api.twexapi.io/mcp"),
    Headers = { ["x-api-key"] = Environment.GetEnvironmentVariable("TWEXAPI_API_KEY")! },
};
```

동일한 지시를 사용하세요. `explore` 먼저, 커서 보존, `read_only: false` 전 중지. 타입 REST 호출은 [C# SDK](/sdks/csharp)에 속합니다.

## MCP 응답 계약 보존

모든 페이지에서 동일한 쿼리와 필터를 재사용하세요. 각 커서는 불투명 값으로 취급합니다.

요청한 총량에 도달하거나, `has_more`가 false이거나, `next_cursor`가 반복되거나, 페이지 상한에 도달하면 페이지네이션을 중지합니다.

## 재개 가능한 에이전트 핸드오프 유지

<CardGroup cols={2}>
  <Card title="트윗 페이지" icon="message-square">
    `tweet_id`, `text`, `author_username`, `created_at`, `has_more`, `next_cursor`, 원본 쿼리를 저장합니다.
  </Card>
  <Card title="프로필 행" icon="user-round">
    `user_id`, `username`, `name`, `description`, 팔로워 수를 저장합니다.
  </Card>
  <Card title="팔로워 페이지" icon="users">
    소스 사용자명, 팔로워 행, `next_cursor`, 페이지 인덱스를 저장합니다.
  </Card>
  <Card title="쓰기 작업" icon="send">
    경로, 미리보기 텍스트, 승인을 저장합니다. 쿠키는 핸드오프 파일 밖에 보관하세요. 참조.
  </Card>
</CardGroup>

[Agent MCP Handoff](/mcp/agent-handoff)를 참조하세요.

## 오류 처리 구축

| 상태 | 의미 | 에이전트 결정 |
| --- | --- | --- |
| `400` | 잘못된 경로 또는 매개변수 | 재시도 전에 요청을 수정합니다 |
| `401` | API 키 누락 또는 유효하지 않음 | 중지하고 자격 증명을 교체합니다 |
| `403` | 액세스 거부 또는 크레딧 | 쓰기 일시 중지; [Get Balance](/api-reference/balance-endpoints/get-balance-api-balance-get) 확인 |
| `429` | 속도 제한 도달 | 백오프 후 동일 커서로 재개합니다 |
| `5xx` | 일시적 서버 오류 | 안전한 읽기에 제한된 백오프를 적용합니다 |

타임아웃 후 읽기 확인 없이 쓰기를 재시도하지 마세요. [Error Handling](/guides/error-handling) 및 [Rate Limits](/guides/rate-limits)를 참조하세요.

## X 작업 전 승인 요구

```txt
You have access to TwexAPI MCP tools.
Call explore before twexapi_request.
Use only relative paths returned by explore.
Return tweet_id, user_id, author_username, route_used, has_more, and next_cursor.
Ask for confirmation before read_only: false actions.
Never print cookie or auth_token values.
```

[CLI](/sdks/cli) `--dry-run`으로 미리보기하세요. 승인된 쓰기는 감독 없는 에이전트 루프가 아닌 REST 또는 SDK를 통해 실행하세요.

## 프로덕션 가이드

- 환경별 API 키를 사용하세요. 프롬프트에 키를 포함하지 마세요.
- MCP 도구 이름과 반환된 `path` 값을 로깅하고, 쿠키 헤더는 로깅하지 마세요.
- 커서와 트윗 ID를 `ChatAgent` 메모리뿐 아니라 저장소에 영속 저장하세요.
- 읽기 연구와 쓰기 실행을 별도 에이전트 또는 작업으로 분리하세요.

## 패키지 버전

| 패키지 | 지원 범위 |
| --- | --- |
| Python | `>=3.10` |
| `agent-framework` | `>=0.2` |
| `mcp` | `>=1.9` |
| `pydantic` | `>=2.7` |

## 다음 단계

- [MCP Tools](/mcp/tools)
- [Agent MCP Handoff](/mcp/agent-handoff)
-
- [Python SDK](/sdks/python)
- [C# SDK](/sdks/csharp)
- [Advanced Twitter Search](/api-reference/search-endpoints/get-data-page-twitter-advanced-search-page-post)
