Spaces:
Sleeping
Sleeping
File size: 4,810 Bytes
fb07b17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | 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")
|