Skip to content
Twexapi
English
Esc
↑↓navigate↵open⌘Jpreview
On this page

Microsoft Agent Framework

Build Python or .NET Microsoft Agent Framework workflows for tweet search, profiles, and reviewed X writes through TwexAPI MCP.

Build a Microsoft Agent Framework Twitter API agent through TwexAPI’s MCP server. Search tweets, inspect profiles, read trends,. Persist tweet IDs, cursors, and route names outside the chat transcript.

Why use Microsoft Agent Framework with TwexAPI?

The framework hosts tool-calling agents in Python or .NET. TwexAPI supplies explore and twexapi_request over Streamable HTTP.

Agent task TwexAPI route Preserve for the next step
Search tweets POST /twitter/advanced_search/page Query, tweet IDs, authors, created_at, cursor
Inspect a profile GET /twitter/{screen_name}/about User ID, username, biography, follower count
List followers POST /v3/twitter/users/followers Username, follower rows, next_cursor
Post or reply POST /twitter/tweets/create Tweet ID, route, human approval

Use this framework when you already run Microsoft agent hosts. Use the Python SDK or C# SDK for deterministic jobs without a model.

Prerequisites

  • Python 3.10 or later, or a .NET 8+ host with MCP Streamable HTTP support
  • A TwexAPI API key
  • A model configured for the agent runtime

Public X reads need no X Developer credentials. Authenticate with TwexAPI.

Install

Python:

python -m pip install "agent-framework>=0.2" mcp python-dotenv pydantic
TWEXAPI_API_KEY=YOUR_API_KEY
OPENAI_API_KEY=sk-...

Connect TwexAPI MCP

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",
)

Equivalent host JSON:

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

Unauthenticated MCP requests return 401.

Full example (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())

Strip Markdown fences if the model wraps the JSON. Persist the file outside conversation state.

.NET host sketch

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

Use the same instruction: explore first, preserve cursors, stop before read_only: false. Typed REST calls belong in the C# SDK.

Preserve the MCP response contract

Reuse the same query and filters on every page. Treat each cursor as opaque.

Stop pagination when the requested total is met, has_more is false, next_cursor repeats, or the page cap is reached.

Keep a resumable agent handoff

Tweet pages

Store tweet_id, text, author_username, created_at, has_more, next_cursor, and the original query.

Profile rows

Store user_id, username, name, description, and follower counts.

Follower pages

Store source username, follower rows, next_cursor, and page index.

Write actions

Store route, preview text, and approval. Keep API keys out of the handoff file.

See Agent MCP Handoff.

Build error handling

Status Meaning Agent decision
400 Invalid route or parameters Fix the request before retrying
401 Missing or invalid API key Stop and replace the credential
403 Access denied or credits Pause writes; check Get Balance
429 Rate limit reached Back off, then resume the same cursor
5xx Temporary server failure Apply bounded backoff to safe reads

Never retry a write after a timeout without a read-back check. See Error Handling and Rate Limits.

Require approval before X actions

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.

Preview with the CLI --dry-run. Execute approved writes through REST or an SDK, not an unsupervised agent loop.

Production guidance

  • Use a per-environment API key. Do not embed keys in prompts.
  • Log MCP tool names and returned path values, not cookie headers.
  • Persist cursors and tweet IDs in your store, not only in ChatAgent memory.
  • Split read research and write execution into separate agents or jobs.

Package versions

Package Supported range
Python >=3.10
agent-framework >=0.2
mcp >=1.9
pydantic >=2.7

Next steps

Was this page helpful?