mirror of
https://github.com/Dasemu/meta-social-mcp.git
synced 2026-11-27 15:56:55 +00:00
Add SocialMCP: HTTP MCP server for Meta Graph API
Publishes to Facebook Pages and Instagram professional accounts, reads own post/media history, and lists/reads/replies to comments, using the official Meta Graph API over a stateless streamable-HTTP MCP transport. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
commit
0ea3841512
10 files changed
+2182
No files matched your search
@@ -0,0 +1,23 @@
|
|||||||
|
# Copia este archivo a .env y rellena los valores
|
||||||
|
|
||||||
|
# Token de acceso (largo, 60 dias) del usuario admin de la pagina/cuenta IG
|
||||||
|
META_ACCESS_TOKEN=
|
||||||
|
|
||||||
|
# App ID y App Secret de tu app en developers.facebook.com
|
||||||
|
META_APP_ID=
|
||||||
|
META_APP_SECRET=
|
||||||
|
|
||||||
|
# Se obtienen con: npm run get-ids
|
||||||
|
META_PAGE_ID=
|
||||||
|
META_IG_BUSINESS_ID=
|
||||||
|
|
||||||
|
# Version de la Graph API a usar
|
||||||
|
META_GRAPH_VERSION=v21.0
|
||||||
|
|
||||||
|
# Puerto e interfaz donde escucha el servidor HTTP del MCP
|
||||||
|
PORT=3300
|
||||||
|
HOST=127.0.0.1
|
||||||
|
|
||||||
|
# Token opcional para proteger el endpoint /mcp (header: Authorization: Bearer <valor>)
|
||||||
|
# Dejalo vacio para desactivar la comprobacion (solo recomendable en local/dev)
|
||||||
|
MCP_AUTH_TOKEN=
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
node_modules/
|
||||||
|
.env
|
||||||
|
data/
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# SocialMCP
|
||||||
|
|
||||||
|
Servidor MCP **HTTP** para publicar y gestionar contenido propio en Facebook Pages e Instagram
|
||||||
|
(cuentas profesionales) usando la Graph API oficial de Meta.
|
||||||
|
|
||||||
|
Publica y responde en **tu propia página/cuenta**. No envía mensajes ni interactúa con cuentas de
|
||||||
|
terceros — eso lo prohíben las políticas de Meta y este servidor no lo hace.
|
||||||
|
|
||||||
|
## 1. Requisitos previos en Meta
|
||||||
|
|
||||||
|
- Una **Página de Facebook** de la que seas admin.
|
||||||
|
- Una **cuenta de Instagram profesional** (Business o Creator) **vinculada a esa página**.
|
||||||
|
- Una app en [developers.facebook.com/apps](https://developers.facebook.com/apps), tipo "Business", con los productos:
|
||||||
|
- **Facebook Login for Business**
|
||||||
|
- **Instagram Graph API**
|
||||||
|
|
||||||
|
## 2. Obtener el token de acceso
|
||||||
|
|
||||||
|
1. En el panel de tu app, ve a **Graph API Explorer**.
|
||||||
|
2. Selecciona tu app y en "Permisos" añade los que necesites (ver tabla de la sección 6).
|
||||||
|
3. Genera el token de acceso (será uno "corto", de ~1 hora).
|
||||||
|
4. Copia ese token, tu **App ID** y **App Secret** (Configuración > Básica de la app) a tu `.env`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
# rellena META_ACCESS_TOKEN (el corto), META_APP_ID, META_APP_SECRET
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Instala dependencias y convierte el token en uno de larga duración (60 días):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run extend-token
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Copia el token resultante a `META_ACCESS_TOKEN` en tu `.env` (sobrescribe el corto).
|
||||||
|
|
||||||
|
## 3. Obtener Page ID e Instagram Business ID
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run get-ids
|
||||||
|
```
|
||||||
|
|
||||||
|
Copia los IDs correctos a `META_PAGE_ID` y `META_IG_BUSINESS_ID` en el `.env`.
|
||||||
|
|
||||||
|
## 4. Arrancar el servidor
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
Por defecto escucha en `http://127.0.0.1:3300/mcp` (configurable con `PORT`/`HOST` en `.env`).
|
||||||
|
El servidor es **stateless** (sin sesión persistente): cada petición JSON-RPC se atiende de forma
|
||||||
|
independiente, tal como recomienda el SDK para streamable HTTP sin estado.
|
||||||
|
|
||||||
|
Si defines `MCP_AUTH_TOKEN` en `.env`, todas las peticiones deberán incluir la cabecera
|
||||||
|
`Authorization: Bearer <ese valor>`.
|
||||||
|
|
||||||
|
## 5. Conectar el MCP a un cliente
|
||||||
|
|
||||||
|
Como es un servidor HTTP, se añade por URL en vez de por comando. Ejemplo (Claude Code):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
claude mcp add --transport http socialmcp http://127.0.0.1:3300/mcp
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. Herramientas disponibles
|
||||||
|
|
||||||
|
| Herramienta | Qué hace | Endpoint(s) Graph API | Permisos necesarios |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `publish_post` | Publica ya en Facebook y/o Instagram (texto, imagen, video o enlace). Instagram exige `imageUrl` o `videoUrl`. | `POST /{page-id}/feed`, `/photos`, `/videos` · `POST /{ig-id}/media` + `/media_publish` | `pages_manage_posts`, `pages_show_list`, `instagram_basic`, `instagram_content_publish` |
|
||||||
|
| `list_posts` | Lee el histórico de publicaciones propias (FB o IG). | `GET /{page-id}/posts` · `GET /{ig-id}/media` | `pages_read_engagement`, `pages_show_list`, `instagram_basic` |
|
||||||
|
| `list_comments` | Lista comentarios de un post/media propio, o respuestas de un comentario. | `GET /{object-id}/comments` | `pages_read_engagement`, `pages_manage_engagement` (FB) · `instagram_basic`, `instagram_manage_comments` (IG) |
|
||||||
|
| `get_comment` | Lee el detalle de un comentario por ID. | `GET /{comment-id}` | igual que `list_comments` |
|
||||||
|
| `reply_comment` | Responde a un comentario propio. | `POST /{comment-id}/comments` (FB) · `POST /{comment-id}/replies` (IG) | `pages_manage_engagement` (FB) · `instagram_basic`, `instagram_manage_comments` (IG) |
|
||||||
|
|
||||||
|
Todos los permisos anteriores requieren, además, `business_management` si la app opera sobre
|
||||||
|
activos gestionados desde Business Manager, y que la app haya pasado **App Review** de Meta para
|
||||||
|
usarlos fuera del modo de desarrollo/testers.
|
||||||
|
|
||||||
|
## 7. Limitaciones importantes
|
||||||
|
|
||||||
|
- **Instagram no admite publicaciones de solo texto**: siempre necesita `imageUrl` o `videoUrl`
|
||||||
|
accesible por una **URL pública** (no vale una ruta local ni una URL que requiera login).
|
||||||
|
- Los videos/reels de Instagram necesitan tiempo de procesamiento: `publish_post` espera
|
||||||
|
automáticamente (hasta 60s) a que el contenedor esté listo antes de publicar.
|
||||||
|
- Instagram no tiene programación nativa de publicaciones ni este servidor la implementa;
|
||||||
|
`publish_post` publica siempre de inmediato.
|
||||||
|
|
||||||
|
## 8. Notas de cumplimiento
|
||||||
|
|
||||||
|
Este servidor solo publica y responde en las páginas/cuentas que tú administras. No automatiza
|
||||||
|
mensajes directos, comentarios en cuentas ajenas, solicitudes de amistad/seguimiento, ni scraping —
|
||||||
|
ese tipo de automatización viola las políticas de Meta y queda fuera del alcance de esta herramienta.
|
||||||
Generated
+1599
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"name": "socialmcp",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "MCP HTTP server para publicar y gestionar Facebook Pages e Instagram (cuentas profesionales) via Graph API oficial de Meta",
|
||||||
|
"type": "module",
|
||||||
|
"main": "src/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node src/index.js",
|
||||||
|
"get-ids": "node src/get-ids.js",
|
||||||
|
"extend-token": "node src/extend-token.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
||||||
|
"dotenv": "^16.4.5",
|
||||||
|
"express": "^4.21.2",
|
||||||
|
"zod": "^3.24.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import "dotenv/config";
|
||||||
|
import { exchangeForLongLivedToken } from "./graph.js";
|
||||||
|
|
||||||
|
const { META_APP_ID, META_APP_SECRET, META_ACCESS_TOKEN } = process.env;
|
||||||
|
|
||||||
|
if (!META_APP_ID || !META_APP_SECRET || !META_ACCESS_TOKEN) {
|
||||||
|
console.error(
|
||||||
|
"Necesitas META_APP_ID, META_APP_SECRET y META_ACCESS_TOKEN (el token corto) en tu .env"
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await exchangeForLongLivedToken({
|
||||||
|
appId: META_APP_ID,
|
||||||
|
appSecret: META_APP_SECRET,
|
||||||
|
shortToken: META_ACCESS_TOKEN,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log("\nToken de larga duracion (dura ~60 dias):\n");
|
||||||
|
console.log(result.access_token);
|
||||||
|
console.log("\nSustituye META_ACCESS_TOKEN en tu .env por este valor.");
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import "dotenv/config";
|
||||||
|
import { getPageAndIgIds } from "./graph.js";
|
||||||
|
|
||||||
|
const token = process.env.META_ACCESS_TOKEN;
|
||||||
|
if (!token) {
|
||||||
|
console.error("Pon META_ACCESS_TOKEN en tu .env antes de ejecutar esto.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await getPageAndIgIds(token);
|
||||||
|
console.log("\nPaginas encontradas y sus cuentas de Instagram vinculadas:\n");
|
||||||
|
for (const r of results) {
|
||||||
|
console.log(`- Pagina: ${r.pageName}`);
|
||||||
|
console.log(` META_PAGE_ID=${r.pageId}`);
|
||||||
|
console.log(` META_IG_BUSINESS_ID=${r.igBusinessId || "(sin cuenta IG vinculada)"}\n`);
|
||||||
|
}
|
||||||
|
console.log("Copia los valores que correspondan a tu pagina en el archivo .env");
|
||||||
+171
@@ -0,0 +1,171 @@
|
|||||||
|
const BASE = "https://graph.facebook.com";
|
||||||
|
|
||||||
|
function ver() {
|
||||||
|
return process.env.META_GRAPH_VERSION || "v21.0";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function graphRequest(path, { method = "GET", params = {} } = {}) {
|
||||||
|
const token = process.env.META_ACCESS_TOKEN;
|
||||||
|
if (!token) throw new Error("Falta META_ACCESS_TOKEN en el entorno (.env)");
|
||||||
|
|
||||||
|
const url = new URL(`${BASE}/${ver()}/${path}`);
|
||||||
|
const qs = { ...params, access_token: token };
|
||||||
|
Object.entries(qs).forEach(([k, v]) => {
|
||||||
|
if (v !== undefined && v !== null) url.searchParams.set(k, v);
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await fetch(url.toString(), { method });
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok || data.error) {
|
||||||
|
const msg = data?.error?.message || res.statusText;
|
||||||
|
const code = data?.error?.code;
|
||||||
|
throw new Error(`Graph API error (${path})${code ? ` [${code}]` : ""}: ${msg}`);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Publicacion: Facebook Page ----------
|
||||||
|
|
||||||
|
export async function publishFacebookPost({ pageId, message, imageUrl, videoUrl, linkUrl }) {
|
||||||
|
if (videoUrl) {
|
||||||
|
return graphRequest(`${pageId}/videos`, {
|
||||||
|
method: "POST",
|
||||||
|
params: { file_url: videoUrl, description: message },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (imageUrl) {
|
||||||
|
return graphRequest(`${pageId}/photos`, {
|
||||||
|
method: "POST",
|
||||||
|
params: { url: imageUrl, caption: message },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return graphRequest(`${pageId}/feed`, {
|
||||||
|
method: "POST",
|
||||||
|
params: { message, link: linkUrl },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Publicacion: Instagram (cuenta profesional) ----------
|
||||||
|
|
||||||
|
export async function publishInstagramPost({ igBusinessId, imageUrl, videoUrl, caption }) {
|
||||||
|
if (!imageUrl && !videoUrl) {
|
||||||
|
throw new Error("Instagram requiere imageUrl o videoUrl (contenido accesible por URL publica)");
|
||||||
|
}
|
||||||
|
const mediaParams = videoUrl
|
||||||
|
? { video_url: videoUrl, media_type: "REELS", caption: caption || "" }
|
||||||
|
: { image_url: imageUrl, caption: caption || "" };
|
||||||
|
|
||||||
|
// 1. Crear contenedor de media
|
||||||
|
const container = await graphRequest(`${igBusinessId}/media`, {
|
||||||
|
method: "POST",
|
||||||
|
params: mediaParams,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Los videos/reels necesitan tiempo de procesamiento antes de publicarse
|
||||||
|
if (videoUrl) {
|
||||||
|
await waitUntilContainerReady(container.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Publicar el contenedor
|
||||||
|
return graphRequest(`${igBusinessId}/media_publish`, {
|
||||||
|
method: "POST",
|
||||||
|
params: { creation_id: container.id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitUntilContainerReady(containerId, { timeoutMs = 60000, intervalMs = 3000 } = {}) {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
const status = await graphRequest(containerId, { params: { fields: "status_code" } });
|
||||||
|
if (status.status_code === "FINISHED") return;
|
||||||
|
if (status.status_code === "ERROR") {
|
||||||
|
throw new Error(`El contenedor de Instagram fallo al procesarse (${containerId})`);
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, intervalMs));
|
||||||
|
}
|
||||||
|
throw new Error(`Timeout esperando a que Instagram procese el contenedor (${containerId})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Lectura de historico propio ----------
|
||||||
|
|
||||||
|
const FB_POST_FIELDS =
|
||||||
|
"id,message,created_time,permalink_url,full_picture,attachments{media_type,url,media},status_type";
|
||||||
|
|
||||||
|
const IG_MEDIA_FIELDS =
|
||||||
|
"id,caption,media_type,media_url,permalink,timestamp,like_count,comments_count";
|
||||||
|
|
||||||
|
export async function listFacebookPosts({ pageId, limit = 10, after }) {
|
||||||
|
return graphRequest(`${pageId}/posts`, {
|
||||||
|
params: { fields: FB_POST_FIELDS, limit, after },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listInstagramMedia({ igBusinessId, limit = 10, after }) {
|
||||||
|
return graphRequest(`${igBusinessId}/media`, {
|
||||||
|
params: { fields: IG_MEDIA_FIELDS, limit, after },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Comentarios ----------
|
||||||
|
|
||||||
|
const COMMENT_FIELDS = "id,message,from,created_time,like_count,comment_count";
|
||||||
|
|
||||||
|
export async function listComments({ objectId, limit = 25, after }) {
|
||||||
|
return graphRequest(`${objectId}/comments`, {
|
||||||
|
params: { fields: COMMENT_FIELDS, limit, after },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getComment({ commentId }) {
|
||||||
|
return graphRequest(commentId, { params: { fields: COMMENT_FIELDS } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// FB: una respuesta es un comentario anidado, se crea igual que un comentario normal
|
||||||
|
// sobre el comment-id padre (edge /comments).
|
||||||
|
export async function replyFacebookComment({ commentId, message }) {
|
||||||
|
return graphRequest(`${commentId}/comments`, {
|
||||||
|
method: "POST",
|
||||||
|
params: { message },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// IG: las respuestas usan un edge dedicado /replies sobre el ig-comment-id.
|
||||||
|
export async function replyInstagramComment({ commentId, message }) {
|
||||||
|
return graphRequest(`${commentId}/replies`, {
|
||||||
|
method: "POST",
|
||||||
|
params: { message },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Utilidades de configuracion ----------
|
||||||
|
|
||||||
|
export async function getPageAndIgIds(userToken) {
|
||||||
|
const accounts = await graphRequest("me/accounts", {
|
||||||
|
params: { access_token: userToken },
|
||||||
|
});
|
||||||
|
const results = [];
|
||||||
|
for (const page of accounts.data || []) {
|
||||||
|
let igId = null;
|
||||||
|
try {
|
||||||
|
const ig = await graphRequest(page.id, {
|
||||||
|
params: { fields: "instagram_business_account", access_token: userToken },
|
||||||
|
});
|
||||||
|
igId = ig.instagram_business_account?.id || null;
|
||||||
|
} catch {
|
||||||
|
igId = null;
|
||||||
|
}
|
||||||
|
results.push({ pageId: page.id, pageName: page.name, igBusinessId: igId });
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exchangeForLongLivedToken({ appId, appSecret, shortToken }) {
|
||||||
|
return graphRequest("oauth/access_token", {
|
||||||
|
params: {
|
||||||
|
grant_type: "fb_exchange_token",
|
||||||
|
client_id: appId,
|
||||||
|
client_secret: appSecret,
|
||||||
|
fb_exchange_token: shortToken,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import "dotenv/config";
|
||||||
|
import express from "express";
|
||||||
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||||
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||||
|
import { registerTools } from "./tools.js";
|
||||||
|
|
||||||
|
function buildServer() {
|
||||||
|
const server = new McpServer({ name: "socialmcp", version: "1.0.0" });
|
||||||
|
registerTools(server);
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
const requiredToken = process.env.MCP_AUTH_TOKEN;
|
||||||
|
if (!requiredToken) return next();
|
||||||
|
const header = req.get("authorization") || "";
|
||||||
|
const provided = header.startsWith("Bearer ") ? header.slice(7) : null;
|
||||||
|
if (provided !== requiredToken) {
|
||||||
|
return res.status(401).json({ error: "unauthorized" });
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Servidor stateless: cada peticion crea su propia instancia de McpServer/transport
|
||||||
|
// (patron recomendado por el SDK para streamable HTTP sin sesion).
|
||||||
|
app.post("/mcp", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const server = buildServer();
|
||||||
|
const transport = new StreamableHTTPServerTransport({
|
||||||
|
sessionIdGenerator: undefined,
|
||||||
|
});
|
||||||
|
res.on("close", () => {
|
||||||
|
transport.close();
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
await server.connect(transport);
|
||||||
|
await transport.handleRequest(req, res, req.body);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error manejando peticion MCP:", err);
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.status(500).json({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
error: { code: -32603, message: "Internal server error" },
|
||||||
|
id: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get("/mcp", (req, res) => {
|
||||||
|
res.status(405).json({ error: "Method not allowed. Este servidor es stateless (solo POST /mcp)." });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete("/mcp", (req, res) => {
|
||||||
|
res.status(405).json({ error: "Method not allowed. Este servidor es stateless (solo POST /mcp)." });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get("/health", (req, res) => res.json({ ok: true }));
|
||||||
|
|
||||||
|
const port = Number(process.env.PORT) || 3300;
|
||||||
|
const host = process.env.HOST || "127.0.0.1";
|
||||||
|
|
||||||
|
app.listen(port, host, () => {
|
||||||
|
console.log(`SocialMCP escuchando en http://${host}:${port}/mcp`);
|
||||||
|
});
|
||||||
+168
@@ -0,0 +1,168 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
publishFacebookPost,
|
||||||
|
publishInstagramPost,
|
||||||
|
listFacebookPosts,
|
||||||
|
listInstagramMedia,
|
||||||
|
listComments,
|
||||||
|
getComment,
|
||||||
|
replyFacebookComment,
|
||||||
|
replyInstagramComment,
|
||||||
|
} from "./graph.js";
|
||||||
|
|
||||||
|
function text(payload) {
|
||||||
|
return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorText(err) {
|
||||||
|
return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function requirePageId() {
|
||||||
|
const pageId = process.env.META_PAGE_ID;
|
||||||
|
if (!pageId) throw new Error("Falta META_PAGE_ID en el entorno (.env)");
|
||||||
|
return pageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireIgId() {
|
||||||
|
const igId = process.env.META_IG_BUSINESS_ID;
|
||||||
|
if (!igId) throw new Error("Falta META_IG_BUSINESS_ID en el entorno (.env)");
|
||||||
|
return igId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerTools(server) {
|
||||||
|
server.registerTool(
|
||||||
|
"publish_post",
|
||||||
|
{
|
||||||
|
title: "Publicar en Facebook/Instagram",
|
||||||
|
description:
|
||||||
|
"Publica contenido propio en la Facebook Page y/o cuenta profesional de Instagram configuradas. " +
|
||||||
|
"Instagram exige imageUrl o videoUrl (no admite publicaciones de solo texto).",
|
||||||
|
inputSchema: {
|
||||||
|
platform: z.enum(["facebook", "instagram", "both"]),
|
||||||
|
message: z.string().describe("Texto del post o caption"),
|
||||||
|
imageUrl: z.string().url().optional().describe("URL publica de una imagen"),
|
||||||
|
videoUrl: z.string().url().optional().describe("URL publica de un video (IG lo publica como Reel)"),
|
||||||
|
linkUrl: z.string().url().optional().describe("Solo Facebook: enlace a incluir en un post de texto"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async ({ platform, message, imageUrl, videoUrl, linkUrl }) => {
|
||||||
|
try {
|
||||||
|
const results = {};
|
||||||
|
if (platform === "facebook" || platform === "both") {
|
||||||
|
results.facebook = await publishFacebookPost({
|
||||||
|
pageId: requirePageId(),
|
||||||
|
message,
|
||||||
|
imageUrl,
|
||||||
|
videoUrl,
|
||||||
|
linkUrl,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (platform === "instagram" || platform === "both") {
|
||||||
|
results.instagram = await publishInstagramPost({
|
||||||
|
igBusinessId: requireIgId(),
|
||||||
|
imageUrl,
|
||||||
|
videoUrl,
|
||||||
|
caption: message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return text(results);
|
||||||
|
} catch (err) {
|
||||||
|
return errorText(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"list_posts",
|
||||||
|
{
|
||||||
|
title: "Listar historico de publicaciones propias",
|
||||||
|
description:
|
||||||
|
"Lee el historico de publicaciones de la propia Facebook Page o de la propia cuenta de Instagram configuradas.",
|
||||||
|
inputSchema: {
|
||||||
|
platform: z.enum(["facebook", "instagram"]),
|
||||||
|
limit: z.number().int().min(1).max(100).default(10),
|
||||||
|
after: z.string().optional().describe("Cursor de paginacion (paging.cursors.after de la respuesta anterior)"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async ({ platform, limit, after }) => {
|
||||||
|
try {
|
||||||
|
const data =
|
||||||
|
platform === "facebook"
|
||||||
|
? await listFacebookPosts({ pageId: requirePageId(), limit, after })
|
||||||
|
: await listInstagramMedia({ igBusinessId: requireIgId(), limit, after });
|
||||||
|
return text(data);
|
||||||
|
} catch (err) {
|
||||||
|
return errorText(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"list_comments",
|
||||||
|
{
|
||||||
|
title: "Listar comentarios",
|
||||||
|
description:
|
||||||
|
"Lista los comentarios de una publicacion propia (post de Facebook o media de Instagram), " +
|
||||||
|
"o las respuestas anidadas de un comentario si se pasa un comment-id.",
|
||||||
|
inputSchema: {
|
||||||
|
objectId: z.string().describe("ID del post, media o comentario del que listar comentarios/respuestas"),
|
||||||
|
limit: z.number().int().min(1).max(100).default(25),
|
||||||
|
after: z.string().optional().describe("Cursor de paginacion"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async ({ objectId, limit, after }) => {
|
||||||
|
try {
|
||||||
|
const data = await listComments({ objectId, limit, after });
|
||||||
|
return text(data);
|
||||||
|
} catch (err) {
|
||||||
|
return errorText(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"get_comment",
|
||||||
|
{
|
||||||
|
title: "Leer un comentario",
|
||||||
|
description: "Obtiene el detalle de un comentario concreto por su ID (valido para FB e IG).",
|
||||||
|
inputSchema: {
|
||||||
|
commentId: z.string(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async ({ commentId }) => {
|
||||||
|
try {
|
||||||
|
const data = await getComment({ commentId });
|
||||||
|
return text(data);
|
||||||
|
} catch (err) {
|
||||||
|
return errorText(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"reply_comment",
|
||||||
|
{
|
||||||
|
title: "Responder a un comentario",
|
||||||
|
description:
|
||||||
|
"Responde a un comentario existente en una publicacion propia. " +
|
||||||
|
"En Facebook crea un comentario anidado; en Instagram usa el edge de respuestas.",
|
||||||
|
inputSchema: {
|
||||||
|
platform: z.enum(["facebook", "instagram"]),
|
||||||
|
commentId: z.string(),
|
||||||
|
message: z.string(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async ({ platform, commentId, message }) => {
|
||||||
|
try {
|
||||||
|
const data =
|
||||||
|
platform === "facebook"
|
||||||
|
? await replyFacebookComment({ commentId, message })
|
||||||
|
: await replyInstagramComment({ commentId, message });
|
||||||
|
return text(data);
|
||||||
|
} catch (err) {
|
||||||
|
return errorText(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user