Skip to main content
Build a Pydantic AI Twitter API agent through Xquik’s MCP server. Search tweets, inspect profiles, export followers, and replay monitor events. Review every proposed post, reply, like, repost, follow, and direct message. Validate every durable handoff with a Pydantic model.

Why use Pydantic AI with a Twitter API?

Pydantic AI combines model tool calls with typed Python output. Xquik supplies the Twitter API routes through two MCP tools: explore and xquik. Use each strength at the correct boundary. Use one typed agent for tweet search, profile enrichment, or follower exports. Use another agent for monitor processing. Keep each agent focused.

Pydantic AI Twitter API prerequisites

  • Python 3.10 or later
  • An Xquik API key beginning with xq_
  • A Pydantic AI-supported model with tool calling
  • A connected X account for private reads or write actions
Public X reads do not require X Developer credentials. Authenticate with Xquik. Connect an X account only when the selected route requires it. This supplies a Twitter API for Python agents through one MCP connection. Send the x-api-key header. Do not send bearer tokens or access tokens.

Install Pydantic AI MCP support

Install the current stable Pydantic AI 2.x line. Keep FastMCP below 4 until Pydantic AI adds MCP SDK v2 support.
The explicit FastMCP range prevents an MCP SDK v2 prerelease from entering the environment. Remove that cap only after Pydantic AI adds FastMCP 4 support. This Pydantic AI MCP Streamable HTTP setup keeps execution inside Python. This Pydantic AI MCP server connection uses the Xquik endpoint. Keep the MCP URL HTTPS-only. It authenticates with the x-api-key header. After setup is complete, it can be run inside a local Python process. Store secrets outside source control.
.env
.gitignore
Define the final tweet-search handoff before creating the agent. Pydantic AI validates the model output against this schema. To import Agent from Pydantic AI, use from pydantic_ai import Agent. Use type hints for every durable handoff field. Start the async example with import asyncio. The typing import supplies Literal for finite stop reasons.
MCP is Pydantic AI’s primary MCP entry point. The connection runs locally unless you configure another execution mode. Headers, hooks, and traces remain inside your Python process. The URL selects Streamable HTTP. The allowed list contains only the public explore and xquik tools. Model Context Protocol (MCP) turns Xquik routes into model-callable tools. Pydantic builds JSON schemas from output_type. Use explicit keyword arguments for headers, allowed_tools, capabilities, and output_type. Pydantic AI opens and closes the connection automatically. Enter async with agent when several runs should share one connection. The agent discovers explore and xquik. Discover route requirements before selecting an unfamiliar endpoint. The Xquik sandbox invokes xquik.request(...) with validated route values. Xquik injects authentication separately.

Validate Twitter API fields before storage

MCP returns normalized snake_case fields. Date-time values use Unix seconds. Map REST createdAt to created, never created_at. Keep these source fields unchanged:
  • Tweet rows: id, text, author, created, and url
  • Profile rows: id, username, name, description, and followers
  • Page state: has_more and next_cursor
  • Error fields: error.type, error.code, and error.message
  • Write receipts: tweet_id, write_action_id, and charged_credits
Map source id to tweet_id or user_id only in your output model. Never cast large IDs to floating-point numbers. Search and list routes return has_more and next_cursor. Pass cursor for tweet, profile, follower, reply, timeline, community, and list pagination. Keep the original query and filters unchanged. Events, draws, and extraction pages use cursor. Radar pages use after. Draft pages use afterCursor. Treat every cursor as opaque. Continue through an empty page when has_more stays true. Stop when no cursor exists. Stop after the server repeats a cursor. Return cursor_stalled with the number of collected rows. MCP output has a 24,000-character limit. Project only required fields. Use extraction exports when the workflow must persist every complete row.

Build a typed Twitter agent handoff

Conversation text cannot safely resume a Python Twitter API job. Persist the validated fields required by the next worker.

Tweet search

Store the query, route, tweet IDs, authors, created, URLs, has_more, next_cursor, and stop reason.

Profile lookup

Store user_id, username, name, description, followers, verified, and profile_picture.

Follower export

Store the source user, extraction ID, status, poll URL, requested format, and export completion state.

Reply collection

Store the root tweet ID, reply IDs, parent IDs, cursor state, and coverage diagnostics. Keep nested replies separate.

Monitor replay

Store monitor_id, event_id, type, occurred_at, has_more, and next_cursor. Send the next cursor as cursor.

Webhook delivery

Store webhook_id, delivery_id, and stream_event_id. Keep the webhook secret in a secret manager.

Write receipt

Store tweet_id or write_action_id, status, charged_credits, poll, and the idempotency key.

Media attachment

Use public URLs in media for tweets. Reserve uploaded media_id values for direct messages.
Keep API keys, headers, webhook secrets, and raw signatures outside agent output. Never place private messages in shared traces.

