为 CrewAI 团队添加 Instagram、TikTok 和 WhatsApp 工具
当 CrewAI 团队中每个智能体的 mcps 列表包含一个 MCPServerHTTP,其地址为 https://easycoexistence.com/api/mcp,且其 Authorization 请求头中带有 easyCoexistence 的 OAuth 访问令牌时,该团队即可将 Instagram、TikTok、WhatsApp 及更多渠道作为工具使用。CrewAI 的 MCP 客户端只发送请求头,不运行登录流程,因此团队需要在每次 kickoff 时刷新令牌。自定义工具则可改用密钥调用 posts API。
MCPServerHTTP 的可选 HTTP 请求头字典,CrewAI 文档中用它携带 Authorization Bearer 令牌。
CrewAI 的允许列表与阻止列表,用于筛选 MCP 服务器的工具,从 crewai.mcp.filters 导入。
CrewAI 等待 MCP 连接的默认时长;若无法连接服务器,将记录警告,智能体仍可使用其他工具。
easyCoexistence MCP 访问令牌的有效期;刷新令牌有效期为 60 天,可换取一组新令牌。
easyCoexistence posts API 可从 1 分钟起提前排期,入队时复制媒体。
CrewAI 智能体如何加载 easyCoexistence 工具?
通过 mcps 字段加载,每个智能体配置一个 MCPServerHTTP。它通过 Streamable HTTP 连接,这是 CrewAI 对该类的默认设置,并发送你设置的请求头,此处即包含 easyCoexistence 访问令牌的 Authorization 请求头。使用 create_static_tool_filter 创建的静态工具过滤器,可让每个智能体只获得其任务所需的工具;cache_tools_list 则在首次连接后保留工具列表。CrewAI 按需连接,若服务器无法访问,会记录警告并让智能体继续使用其他工具,因此首次运行时请查看日志。访问令牌来自下一节的辅助函数。
from crewai import Agent, Crew, Task
from crewai.mcp import MCPServerHTTP
from crewai.mcp.filters import create_static_tool_filter
from easycoexistence_token import fresh_token
TOKEN = fresh_token() # one per kickoff: an access token lasts an hour
def easycoexistence(*tools: str) -> MCPServerHTTP:
return MCPServerHTTP(
url="https://easycoexistence.com/api/mcp",
headers={"Authorization": f"Bearer {TOKEN}"},
streamable=True,
cache_tools_list=True,
tool_filter=create_static_tool_filter(allowed_tool_names=list(tools)),
)
analyst = Agent(
role="Social analyst",
goal="Find which of last week's Instagram and TikTok posts reached the most people",
backstory="You read the numbers before anyone writes a caption.",
mcps=[easycoexistence("list_social_accounts", "list_social_posts", "get_social_insights")],
)
scheduler = Agent(
role="Scheduler",
goal="Queue next week's posts at the times the analyst recommends",
backstory="You post only what the brief approves, always with scheduled_at.",
mcps=[easycoexistence("list_social_accounts", "publish_instagram_post",
"publish_tiktok_post", "list_scheduled_posts")],
)
crew = Crew(
agents=[analyst, scheduler],
tasks=[
Task(description="Rank last week's posts by reach and views.",
expected_output="A ranked list with the best posting times", agent=analyst),
Task(description="Schedule the three posts in {brief} for next week.",
expected_output="The post_id of each queued post", agent=scheduler),
],
)
crew.kickoff(inputs={"brief": "<THE WEEK'S BRIEF>"})团队的访问令牌从哪里获取?
首次通过浏览器登录获取,之后在每次 kickoff 时刷新。easyCoexistence 的 MCP 服务器只接受 OAuth 令牌:支持动态客户端注册、带 PKCE 的授权码流程,访问令牌有效期为一小时,刷新令牌有效期为 60 天。请在有浏览器的机器上运行一次 MCP Python SDK 的 OAuthClientProvider,并保存其返回的注册信息与令牌;下方辅助函数使用 SDK 的 1.x 版本,CrewAI 会安装该版本。每次 kickoff 前,fresh_token 会在 easyCoexistence 的令牌端点用已保存的刷新令牌换取一组新令牌,并将其保存,因此每 60 天内至少运行一次的团队便无需再次打开浏览器。请将保存的文件存放在密钥存储中,不要放入代码仓库。
import asyncio, json, webbrowser
from pathlib import Path
from urllib.parse import parse_qs, urlparse
import httpx
import requests
from pydantic import AnyUrl
from mcp import ClientSession
from mcp.client.auth import OAuthClientProvider
from mcp.client.streamable_http import streamable_http_client
from mcp.shared.auth import OAuthClientMetadata
URL = "https://easycoexistence.com/api/mcp"
SAVED = Path("easycoexistence-oauth.json") # a secret store in production
class SaveToFile: # the MCP SDK's TokenStorage, writing what the sign-in returns
def __init__(self):
self.saved = {}
async def get_tokens(self): return None
async def get_client_info(self): return None
async def set_tokens(self, tokens): self._put("tokens", tokens)
async def set_client_info(self, info): self._put("client", info)
def _put(self, key, model):
self.saved[key] = model.model_dump(mode="json")
SAVED.write_text(json.dumps(self.saved))
async def open_browser(url: str) -> None:
webbrowser.open(url)
async def code_from_redirect() -> tuple[str, str | None]:
q = parse_qs(urlparse(input("Address after sign-in: ")).query)
return q["code"][0], q.get("state", [None])[0]
async def sign_in_once() -> None:
oauth = OAuthClientProvider(
server_url=URL,
client_metadata=OAuthClientMetadata(
client_name="Acme crew", redirect_uris=[AnyUrl("http://localhost:3030/callback")], scope="mcp"),
storage=SaveToFile(), redirect_handler=open_browser, callback_handler=code_from_redirect,
)
async with httpx.AsyncClient(auth=oauth) as http:
async with streamable_http_client(URL, http_client=http) as (read, write, _):
async with ClientSession(read, write) as session:
await session.initialize() # completes the sign-in and saves the tokens
def fresh_token() -> str:
"""Trade the saved refresh token for a new pair and return the access token."""
saved = json.loads(SAVED.read_text())
r = requests.post("https://easycoexistence.com/api/oauth/token", data={
"grant_type": "refresh_token",
"refresh_token": saved["tokens"]["refresh_token"],
"client_id": saved["client"]["client_id"],
}, timeout=30)
r.raise_for_status()
saved["tokens"] = r.json() # a new refresh token comes with each refresh
SAVED.write_text(json.dumps(saved))
return saved["tokens"]["access_token"]
if __name__ == "__main__":
asyncio.run(sign_in_once())团队如何在没有 MCP 服务器的情况下发布内容?
使用调用 easyCoexistence posts API 的自定义工具,适合由调度器启动、无人值守的团队。请在控制台中创建 Partner API 密钥,其以 ec_live_ 开头。下面的工具会发送 POST /api/v1/channels/:id/posts,请求体包含文本、媒体链接和类型以及 publish_at。排入队列时,easyCoexistence 会复制媒体;若此时链接返回的是网页或格式不符,则拒绝该链接,并在约定时间发布帖子。Idempotency-Key 请求头可防止重试的调用把帖子排队两次。同一密钥还可通过 GET /api/v1/channels/:id?credentials=1 读取最新的网络令牌。
import hashlib, os
import requests
from crewai.tools import tool
@tool("Schedule a social post")
def schedule_post(account_id: str, text: str, media_url: str, media_type: str, publish_at: str) -> str:
"""Queue one post on a connected Instagram, TikTok or Facebook account.
media_type is image or video; publish_at is ISO 8601 with a timezone, 1 minute to 90 days ahead."""
key = hashlib.sha256(f"{account_id}|{publish_at}|{media_url}".encode()).hexdigest()
r = requests.post(
f"https://easycoexistence.com/api/v1/channels/{account_id}/posts",
headers={"Authorization": f"Bearer {os.environ['EC_API_KEY']}", "Idempotency-Key": key},
json={"text": text, "media": [{"url": media_url, "type": media_type}], "publish_at": publish_at},
timeout=60,
)
return r.text # the queued post, or why it was refused团队中哪个智能体应持有哪些工具?
在能完成任务的前提下,工具越少越好,因为智能体可以调用其持有的任何工具。一个负责规划并发布一周内容的团队,应将读取、写作与发布分给不同的智能体,只让其中一个能将内容正式上线。写作智能体完全不分配 easyCoexistence 工具:它基于分析师的发现和简报工作,其文案作为任务输出交给调度器。发布工具接受 scheduled_at,因此调度器会将帖子排入对应时间,而不是在运行时立即发布;list_scheduled_posts 则可用来确认等待发布的内容。LinkedIn 帖子不纳入团队工作流:智能体可应要求起草(例如在 Claude 或 ChatGPT 中),发布前须由人工审核。
各网络对团队的帖子和回复有哪些要求?
以下是各网络 API 的规则,应写入智能体的目标与背景设定中:
- 媒体:每个文件需提供公开的 HTTPS 链接。Instagram 接受 JPEG 图片,TikTok 图文帖接受 JPEG 或 WebP,Facebook 主页帖子只能包含一张照片或一段视频。
- 时间:使用带时区的 ISO 8601 格式,例如 2026-11-20T09:00:00-03:00,可提前 1 分钟至 90 天排期。
- 评论:TikTok 回复是公开的,需要以视频 ID 作为
post_id;Instagram 或 Facebook 评论可在 7 天内获得一次私人回复。 - 私信:Instagram 和 Messenger 只能在用户最后一条消息的 24 小时内回复;WhatsApp 的
send_message遵循同样的时间窗口,send_template则可发给其他任何人。 - 事件:评论或私信仅能通过你自行设置的路由送达团队,该路由需用
set_social_webhook_destination设置,并可在收到事件时调用 crew.kickoff。
常见错误
- 使用昨天的令牌启动团队。easyCoexistence 访问令牌在签发一小时后即失效,而 CrewAI 在无法连接服务器时会继续运行,只在日志中留下警告;请在每次 kickoff 时调用 fresh_token。
- 为每个智能体分配整个服务器。若未设置 tool_filter,分析师也能看到发布工具;请传入 create_static_tool_filter,并列出其任务所需的工具名称。
- publish_at 或 scheduled_at 没有带偏移量。easyCoexistence 会拒绝没有时区的时间,因此请以 Z 结尾,或使用 -03:00 之类的偏移量。
- 将保存的登录文件提交到代码库。其刷新令牌会让持有者在最长 60 天内使用该账户的工具,因此请将其存放在密钥存储中。
easyCoexistence 让你的 CrewAI 智能体通过 WhatsApp、Instagram、Facebook、TikTok、YouTube、LinkedIn 及更多渠道触达客户,每个渠道均通过其官方 API 接入:为每个智能体的 mcps 列表提供 35 多个 MCP 工具;提供最多可提前 90 天排期的 posts API;并提供带签名的评论与私信事件,所有连接均经 24/7 全天候监控。每个连接每月 US$ 9 起,连接越多越便宜,最低降至 US$ 0.75,前 3 天免费试用。
常见问题
CrewAI 的 MCP 客户端会自行运行 OAuth 登录吗?
其文档中展示的是请求头、环境变量和查询参数等认证方式,没有 OAuth 流程。因此团队需发送已持有的 Bearer 令牌,而这一令牌由使用 MCP Python SDK 完成的一次登录提供。
团队能否按自己的时间表回复评论?
可以。社区管理智能体配备 list_social_posts、list_social_comments 和 reply_to_comment 后,每次运行都可以处理新评论。YouTube 和 LinkedIn 评论也通过这种方式读取,因为这两个平台都不转发事件。
团队能否发送 WhatsApp 消息?
可以,在智能体的工具过滤器中加入 list_numbers、send_message 和 send_template 即可。send_message 用于回复 24 小时内给你发过消息的客户,send_template 则可向其他任何人发送已获批准的模板。
easyCoexistence 对 CrewAI 团队收费多少?
每个连接每月 US$ 9 起,连接越多越便宜,最低降至 US$ 0.75,且各网络收费相同。MCP 服务器、posts API 和转发事件均包含在内,前 3 天免费试用。
继续阅读
两分钟连接您的第一个渠道。
无需等待平台审核。连接 WhatsApp、Instagram、TikTok 或其他渠道,然后让您的 AI 发布、回复或生成报告,看它如何运作。
- 免费试用 3 天
- 随时取消
- 仅使用官方 API
- 全天候 24/7 监控
验证时间