Give an OpenAI Agents SDK agent Instagram, TikTok and WhatsApp tools
An OpenAI Agents SDK agent gets Instagram, TikTok, WhatsApp and more channels as tools through MCPServerStreamableHttp pointed at https://easycoexistence.com/api/mcp, with the MCP Python SDK's OAuthClientProvider as its auth handler. A tool filter narrows the 35+ tools to the job, require_approval holds publishing until a person approves, and each call reaches the network through its official API.
What MCPServerStreamableHttp takes in params["auth"] with MCP Python SDK v2; with v1 it takes an httpx.Auth.
The mcp package range the Agents SDK depends on, covering both major versions of the MCP Python SDK.
Where a paused run lists the tool calls awaiting approval, which a RunState approves or rejects before Runner.run resumes.
How often the Responses API's MCP tool must be sent its OAuth token in authorization; OpenAI does not store the value.
Calls TikTok allows per authorized account on each Accounts API endpoint, comment replies included.
How does an Agents SDK agent connect to easyCoexistence?
Through MCPServerStreamableHttp, with the MCP Python SDK's OAuthClientProvider in params["auth"]. The Agents SDK passes that handler to the HTTP client it builds, so the provider discovers easyCoexistence's authorization server, registers your agent as a public client, runs one browser sign-in with PKCE and refreshes the hour-long access tokens with the refresh token. The example uses MCP Python SDK v2, where the handler has to be an httpx2.Auth, which the provider is. A storage object keeps the registration and the tokens between runs; the file below stands in for a secret store. create_static_tool_filter lists the tools the agent may see, and require_approval names the ones that wait for a person.
import json, webbrowser
from pathlib import Path
from urllib.parse import parse_qs, urlparse
from pydantic import AnyUrl
from mcp.client.auth import AuthorizationCodeResult, OAuthClientProvider
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
from agents.mcp import MCPServerStreamableHttp, create_static_tool_filter
URL = "https://easycoexistence.com/api/mcp"
SAVED = Path("easycoexistence-oauth.json") # a secret store in production
class SavedSignIn: # the MCP SDK's TokenStorage: registration and tokens survive restarts
def _read(self) -> dict:
return json.loads(SAVED.read_text()) if SAVED.exists() else {}
def _write(self, key: str, model) -> None:
data = self._read()
data[key] = model.model_dump(mode="json")
SAVED.write_text(json.dumps(data))
async def get_tokens(self):
t = self._read().get("tokens")
return OAuthToken(**t) if t else None
async def set_tokens(self, tokens): self._write("tokens", tokens)
async def get_client_info(self):
c = self._read().get("client")
return OAuthClientInformationFull(**c) if c else None
async def set_client_info(self, info): self._write("client", info)
async def open_sign_in(url: str) -> None:
webbrowser.open(url)
async def code_from_redirect() -> AuthorizationCodeResult:
q = parse_qs(urlparse(input("Address after sign-in: ")).query)
return AuthorizationCodeResult(code=q["code"][0], state=q["state"][0])
oauth = OAuthClientProvider(
server_url=URL,
client_metadata=OAuthClientMetadata(
client_name="Social desk agent", # shown on easyCoexistence's consent screen
redirect_uris=[AnyUrl("http://localhost:3030/callback")],
scope="mcp",
),
storage=SavedSignIn(),
redirect_handler=open_sign_in,
callback_handler=code_from_redirect,
)
PUBLISH = ["publish_instagram_post", "publish_tiktok_post", "publish_facebook_post"]
def easycoexistence() -> MCPServerStreamableHttp:
return MCPServerStreamableHttp(
name="easyCoexistence",
params={"url": URL, "auth": oauth, "timeout": 60},
client_session_timeout_seconds=60, # publishing waits on the network's API
cache_tools_list=True,
tool_filter=create_static_tool_filter(allowed_tool_names=[
"list_social_accounts", "list_social_posts", "list_social_comments",
"reply_to_comment", "list_scheduled_posts", *PUBLISH,
]),
require_approval={"always": {"tool_names": PUBLISH}},
)How do you keep publishing behind a person's approval?
With require_approval on the server, which pauses the run before a named tool executes. The run then comes back with interruptions instead of a final answer: turn the result into a RunState, approve or reject each pending call, and call Runner.run again with the same agent and the state. With always_approve left False, each yes covers one call, so the agent cannot reuse an approval for a second post. The server stays open across the pause because the loop runs inside its async with block. For a review that takes hours, the SDK can store the state as JSON and load it again later with RunState.from_json.
from agents import Agent, Runner
RULES = "You run Acme's social accounts. Schedule posts with scheduled_at; TikTok replies are public."
async def run(task: str) -> str:
async with easycoexistence() as server:
agent = Agent(name="Social desk", instructions=RULES, mcp_servers=[server])
result = await Runner.run(agent, task)
while result.interruptions: # a publish tool is waiting for a decision
state = result.to_state()
for item in result.interruptions:
if await ask_a_person(item): # your review screen, chat message or queue
state.approve(item, always_approve=False)
else:
state.reject(item)
result = await Runner.run(agent, state)
return result.final_outputHow does a TikTok comment or an Instagram DM start a run?
Through your own HTTPS route, since the agent only hears what it asks the MCP server for. set_social_webhook_destination points an account's comments, mentions and DMs at the route and returns a signing secret once; TikTok accounts forward comments. The route checks X-EC-Signature, an HMAC-SHA256 of the timestamp, a dot and the raw body, responds within easyCoexistence's 8 seconds and queues the event. A worker then calls Runner.run with the event as input. For DMs, a session keyed on the account and the sender keeps the conversation going; a TikTok comment needs only the comment and its video, so it can run without one.
What should the agent's instructions say about each network?
The rules each network's API applies to the account, written where the model reads them:
- TikTok:
reply_to_commentposts in public and needs the video's ID aspost_id;send_social_dmrefuses TikTok accounts. - TikTok volume: up to 40 calls a minute per account on the reply endpoint, and many near-identical replies in a short time can be hidden as spam.
- Instagram DMs: replies only to people who wrote in the last 24 hours, in at most 1,000 bytes of UTF-8 text.
- WhatsApp:
send_messagewithin 24 hours of the customer's last message, andsend_templatewith an approved template otherwise. - Timing:
scheduled_attakes ISO 8601 with a timezone, 1 minute to 90 days ahead, andlist_scheduled_postsshows the queue.
Can the agent use HostedMCPTool, or run with no sign-in?
Both, with trade-offs. HostedMCPTool hands the server to the Responses API, whose MCP tool takes an OAuth access token in authorization and needs it in each request, since OpenAI does not store it; an easyCoexistence access token lasts an hour, so your code refreshes one before each run. For a job with no one to sign in, skip MCP: function tools that call the Partner API with an ec_live_ key can queue posts through POST /api/v1/channels/:id/posts and fetch fresh TikTok, YouTube and LinkedIn tokens from GET /api/v1/channels/:id?credentials=1, while comment rules and automations reply on easyCoexistence with no agent running.
Common mistakes
- Keeping the 5-second client_session_timeout_seconds for publishing. A publish waits on the network's API, so a slow call can time out in the agent after easyCoexistence has passed the post on; allow a minute, and check list_scheduled_posts before trying again.
- Passing external_id as account_id. The tools take account_id, easyCoexistence's ID for the account; external_id is the account's own ID on Instagram, TikTok or Facebook.
- Approving interruptions in a loop with no person in it. require_approval only protects publishing when a human, or a rule you trust, decides on each pending call.
- Feeding the agent the account's own activity. Instagram returns the account's DMs as echoes with is_echo true and its public replies as new comments; filter both out before Runner.run.
easyCoexistence gives your OpenAI Agents SDK agents reach to customers on WhatsApp, Instagram, Facebook, TikTok, YouTube, LinkedIn and more channels, each through its official API: an MCP server that signs in with OAuth, signed events for comments and DMs, and a Partner API for jobs that run unattended, with every connection monitored 24/7. US$ 9 to US$ 0.75 per connection per month, falling as you add connections, with the first 3 days free.
easyCoexistence is a multichannel API and MCP server that connects AI agents such as Claude and ChatGPT to WhatsApp, Instagram, TikTok, Facebook and more. On WhatsApp it uses Coexistence: the business keeps using its number in the WhatsApp Business app while the AI works through Meta's official API.
Frequently asked questions
Does the agent need an API key from easyCoexistence?
Not for MCP. The OAuth sign-in issues the agent its own tokens; an ec_live_ key from the dashboard is only for code that calls the Partner API instead of the MCP server.
Can the same agent reply to WhatsApp messages?
Yes, with the number's tools: list_numbers for the connection_id, send_message inside 24 hours of the customer's last message and send_template outside it. The OpenAI Agents SDK guide for WhatsApp covers receiving the messages.
Which model does the agent use?
The one you give the Agent. The MCP tools work the same whatever model the SDK runs, the model's usage is billed by its provider, and easyCoexistence charges per connection.
How much does easyCoexistence cost for an OpenAI Agents SDK agent?
US$ 9 to US$ 0.75 per connection per month, falling as you add connections, the same on each network. The MCP server, the forwarded events and the Partner API come with it, and the first 3 days are free.
Keep reading
Connect your first channel in two minutes.
No platform reviews to wait for. Connect WhatsApp, Instagram, TikTok or another channel, then ask your AI to post, reply or report, and watch it work.
- 3 days free
- Cancel any time
- Official APIs only
- Monitored 24/7
Verified on