from raw_function import register_image_upload, upload_image, get_user_id from dotenv import load_dotenv, find_dotenv from mcp.server.fastmcp import FastMCP import requests import os # Create server mcp = FastMCP( name="Linkedin MCP Server", description="A basic MCP server for HTTP client demonstration.", stateless_http=True, # Makes the server treat each HTTP request independently json_response=True, # Allows single JSON responses for non-streaming calls (optimization) port=8000, host="0.0.0.0", ) # Constants LINKEDIN_ACCESS_TOKEN = os.getenv("LINKEDIN_ACCESS_TOKEN") load_dotenv(find_dotenv()) HEADERS = { "Authorization": f"Bearer {LINKEDIN_ACCESS_TOKEN}", "Content-Type": "application/json", } @mcp.tool( name="get_user_info", description="Retrieves the authenticated user's LinkedIn profile information including their ID, name, and other profile details.", ) def get_user_info(): """ Retrieve LinkedIn user profile information using the /userinfo endpoint. Returns: dict: User profile information or None if an error occurs. """ url = "https://api.linkedin.com/v2/userinfo" try: response = requests.get(url, headers=HEADERS) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching user info: {e}") return None @mcp.tool( name="post_content_linkedin", description="Creates a text-only post on LinkedIn with the specified content. The post will be visible to the public.", ) def post_content_linkedin(content: str): """ Share content on LinkedIn. Args: content (str): The text content to post on LinkedIn. Returns: dict: API response or None if an error occurs. """ user_info = get_user_id() if not user_info: print("Failed to retrieve user information.") return None author_urn = f"urn:li:person:{user_info['sub']}" url = "https://api.linkedin.com/v2/ugcPosts" payload = { "author": author_urn, "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": {"text": content}, "shareMediaCategory": "NONE", } }, "visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"}, } try: response = requests.post(url, headers=HEADERS, json=payload) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error posting content: {e}") return None @mcp.tool( name="create_post_links_image", 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.", ) def create_post_links_image(image_path: str, post_text: str): """ Create a post on LinkedIn with the uploaded image. Args: image_path (str): Path to the image file or URL of the image to post. post_text (str): The text content to accompany the image in the post. Returns: None: Prints success or error message. """ # Step 1: Register image upload upload_url, image_urn = register_image_upload() if not (upload_url and image_urn): print("Failed to register image upload.") return # Step 2: Upload the image if not upload_image(upload_url, image_path): print("Failed to upload image.") return # Step 3: Create the post user_info = get_user_info() if not user_info: print("Failed to retrieve user information.") return url = "https://api.linkedin.com/v2/ugcPosts" payload = { "author": f"urn:li:person:{user_info['sub']}", "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": {"text": post_text}, "shareMediaCategory": "IMAGE", "media": [ { "status": "READY", "media": image_urn, } ], } }, "visibility": {"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"}, } response = requests.post(url, headers=HEADERS, json=payload) if response.status_code == 201: print("Post created successfully.") else: print(f"Error creating post: {response.status_code}") # 6. Make the server runnable if __name__ == "__main__": print(f"Starting MCP server '{mcp.name}'...") # This uses the built-in server runner from the MCP SDK. mcp.run(transport="streamable-http")