Reuse the MCP connection safely

Wrap related calls in async with agent. One session fetches two tweet-search pages.
One local MCP session connects as one identity. Do not share one session across users with different Xquik keys. Give every credential its own request-scoped MCP capability.

Require approval before X actions

Read-only agents can search tweets automatically. Write-capable agents need a human decision before every X action. Review posts, replies, likes, reposts, follows, and direct messages. Xquik exposes all API calls through one aggregate xquik tool. Review and approve each validated Xquik tool invocation. Leave explore available without approval.
Inspect the sandbox code before approval. Confirm the route, method, account, target ID, text, media, and idempotency key. Reject unexpected arguments. The CLI displays every validated tool request. Replace it with your application’s review screen when needed. Do not use approve_all=True when the agent can write to X. Store the approval decision and tool call ID with the resulting action receipt.

Build Twitter API error handling

Treat error messages as typed error handling inputs. A 402 never authorizes a purchase. Show the available payment choices. Wait for explicit confirmation before any supported account checkout action. Never recreate a pending write after a timeout. Poll the returned action ID. Retry only safe reads when error.retryable permits it.

Defer and prefix MCP tools

Xquik exposes only two aggregate tools. Deferred loading is optional for one Xquik connection. Use it when several servers create a larger tool catalog.
Prefix tools when another server also exposes explore or xquik.
The resulting names become twitter_explore and twitter_xquik. Update any approval predicate after adding a prefix.

Choose Pydantic AI MCP or the REST API

MCP and REST solve different integration problems. MCP adds a discoverable tool layer over documented Twitter API routes. Xquik validates the sandbox route, method, query, and body. Pydantic validates the final typed handoff. Keep both layers. Each layer enforces a separate boundary.

Tested Pydantic AI compatibility

These versions were checked on August 3, 2026. Pydantic AI issue 6661 tracks FastMCP 4 and MCP SDK v2 support. Use the stable FastMCP 3.x line until that compatibility work ships.

Pydantic AI Twitter API questions

Does Pydantic AI support MCP?

Yes. Install the mcp extra and create an MCP capability. Xquik uses the recommended Streamable HTTP transport.

What is the difference between Pydantic AI tools and MCP?

Your Python application registers local Pydantic AI tools. MCP tools come from a connected server and can change independently. Xquik publishes explore and xquik through MCP.

Is Pydantic AI better than LangChain for a Twitter agent?

Choose Pydantic AI for typed Python handoffs. Choose LangChain and LangGraph for durable graph orchestration. Both can call the same Xquik MCP tools.

Can Pydantic AI call the Twitter API?

Yes. MCP exposes eligible routes for tweets, profiles, followers, monitors, extractions, and X actions. Authenticate with an Xquik API key.

Can Pydantic AI scrape tweets with Python?

Yes. Call GET /api/v1/x/tweets/search through the MCP tools. Preserve tweet IDs, authors, created, URLs, has_more, and next_cursor.

How do I validate Twitter API JSON with Pydantic?

Pass a BaseModel as the agent’s output_type. Call model_dump_json() before storing each validated output. Never print result.output into logs or files. Validate result.output before storage. Never save conversational text as JSON.

How can I use Pydantic with AI model validation effectively?

Model tweet IDs and cursors as strings. Mark a field optional only when its route omits that field. Use Literal for finite stop reasons. Prefer typed Pydantic models. Validate before storage, queues, exports, or handoff.

Why avoid a str return?

A structured result preserves tweet IDs, cursors, stop reasons, and errors. A plain string cannot prove field completeness or types.

How do I import agent from Pydantic AI?

Use from pydantic_ai import Agent. Import BaseModel from pydantic and Literal from typing. Keep these imports separate from application tools.

Does a Pydantic AI Twitter agent need X developer keys?

No. Use an Xquik API key. Some private reads and write actions also require a connected X account.

How do I post a tweet with Pydantic AI?

Use the matching X write route through xquik. Validate and approve each requested X write operation. Store the idempotency key and returned action ID.

How do I handle Twitter API rate limits in Python?

Read error.retry_after from a 429 response. Wait for that interval. Apply bounded backoff when retrying safe read requests.

How do I paginate tweet search in Pydantic AI?

Persist has_more and next_cursor in the output model. Reuse unchanged filters. Stop on completion, limits, or a stalled cursor.

Can a Pydantic AI agent export Twitter followers?

Yes. Create an extraction, persist its ID, and poll its status. Export only after completion. Save the source user and format together.

Can Pydantic AI monitor Twitter keywords?

Yes. Create a monitor and webhook. Persist both identifiers together. Replay missed events through GET /api/v1/events with cursor pagination. Monitor delivery is asynchronous and cannot guarantee real-time events.

Next steps

Xquik is an independent third-party service. Not affiliated with X Corp. “Twitter” and “X” are trademarks of X Corp.