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
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.x-api-key header.
After setup is complete, it can be run inside a local Python process.
Store secrets outside source control.
.env
.gitignore
Build a Pydantic AI MCP example for tweet search
Define the final tweet-search handoff before creating the agent. Pydantic AI validates the model output against this schema. To importAgent 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 RESTcreatedAt to created, never created_at.
Keep these source fields unchanged:
- Tweet rows:
id,text,author,created, andurl - Profile rows:
id,username,name,description, andfollowers - Page state:
has_moreandnext_cursor - Error fields:
error.type,error.code, anderror.message - Write receipts:
tweet_id,write_action_id, andcharged_credits
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.Reuse the MCP connection safely
Wrap related calls inasync with agent. One session fetches two tweet-search
pages.
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 aggregatexquik tool. Review and
approve each validated Xquik tool invocation. Leave explore available without
approval.
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.explore or xquik.
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 themcp 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 publishesexplore 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. CallGET /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 aBaseModel 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. UseLiteral 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?
Usefrom 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 throughxquik.
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?
Readerror.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?
Persisthas_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 throughGET /api/v1/events with cursor pagination. Monitor
delivery is asynchronous and cannot guarantee real-time events.
Next steps
- Read the official Pydantic AI MCP client guide.
- Review the MCP tool contract.
- Follow the agent handoff checklist.
- Build a tweet search workflow.
- Add monitor and webhook delivery.
- Compare Twitter API alternatives.