Spaces:
Sleeping
Sleeping
Commit ·
fb07b17
1
Parent(s): b1ff755
Update Dockerfile to change application entry point to backend/main:app for improved structure.
Browse files- Dockerfile +1 -1
- backend/.dockerignore +1 -0
- backend/.env +5 -0
- backend/.env.example +5 -0
- backend/.python-version +1 -0
- backend/Dockerfile +25 -0
- backend/README.md +0 -0
- backend/__init__.py +0 -0
- backend/agent/__init__.py +3 -0
- backend/agent/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/agent/__pycache__/linkedin_assistant.cpython-313.pyc +0 -0
- backend/agent/linkedin_assistant.py +77 -0
- backend/compose.yml +10 -0
- backend/main.py +85 -0
- backend/mcp_client_tools/__init__.py +3 -0
- backend/mcp_client_tools/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/mcp_client_tools/__pycache__/mcp_client.cpython-313.pyc +0 -0
- backend/mcp_client_tools/mcp_client.py +68 -0
- backend/mcp_server_tools/__init__.py +0 -0
- backend/mcp_server_tools/__pycache__/raw_function.cpython-313.pyc +0 -0
- backend/mcp_server_tools/mcp_server_linkedin.py +154 -0
- backend/mcp_server_tools/mcp_server_weather.py +56 -0
- backend/mcp_server_tools/raw_function.py +110 -0
- backend/pyproject.toml +16 -0
- backend/tools/__init__.py +3 -0
- backend/tools/__pycache__/__init__.cpython-313.pyc +0 -0
- backend/tools/__pycache__/linkedin_post_links.cpython-313.pyc +0 -0
- backend/tools/__pycache__/linkedin_posts.cpython-313.pyc +0 -0
- backend/tools/__pycache__/linkedin_userinfo.cpython-313.pyc +0 -0
- backend/tools/linkedin_group_posts.py +47 -0
- backend/tools/linkedin_post_links.py +140 -0
- backend/tools/linkedin_posts.py +73 -0
- backend/tools/linkedin_userinfo.py +34 -0
- backend/uv.lock +0 -0
Dockerfile
CHANGED
|
@@ -13,4 +13,4 @@ COPY --chown=user ./requirements.txt requirements.txt
|
|
| 13 |
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 14 |
|
| 15 |
COPY --chown=user . /app
|
| 16 |
-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 13 |
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 14 |
|
| 15 |
COPY --chown=user . /app
|
| 16 |
+
CMD ["uvicorn", "backend/main:app", "--host", "0.0.0.0", "--port", "7860"]
|
backend/.dockerignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.venv
|
backend/.env
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GOOGLE_API_KEY="AIzaSyBb_dW5DIKP9N8jcrgQrCjWGbq9JzUHps0"
|
| 2 |
+
|
| 3 |
+
LANGSMITH_API_KEY="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"
|
| 4 |
+
|
| 5 |
+
LINKEDIN_ACCESS_TOKEN="AQXDALy5SlRU2h8GaK5Dr3bP6k0fTpx_eDWAoLXrEJZXeFmOaldcyM1ewqEKozVe3umTODdEzQSoN8JlPrUMuISXUvUKdljgrK1nfsykMKZybDza-6ngfX1BInZ-k0ui-EzfLlxTwJMu7WrjQjlNUw_GzM-wWO6hhta3F_DdRqa5DCEhc-e7XYHE4xYfx9K3945jINGWPga1O8oWak4tr0qSMbaRY3BTJ28b-NJzihUvvKlktJvKsZb_h1sjcfV5FBuPqHLH9zUXR5V7t5nXog7OlbZ5NyGx3GR0zWHmkv7QitrPCCemxpsoQ98b5e9VaYm9HjU_2RwfAswkVUGowxzuhHtfnw"
|
backend/.env.example
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GOOGLE_API_KEY=""
|
| 2 |
+
|
| 3 |
+
LINKEDIN_ACCESS_TOKEN=""
|
| 4 |
+
|
| 5 |
+
LANGSMITH_API_KEY=""
|
backend/.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.13
|
backend/Dockerfile
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Base image for all services
|
| 2 |
+
FROM python:3.13-slim
|
| 3 |
+
|
| 4 |
+
# Install uv for dependency management
|
| 5 |
+
RUN pip install uv
|
| 6 |
+
|
| 7 |
+
WORKDIR /app/
|
| 8 |
+
|
| 9 |
+
COPY pyproject.toml uv.lock ./
|
| 10 |
+
|
| 11 |
+
# Copy the main script and the agent directory
|
| 12 |
+
COPY main.py ./
|
| 13 |
+
COPY agent ./agent/
|
| 14 |
+
COPY tools ./tools/
|
| 15 |
+
COPY mcp_server_tools ./mcp_server_tools/
|
| 16 |
+
COPY mcp_client_tools ./mcp_client_tools/
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
RUN uv sync --frozen
|
| 20 |
+
|
| 21 |
+
# Expose all necessary ports
|
| 22 |
+
EXPOSE 8002
|
| 23 |
+
|
| 24 |
+
# Use the start script as the entry point
|
| 25 |
+
CMD ["uv","run","uvicorn","main:app","--port","8002","--host","0.0.0.0","--reload"]
|
backend/README.md
ADDED
|
File without changes
|
backend/__init__.py
ADDED
|
File without changes
|
backend/agent/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from agent import linkedin_assistant
|
| 2 |
+
|
| 3 |
+
__all__ = ["linkedin_assistant"]
|
backend/agent/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (234 Bytes). View file
|
|
|
backend/agent/__pycache__/linkedin_assistant.cpython-313.pyc
ADDED
|
Binary file (3.85 kB). View file
|
|
|
backend/agent/linkedin_assistant.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# from mcp_client_tools.mcp_client import get_mcp_weather_client, get_mcp_linkedin_client
|
| 2 |
+
from tools.linkedin_post_links import create_post_links_image
|
| 3 |
+
from tools.linkedin_posts import post_content_linkedin
|
| 4 |
+
from tools.linkedin_userinfo import get_user_info
|
| 5 |
+
from agents import Agent, OpenAIChatCompletionsModel
|
| 6 |
+
from dotenv import load_dotenv, find_dotenv
|
| 7 |
+
from openai import AsyncOpenAI
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
|
| 12 |
+
|
| 13 |
+
load_dotenv(find_dotenv())
|
| 14 |
+
|
| 15 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 16 |
+
|
| 17 |
+
gemini_client = AsyncOpenAI(
|
| 18 |
+
api_key=GOOGLE_API_KEY,
|
| 19 |
+
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
async def create_assistant_agent():
|
| 24 |
+
# mcp_server_linkedin = await get_mcp_linkedin_client()
|
| 25 |
+
# mcp_server_weather = await get_mcp_weather_client()
|
| 26 |
+
|
| 27 |
+
return Agent(
|
| 28 |
+
name="LinkedIn Assistant",
|
| 29 |
+
instructions=(
|
| 30 |
+
"""
|
| 31 |
+
# LinkedIn Assistant Guide
|
| 32 |
+
|
| 33 |
+
You are a LinkedIn profile assistant that helps users manage their professional presence. Here's how you operate:
|
| 34 |
+
|
| 35 |
+
TOOLS AND THEIR USAGE:
|
| 36 |
+
1. get_user_info: Use this to fetch and display user's LinkedIn profile information when they ask about their profile details.
|
| 37 |
+
2. post_content_linkedin: Use this for creating text-only posts. When a user wants to make a post without images/links.
|
| 38 |
+
3. create_post_links_image: Use this when users want to create posts with images or links. Requires:
|
| 39 |
+
- image_path: Path to the image file or URL
|
| 40 |
+
- post_text: You will automatically generate engaging and professional post content
|
| 41 |
+
4. get_weather: Use this to fetch current weather data for any city. Useful for creating weather-related posts or checking conditions.
|
| 42 |
+
|
| 43 |
+
WORKFLOW:
|
| 44 |
+
- Only call one tool per request.
|
| 45 |
+
- For profile queries: Call `get_user_info` and do not combine with any other tools.
|
| 46 |
+
- For text-only posts: Use `post_content_linkedin` with self-generated content
|
| 47 |
+
- For posts with images/links: Use `create_post_links_image` with self-generated content
|
| 48 |
+
- For weather information: Call `get_weather` separately with the city name.
|
| 49 |
+
|
| 50 |
+
FORMAT:
|
| 51 |
+
- Headers with # for main titles and ## for subtitles
|
| 52 |
+
- **bold** for emphasis
|
| 53 |
+
- *italic* for secondary emphasis
|
| 54 |
+
- Bullet points with - or * for lists
|
| 55 |
+
- Code blocks with ``` for technical content
|
| 56 |
+
- Links with [text](url) format
|
| 57 |
+
- Tables using | and - for structured data
|
| 58 |
+
- Images with  format
|
| 59 |
+
- Always return in format
|
| 60 |
+
|
| 61 |
+
GUIDELINES:
|
| 62 |
+
- Maintain a professional and helpful tone
|
| 63 |
+
- Focus on LinkedIn-related tasks and weather information
|
| 64 |
+
- Generate engaging and relevant post content automatically
|
| 65 |
+
- Create posts immediately without asking for confirmation
|
| 66 |
+
- Provide clear feedback after actions are completed
|
| 67 |
+
- Write posts in first person as if you are the user
|
| 68 |
+
- Use weather data to create relevant professional posts when appropriate
|
| 69 |
+
- Never combine tool names like `get_user_infoget_weather` — only one tool per call.
|
| 70 |
+
"""
|
| 71 |
+
),
|
| 72 |
+
model=OpenAIChatCompletionsModel(
|
| 73 |
+
model="gemini-2.5-flash-preview-05-20", openai_client=gemini_client
|
| 74 |
+
),
|
| 75 |
+
# mcp_servers=[mcp_server_linkedin, mcp_server_weather],
|
| 76 |
+
tools=[post_content_linkedin, create_post_links_image, get_user_info],
|
| 77 |
+
)
|
backend/compose.yml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
agent-backend:
|
| 3 |
+
container_name: Agent-Container
|
| 4 |
+
build:
|
| 5 |
+
context: ./
|
| 6 |
+
dockerfile: Dockerfile
|
| 7 |
+
ports:
|
| 8 |
+
- 8002:8002
|
| 9 |
+
env_file:
|
| 10 |
+
- .env
|
backend/main.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import asynccontextmanager
|
| 2 |
+
from langsmith.wrappers import OpenAIAgentsTracingProcessor
|
| 3 |
+
from agent.linkedin_assistant import create_assistant_agent
|
| 4 |
+
from openai.types.responses import ResponseTextDeltaEvent
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from agents import Runner, set_trace_processors
|
| 7 |
+
from fastapi.responses import StreamingResponse
|
| 8 |
+
from dotenv import find_dotenv, load_dotenv
|
| 9 |
+
from fastapi import FastAPI, HTTPException
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
load_dotenv(find_dotenv())
|
| 15 |
+
|
| 16 |
+
os.environ["LANGCHAIN_TRACING_V2"] = "true"
|
| 17 |
+
os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGSMITH_API_KEY")
|
| 18 |
+
os.environ["LANGCHAIN_PROJECT"] = "linkedin"
|
| 19 |
+
|
| 20 |
+
set_trace_processors([OpenAIAgentsTracingProcessor()])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@asynccontextmanager
|
| 24 |
+
async def lifespan(app: FastAPI):
|
| 25 |
+
global assistant_agent
|
| 26 |
+
try:
|
| 27 |
+
from agent.linkedin_assistant import create_assistant_agent
|
| 28 |
+
assistant_agent = await create_assistant_agent()
|
| 29 |
+
print("[✓] Assistant agent initialized.")
|
| 30 |
+
yield
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"[✗] Failed to initialize assistant agent: {e}")
|
| 33 |
+
raise # Let FastAPI shutdown cleanly on failure
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
app: FastAPI = FastAPI(lifespan=lifespan)
|
| 37 |
+
|
| 38 |
+
# Add CORS middleware
|
| 39 |
+
app.add_middleware(
|
| 40 |
+
CORSMiddleware,
|
| 41 |
+
allow_origins=["*"],
|
| 42 |
+
allow_credentials=True,
|
| 43 |
+
allow_methods=["*"],
|
| 44 |
+
allow_headers=["*"],
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# @app.on_event("startup")
|
| 48 |
+
# async def startup_event():
|
| 49 |
+
# global assistant_agent
|
| 50 |
+
# assistant_agent = await create_assistant_agent()
|
| 51 |
+
|
| 52 |
+
@app.post("/run")
|
| 53 |
+
async def agent_fastapi(input):
|
| 54 |
+
result = await Runner.run(assistant_agent, input=input)
|
| 55 |
+
print(result.final_output)
|
| 56 |
+
return result.final_output
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
async def stream_response(input):
|
| 60 |
+
result = Runner.run_streamed(assistant_agent, input=input)
|
| 61 |
+
async for events in result.stream_events():
|
| 62 |
+
if events.type == "raw_response_event" and isinstance(
|
| 63 |
+
events.data, ResponseTextDeltaEvent
|
| 64 |
+
):
|
| 65 |
+
chunk = json.dumps(events.data.delta)
|
| 66 |
+
yield chunk
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class InputData(BaseModel):
|
| 70 |
+
input: str
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@app.post("/chat/stream")
|
| 74 |
+
async def agent_fastapi_streaming(data: InputData):
|
| 75 |
+
if not data.input:
|
| 76 |
+
raise HTTPException(status_code=400, detail="Message text cannot be empty")
|
| 77 |
+
return StreamingResponse(
|
| 78 |
+
stream_response(data.input), media_type="text/event-stream"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
import uvicorn
|
| 84 |
+
|
| 85 |
+
uvicorn.run(app="main:app", host="0.0.0.0", port=8002, reload=True)
|
backend/mcp_client_tools/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mcp_client_tools import mcp_client
|
| 2 |
+
|
| 3 |
+
__all__ = [mcp_client]
|
backend/mcp_client_tools/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (242 Bytes). View file
|
|
|
backend/mcp_client_tools/__pycache__/mcp_client.cpython-313.pyc
ADDED
|
Binary file (4.13 kB). View file
|
|
|
backend/mcp_client_tools/mcp_client.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from agents.mcp import MCPServerStreamableHttp, MCPServerStreamableHttpParams
|
| 3 |
+
from dotenv import load_dotenv, find_dotenv
|
| 4 |
+
import os
|
| 5 |
+
import aiohttp
|
| 6 |
+
|
| 7 |
+
load_dotenv(find_dotenv())
|
| 8 |
+
|
| 9 |
+
# Read MCP host from env or fallback to localhost
|
| 10 |
+
MCP_HOST = os.getenv("MCP_HOST", "localhost")
|
| 11 |
+
|
| 12 |
+
# Define MCP endpoints
|
| 13 |
+
SERVER_MCP_ENDPOINT_URL_1 = f"http://{MCP_HOST}:8000/mcp/"
|
| 14 |
+
SERVER_MCP_ENDPOINT_URL_2 = f"http://{MCP_HOST}:8001/mcp/"
|
| 15 |
+
|
| 16 |
+
# MCP client parameter instances
|
| 17 |
+
linkedin_params = MCPServerStreamableHttpParams(url=SERVER_MCP_ENDPOINT_URL_1)
|
| 18 |
+
weather_params = MCPServerStreamableHttpParams(url=SERVER_MCP_ENDPOINT_URL_2)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Utility: Wait for MCP server to be ready before attempting connection
|
| 22 |
+
async def wait_for_mcp_server(url: str, retries: int = 10, delay: int = 2):
|
| 23 |
+
for attempt in range(retries):
|
| 24 |
+
try:
|
| 25 |
+
async with aiohttp.ClientSession() as session:
|
| 26 |
+
async with session.get(url, timeout=3) as resp:
|
| 27 |
+
print(
|
| 28 |
+
f"[✓] MCP server responded with status {resp.status} at {url}"
|
| 29 |
+
)
|
| 30 |
+
return
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"[{attempt+1}/{retries}] MCP not ready: {e}")
|
| 33 |
+
await asyncio.sleep(delay)
|
| 34 |
+
raise RuntimeError(
|
| 35 |
+
f"[✗] MCP server at {url} is not available after {retries} attempts."
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Public: Connect to LinkedIn MCP server
|
| 40 |
+
async def get_mcp_linkedin_client(max_retries=3, retry_delay=2):
|
| 41 |
+
for attempt in range(max_retries):
|
| 42 |
+
try:
|
| 43 |
+
await wait_for_mcp_server(SERVER_MCP_ENDPOINT_URL_1)
|
| 44 |
+
client = MCPServerStreamableHttp(params=linkedin_params)
|
| 45 |
+
await client.connect()
|
| 46 |
+
print("[✓] Connected to LinkedIn MCP server")
|
| 47 |
+
return client
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"[{attempt+1}/{max_retries}] Failed to connect to LinkedIn MCP: {e}")
|
| 50 |
+
if attempt == max_retries - 1:
|
| 51 |
+
raise
|
| 52 |
+
await asyncio.sleep(retry_delay)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Public: Connect to Weather MCP server
|
| 56 |
+
async def get_mcp_weather_client(max_retries=3, retry_delay=2):
|
| 57 |
+
for attempt in range(max_retries):
|
| 58 |
+
try:
|
| 59 |
+
await wait_for_mcp_server(SERVER_MCP_ENDPOINT_URL_2)
|
| 60 |
+
client = MCPServerStreamableHttp(params=weather_params)
|
| 61 |
+
await client.connect()
|
| 62 |
+
print("[✓] Connected to Weather MCP server")
|
| 63 |
+
return client
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"[{attempt+1}/{max_retries}] Failed to connect to Weather MCP: {e}")
|
| 66 |
+
if attempt == max_retries - 1:
|
| 67 |
+
raise
|
| 68 |
+
await asyncio.sleep(retry_delay)
|
backend/mcp_server_tools/__init__.py
ADDED
|
File without changes
|
backend/mcp_server_tools/__pycache__/raw_function.cpython-313.pyc
ADDED
|
Binary file (4.56 kB). View file
|
|
|
backend/mcp_server_tools/mcp_server_linkedin.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from raw_function import register_image_upload, upload_image, get_user_id
|
| 2 |
+
from dotenv import load_dotenv, find_dotenv
|
| 3 |
+
from mcp.server.fastmcp import FastMCP
|
| 4 |
+
import requests
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Create server
|
| 8 |
+
mcp = FastMCP(
|
| 9 |
+
name="Linkedin MCP Server",
|
| 10 |
+
description="A basic MCP server for HTTP client demonstration.",
|
| 11 |
+
stateless_http=True, # Makes the server treat each HTTP request independently
|
| 12 |
+
json_response=True, # Allows single JSON responses for non-streaming calls (optimization)
|
| 13 |
+
port=8000,
|
| 14 |
+
host="0.0.0.0",
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Constants
|
| 18 |
+
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
|
| 19 |
+
|
| 20 |
+
load_dotenv(find_dotenv())
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
HEADERS = {
|
| 24 |
+
"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",
|
| 25 |
+
"Content-Type": "application/json",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@mcp.tool(
|
| 30 |
+
name="get_user_info",
|
| 31 |
+
description="Retrieves the authenticated user's LinkedIn profile information including their ID, name, and other profile details.",
|
| 32 |
+
)
|
| 33 |
+
def get_user_info():
|
| 34 |
+
"""
|
| 35 |
+
Retrieve LinkedIn user profile information using the /userinfo endpoint.
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
dict: User profile information or None if an error occurs.
|
| 39 |
+
"""
|
| 40 |
+
url = "https://api.linkedin.com/v2/userinfo"
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
response = requests.get(url, headers=HEADERS)
|
| 44 |
+
response.raise_for_status()
|
| 45 |
+
return response.json()
|
| 46 |
+
except requests.exceptions.RequestException as e:
|
| 47 |
+
print(f"Error fetching user info: {e}")
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@mcp.tool(
|
| 52 |
+
name="post_content_linkedin",
|
| 53 |
+
description="Creates a text-only post on LinkedIn with the specified content. The post will be visible to the public.",
|
| 54 |
+
)
|
| 55 |
+
def post_content_linkedin(content: str):
|
| 56 |
+
"""
|
| 57 |
+
Share content on LinkedIn.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
content (str): The text content to post on LinkedIn.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
dict: API response or None if an error occurs.
|
| 64 |
+
"""
|
| 65 |
+
user_info = get_user_id()
|
| 66 |
+
if not user_info:
|
| 67 |
+
print("Failed to retrieve user information.")
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
author_urn = f"urn:li:person:{user_info['sub']}"
|
| 71 |
+
url = "https://api.linkedin.com/v2/ugcPosts"
|
| 72 |
+
payload = {
|
| 73 |
+
"author": author_urn,
|
| 74 |
+
"lifecycleState": "PUBLISHED",
|
| 75 |
+
"specificContent": {
|
| 76 |
+
"com.linkedin.ugc.ShareContent": {
|
| 77 |
+
"shareCommentary": {"text": content},
|
| 78 |
+
"shareMediaCategory": "NONE",
|
| 79 |
+
}
|
| 80 |
+
},
|
| 81 |
+
"visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"},
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
response = requests.post(url, headers=HEADERS, json=payload)
|
| 86 |
+
response.raise_for_status()
|
| 87 |
+
return response.json()
|
| 88 |
+
except requests.exceptions.RequestException as e:
|
| 89 |
+
print(f"Error posting content: {e}")
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@mcp.tool(
|
| 94 |
+
name="create_post_links_image",
|
| 95 |
+
description="Creates a LinkedIn post with both text content and an image. The image can be provided as a local file path or URL, and the post will be visible to the public.",
|
| 96 |
+
)
|
| 97 |
+
def create_post_links_image(image_path: str, post_text: str):
|
| 98 |
+
"""
|
| 99 |
+
Create a post on LinkedIn with the uploaded image.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
image_path (str): Path to the image file or URL of the image to post.
|
| 103 |
+
post_text (str): The text content to accompany the image in the post.
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
None: Prints success or error message.
|
| 107 |
+
"""
|
| 108 |
+
# Step 1: Register image upload
|
| 109 |
+
upload_url, image_urn = register_image_upload()
|
| 110 |
+
if not (upload_url and image_urn):
|
| 111 |
+
print("Failed to register image upload.")
|
| 112 |
+
return
|
| 113 |
+
|
| 114 |
+
# Step 2: Upload the image
|
| 115 |
+
if not upload_image(upload_url, image_path):
|
| 116 |
+
print("Failed to upload image.")
|
| 117 |
+
return
|
| 118 |
+
|
| 119 |
+
# Step 3: Create the post
|
| 120 |
+
user_info = get_user_info()
|
| 121 |
+
if not user_info:
|
| 122 |
+
print("Failed to retrieve user information.")
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
url = "https://api.linkedin.com/v2/ugcPosts"
|
| 126 |
+
payload = {
|
| 127 |
+
"author": f"urn:li:person:{user_info['sub']}",
|
| 128 |
+
"lifecycleState": "PUBLISHED",
|
| 129 |
+
"specificContent": {
|
| 130 |
+
"com.linkedin.ugc.ShareContent": {
|
| 131 |
+
"shareCommentary": {"text": post_text},
|
| 132 |
+
"shareMediaCategory": "IMAGE",
|
| 133 |
+
"media": [
|
| 134 |
+
{
|
| 135 |
+
"status": "READY",
|
| 136 |
+
"media": image_urn,
|
| 137 |
+
}
|
| 138 |
+
],
|
| 139 |
+
}
|
| 140 |
+
},
|
| 141 |
+
"visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"},
|
| 142 |
+
}
|
| 143 |
+
response = requests.post(url, headers=HEADERS, json=payload)
|
| 144 |
+
if response.status_code == 201:
|
| 145 |
+
print("Post created successfully.")
|
| 146 |
+
else:
|
| 147 |
+
print(f"Error creating post: {response.status_code}")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# 6. Make the server runnable
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
print(f"Starting MCP server '{mcp.name}'...")
|
| 153 |
+
# This uses the built-in server runner from the MCP SDK.
|
| 154 |
+
mcp.run(transport="streamable-http")
|
backend/mcp_server_tools/mcp_server_weather.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mcp.server.fastmcp import FastMCP
|
| 2 |
+
|
| 3 |
+
# Create server
|
| 4 |
+
mcp = FastMCP(
|
| 5 |
+
name="Weather MCP Server",
|
| 6 |
+
description="A basic MCP server for HTTP client demonstration.",
|
| 7 |
+
stateless_http=True, # Makes the server treat each HTTP request independently
|
| 8 |
+
json_response=True, # Allows single JSON responses for non-streaming calls (optimization)
|
| 9 |
+
port=8001,
|
| 10 |
+
host="0.0.0.0",
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@mcp.tool("get_weather")
|
| 15 |
+
def get_weather(city: str) -> dict:
|
| 16 |
+
"""
|
| 17 |
+
Get current weather data for a specified city using wttr.in API.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
city (str): Name of the city to get weather for
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
dict: Weather data including temperature, humidity, description etc.
|
| 24 |
+
"""
|
| 25 |
+
import requests
|
| 26 |
+
|
| 27 |
+
# API endpoint
|
| 28 |
+
base_url = f"https://wttr.in/{city}?format=j1"
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
# Make API request
|
| 32 |
+
response = requests.get(base_url)
|
| 33 |
+
response.raise_for_status()
|
| 34 |
+
|
| 35 |
+
# Parse response
|
| 36 |
+
weather_data = response.json()
|
| 37 |
+
current = weather_data["current_condition"][0]
|
| 38 |
+
|
| 39 |
+
# Extract relevant information
|
| 40 |
+
result = {
|
| 41 |
+
"city": city,
|
| 42 |
+
"temperature": float(current["temp_C"]),
|
| 43 |
+
"feels_like": float(current["FeelsLikeC"]),
|
| 44 |
+
"humidity": int(current["humidity"]),
|
| 45 |
+
"description": current["weatherDesc"][0]["value"],
|
| 46 |
+
"wind_speed": float(current["windspeedKmph"]),
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
return result
|
| 50 |
+
|
| 51 |
+
except requests.exceptions.RequestException as e:
|
| 52 |
+
return {"error": f"Failed to fetch weather data: {str(e)}"}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
mcp.run(transport="streamable-http")
|
backend/mcp_server_tools/raw_function.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dotenv import load_dotenv, find_dotenv
|
| 2 |
+
import requests
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# Constants
|
| 6 |
+
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
|
| 7 |
+
|
| 8 |
+
load_dotenv(find_dotenv())
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
HEADERS = {
|
| 12 |
+
"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",
|
| 13 |
+
"Content-Type": "application/json",
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_user_id():
|
| 18 |
+
"""
|
| 19 |
+
Retrieve LinkedIn user profile information using the /userinfo endpoint.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
dict: User profile information or None if an error occurs.
|
| 23 |
+
"""
|
| 24 |
+
url = "https://api.linkedin.com/v2/userinfo"
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
response = requests.get(url, headers=HEADERS)
|
| 28 |
+
response.raise_for_status()
|
| 29 |
+
return response.json()
|
| 30 |
+
except requests.exceptions.RequestException as e:
|
| 31 |
+
print(f"Error fetching user info: {e}")
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_user_info():
|
| 36 |
+
"""Retrieve the authenticated user's LinkedIn information."""
|
| 37 |
+
url = "https://api.linkedin.com/v2/userinfo"
|
| 38 |
+
response = requests.get(url, headers=HEADERS)
|
| 39 |
+
if response.status_code == 200:
|
| 40 |
+
return response.json()
|
| 41 |
+
else:
|
| 42 |
+
print(f"Error fetching user info: {response.status_code}")
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def register_image_upload():
|
| 47 |
+
"""Register an image upload with LinkedIn."""
|
| 48 |
+
user_info = get_user_info()
|
| 49 |
+
if not user_info:
|
| 50 |
+
print("Failed to retrieve user information.")
|
| 51 |
+
return None, None
|
| 52 |
+
url = "https://api.linkedin.com/v2/assets?action=registerUpload"
|
| 53 |
+
payload = {
|
| 54 |
+
"registerUploadRequest": {
|
| 55 |
+
"recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],
|
| 56 |
+
"owner": f"urn:li:person:{user_info['sub']}",
|
| 57 |
+
"serviceRelationships": [
|
| 58 |
+
{
|
| 59 |
+
"relationshipType": "OWNER",
|
| 60 |
+
"identifier": "urn:li:userGeneratedContent",
|
| 61 |
+
}
|
| 62 |
+
],
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
response = requests.post(url, headers=HEADERS, json=payload)
|
| 66 |
+
if response.status_code == 200:
|
| 67 |
+
return response.json().get("value", {}).get("uploadMechanism", {}).get(
|
| 68 |
+
"com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest", {}
|
| 69 |
+
).get("uploadUrl"), response.json().get("value", {}).get("asset")
|
| 70 |
+
else:
|
| 71 |
+
print(f"Error registering image upload: {response.status_code}")
|
| 72 |
+
return None, None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def upload_image(upload_url, image_source):
|
| 76 |
+
"""
|
| 77 |
+
Upload the image to LinkedIn.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
upload_url (str): The LinkedIn upload URL
|
| 81 |
+
image_source (str): Either a local file path or a URL to the image
|
| 82 |
+
"""
|
| 83 |
+
if image_source.startswith(("http://", "https://")):
|
| 84 |
+
# Handle URL
|
| 85 |
+
response = requests.get(image_source)
|
| 86 |
+
if response.status_code != 200:
|
| 87 |
+
print(f"Error fetching image from URL: {response.status_code}")
|
| 88 |
+
return False
|
| 89 |
+
image_data = response.content
|
| 90 |
+
else:
|
| 91 |
+
# Handle local file
|
| 92 |
+
try:
|
| 93 |
+
with open(image_source, "rb") as image_file:
|
| 94 |
+
image_data = image_file.read()
|
| 95 |
+
except FileNotFoundError:
|
| 96 |
+
print(f"Error: Image file not found at {image_source}")
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
response = requests.post(
|
| 100 |
+
upload_url,
|
| 101 |
+
headers={"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}"},
|
| 102 |
+
data=image_data,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
if response.status_code == 201:
|
| 106 |
+
print("Image uploaded successfully.")
|
| 107 |
+
return True
|
| 108 |
+
else:
|
| 109 |
+
print(f"Error uploading image: {response.status_code}")
|
| 110 |
+
return False
|
backend/pyproject.toml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "backend"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Add your description here"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.13"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"aiohttp>=3.11.18",
|
| 9 |
+
"fastapi>=0.115.12",
|
| 10 |
+
"langgraph>=0.3.27",
|
| 11 |
+
"langsmith[openai-agents]>=0.3.28",
|
| 12 |
+
"mcp[cli]>=1.9.0",
|
| 13 |
+
"openai-agents==0.0.15",
|
| 14 |
+
"python-dotenv>=1.1.0",
|
| 15 |
+
"uvicorn>=0.34.0",
|
| 16 |
+
]
|
backend/tools/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tools import linkedin_post_links, linkedin_posts, linkedin_userinfo
|
| 2 |
+
|
| 3 |
+
__all__ = ["linkedin_post_links", "linkedin_posts", "linkedin_userinfo"]
|
backend/tools/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (285 Bytes). View file
|
|
|
backend/tools/__pycache__/linkedin_post_links.cpython-313.pyc
ADDED
|
Binary file (5.57 kB). View file
|
|
|
backend/tools/__pycache__/linkedin_posts.cpython-313.pyc
ADDED
|
Binary file (2.94 kB). View file
|
|
|
backend/tools/__pycache__/linkedin_userinfo.cpython-313.pyc
ADDED
|
Binary file (1.65 kB). View file
|
|
|
backend/tools/linkedin_group_posts.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
from agents import function_tool
|
| 3 |
+
from dotenv import find_dotenv, load_dotenv
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# Constants
|
| 7 |
+
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
|
| 8 |
+
|
| 9 |
+
load_dotenv(find_dotenv())
|
| 10 |
+
|
| 11 |
+
HEADERS = {
|
| 12 |
+
"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",
|
| 13 |
+
"Content-Type": "application/json",
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@function_tool
|
| 18 |
+
def post_group_content_linkedin(content: str, group_id: str):
|
| 19 |
+
"""
|
| 20 |
+
Share content in a LinkedIn group.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
params (PostGroupContentParams): Parameters for the group post.
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
dict: API response or None if an error occurs.
|
| 27 |
+
"""
|
| 28 |
+
url = "https://api.linkedin.com/v2/ugcPosts"
|
| 29 |
+
payload = {
|
| 30 |
+
"author": f"urn:li:group:{group_id}",
|
| 31 |
+
"lifecycleState": "PUBLISHED",
|
| 32 |
+
"specificContent": {
|
| 33 |
+
"com.linkedin.ugc.ShareContent": {
|
| 34 |
+
"shareCommentary": {"text": content},
|
| 35 |
+
"shareMediaCategory": "NONE",
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
"visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"},
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
response = requests.post(url, headers=HEADERS, json=payload)
|
| 43 |
+
response.raise_for_status()
|
| 44 |
+
return response.json()
|
| 45 |
+
except requests.exceptions.RequestException as e:
|
| 46 |
+
print(f"Error posting content to group: {e}")
|
| 47 |
+
return None
|
backend/tools/linkedin_post_links.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import os
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from agents import function_tool
|
| 5 |
+
|
| 6 |
+
# Load environment variables
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# # Constants
|
| 11 |
+
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
|
| 12 |
+
|
| 13 |
+
# Headers for LinkedIn API requests
|
| 14 |
+
HEADERS = {
|
| 15 |
+
"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",
|
| 16 |
+
"X-Restli-Protocol-Version": "2.0.0",
|
| 17 |
+
"Content-Type": "application/json",
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_user_info():
|
| 22 |
+
"""Retrieve the authenticated user's LinkedIn information."""
|
| 23 |
+
url = "https://api.linkedin.com/v2/userinfo"
|
| 24 |
+
response = requests.get(url, headers=HEADERS)
|
| 25 |
+
if response.status_code == 200:
|
| 26 |
+
return response.json()
|
| 27 |
+
else:
|
| 28 |
+
print(f"Error fetching user info: {response.status_code}")
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def register_image_upload():
|
| 33 |
+
"""Register an image upload with LinkedIn."""
|
| 34 |
+
user_info = get_user_info()
|
| 35 |
+
if not user_info:
|
| 36 |
+
print("Failed to retrieve user information.")
|
| 37 |
+
return None, None
|
| 38 |
+
url = "https://api.linkedin.com/v2/assets?action=registerUpload"
|
| 39 |
+
payload = {
|
| 40 |
+
"registerUploadRequest": {
|
| 41 |
+
"recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],
|
| 42 |
+
"owner": f"urn:li:person:{user_info['sub']}",
|
| 43 |
+
"serviceRelationships": [
|
| 44 |
+
{
|
| 45 |
+
"relationshipType": "OWNER",
|
| 46 |
+
"identifier": "urn:li:userGeneratedContent",
|
| 47 |
+
}
|
| 48 |
+
],
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
response = requests.post(url, headers=HEADERS, json=payload)
|
| 52 |
+
if response.status_code == 200:
|
| 53 |
+
return response.json().get("value", {}).get("uploadMechanism", {}).get(
|
| 54 |
+
"com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest", {}
|
| 55 |
+
).get("uploadUrl"), response.json().get("value", {}).get("asset")
|
| 56 |
+
else:
|
| 57 |
+
print(f"Error registering image upload: {response.status_code}")
|
| 58 |
+
return None, None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def upload_image(upload_url, image_source):
|
| 62 |
+
"""
|
| 63 |
+
Upload the image to LinkedIn.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
upload_url (str): The LinkedIn upload URL
|
| 67 |
+
image_source (str): Either a local file path or a URL to the image
|
| 68 |
+
"""
|
| 69 |
+
if image_source.startswith(("http://", "https://")):
|
| 70 |
+
# Handle URL
|
| 71 |
+
response = requests.get(image_source)
|
| 72 |
+
if response.status_code != 200:
|
| 73 |
+
print(f"Error fetching image from URL: {response.status_code}")
|
| 74 |
+
return False
|
| 75 |
+
image_data = response.content
|
| 76 |
+
else:
|
| 77 |
+
# Handle local file
|
| 78 |
+
try:
|
| 79 |
+
with open(image_source, "rb") as image_file:
|
| 80 |
+
image_data = image_file.read()
|
| 81 |
+
except FileNotFoundError:
|
| 82 |
+
print(f"Error: Image file not found at {image_source}")
|
| 83 |
+
return False
|
| 84 |
+
|
| 85 |
+
response = requests.post(
|
| 86 |
+
upload_url,
|
| 87 |
+
headers={"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}"},
|
| 88 |
+
data=image_data,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
if response.status_code == 201:
|
| 92 |
+
print("Image uploaded successfully.")
|
| 93 |
+
return True
|
| 94 |
+
else:
|
| 95 |
+
print(f"Error uploading image: {response.status_code}")
|
| 96 |
+
return False
|
| 97 |
+
|
| 98 |
+
@function_tool
|
| 99 |
+
def create_post_links_image(image_path: str, post_text: str):
|
| 100 |
+
"""Create a post on LinkedIn with the uploaded image."""
|
| 101 |
+
# Step 1: Register image upload
|
| 102 |
+
upload_url, image_urn = register_image_upload()
|
| 103 |
+
if not (upload_url and image_urn):
|
| 104 |
+
print("Failed to register image upload.")
|
| 105 |
+
return
|
| 106 |
+
|
| 107 |
+
# Step 2: Upload the image
|
| 108 |
+
if not upload_image(upload_url, image_path):
|
| 109 |
+
print("Failed to upload image.")
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
# Step 3: Create the post
|
| 113 |
+
user_info = get_user_info()
|
| 114 |
+
if not user_info:
|
| 115 |
+
print("Failed to retrieve user information.")
|
| 116 |
+
return
|
| 117 |
+
|
| 118 |
+
url = "https://api.linkedin.com/v2/ugcPosts"
|
| 119 |
+
payload = {
|
| 120 |
+
"author": f"urn:li:person:{user_info['sub']}",
|
| 121 |
+
"lifecycleState": "PUBLISHED",
|
| 122 |
+
"specificContent": {
|
| 123 |
+
"com.linkedin.ugc.ShareContent": {
|
| 124 |
+
"shareCommentary": {"text": post_text},
|
| 125 |
+
"shareMediaCategory": "IMAGE",
|
| 126 |
+
"media": [
|
| 127 |
+
{
|
| 128 |
+
"status": "READY",
|
| 129 |
+
"media": image_urn,
|
| 130 |
+
}
|
| 131 |
+
],
|
| 132 |
+
}
|
| 133 |
+
},
|
| 134 |
+
"visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"},
|
| 135 |
+
}
|
| 136 |
+
response = requests.post(url, headers=HEADERS, json=payload)
|
| 137 |
+
if response.status_code == 201:
|
| 138 |
+
print("Post created successfully.")
|
| 139 |
+
else:
|
| 140 |
+
print(f"Error creating post: {response.status_code}")
|
backend/tools/linkedin_posts.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from agents import function_tool
|
| 2 |
+
import requests
|
| 3 |
+
from dotenv import find_dotenv, load_dotenv
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# # Constants
|
| 8 |
+
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
|
| 9 |
+
|
| 10 |
+
load_dotenv(find_dotenv())
|
| 11 |
+
|
| 12 |
+
HEADERS = {
|
| 13 |
+
"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",
|
| 14 |
+
"Content-Type": "application/json",
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_user_id():
|
| 19 |
+
"""
|
| 20 |
+
Retrieve LinkedIn user profile information using the /userinfo endpoint.
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
dict: User profile information or None if an error occurs.
|
| 24 |
+
"""
|
| 25 |
+
url = "https://api.linkedin.com/v2/userinfo"
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
response = requests.get(url, headers=HEADERS)
|
| 29 |
+
response.raise_for_status()
|
| 30 |
+
return response.json()
|
| 31 |
+
except requests.exceptions.RequestException as e:
|
| 32 |
+
print(f"Error fetching user info: {e}")
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# @traceable
|
| 37 |
+
@function_tool
|
| 38 |
+
def post_content_linkedin(content: str):
|
| 39 |
+
"""
|
| 40 |
+
Share content on LinkedIn.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
params (RunContextWrapper[PostContentParams]): Parameters for the post.
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
dict: API response or None if an error occurs.
|
| 47 |
+
"""
|
| 48 |
+
user_info = get_user_id()
|
| 49 |
+
if not user_info:
|
| 50 |
+
print("Failed to retrieve user information.")
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
author_urn = f"urn:li:person:{user_info['sub']}"
|
| 54 |
+
url = "https://api.linkedin.com/v2/ugcPosts"
|
| 55 |
+
payload = {
|
| 56 |
+
"author": author_urn,
|
| 57 |
+
"lifecycleState": "PUBLISHED",
|
| 58 |
+
"specificContent": {
|
| 59 |
+
"com.linkedin.ugc.ShareContent": {
|
| 60 |
+
"shareCommentary": {"text": content},
|
| 61 |
+
"shareMediaCategory": "NONE",
|
| 62 |
+
}
|
| 63 |
+
},
|
| 64 |
+
"visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"},
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
response = requests.post(url, headers=HEADERS, json=payload)
|
| 69 |
+
response.raise_for_status()
|
| 70 |
+
return response.json()
|
| 71 |
+
except requests.exceptions.RequestException as e:
|
| 72 |
+
print(f"Error posting content: {e}")
|
| 73 |
+
return None
|
backend/tools/linkedin_userinfo.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
from agents import function_tool
|
| 3 |
+
from dotenv import find_dotenv, load_dotenv
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Constants
|
| 8 |
+
LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN")
|
| 9 |
+
|
| 10 |
+
load_dotenv(find_dotenv())
|
| 11 |
+
|
| 12 |
+
HEADERS = {
|
| 13 |
+
"Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}",
|
| 14 |
+
"Content-Type": "application/json",
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@function_tool
|
| 19 |
+
def get_user_info():
|
| 20 |
+
"""
|
| 21 |
+
Retrieve LinkedIn user profile information using the /userinfo endpoint.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
dict: User profile information or None if an error occurs.
|
| 25 |
+
"""
|
| 26 |
+
url = "https://api.linkedin.com/v2/userinfo"
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
response = requests.get(url, headers=HEADERS)
|
| 30 |
+
response.raise_for_status()
|
| 31 |
+
return response.json()
|
| 32 |
+
except requests.exceptions.RequestException as e:
|
| 33 |
+
print(f"Error fetching user info: {e}")
|
| 34 |
+
return None
|
backend/uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|