server.py•3.48 kB
#!/usr/bin/env python3
"""
MCP Server with fetchRecommendations function
Supports both local (STDIO) and remote (HTTP) deployment
"""
import asyncio
import argparse
import os
import requests
from fastmcp import FastMCP
# Initialize the MCP server
mcp = FastMCP("TabolaAPI")
@mcp.tool()
def fetchRecommendations(publisher_name: str, api_key: str) -> str:
"""
Fetch recommendations for a given publisher using their API key.
Args:
publisher_name (str): The name of the publisher
api_key (str): The API key for authentication
Returns:
str: Recommendations data from Taboola API
"""
try:
# Build the Taboola API URL
url = f"https://api.taboola.com/1.2/json/{publisher_name}/recommendations.get"
# API parameters
params = {
"app.type": "web",
"app.apikey": api_key,
"placement.rec-count": "4",
"source.type": "text",
"source.id": "/news/local/Car-Slams-Into-Building-In-Queens-Boulevard-New-York-SUV-Evac-326416261.html",
"source.url": "http://www.nbcnewyork.com/news/local/Car-Slams-Into-Building-In-Queens-Boulevard-New-York-SUV-Evac-326416261.html",
"user.session": "init"
}
# Make the API request
response = requests.get(url, params=params)
# Check if the request was successful
if response.status_code == 200:
return response.text
else:
return f"Error: API request failed with status code {response.status_code}. Response: {response.text}"
except requests.exceptions.RequestException as e:
return f"Error: Failed to make API request. {str(e)}"
except Exception as e:
return f"Error: Unexpected error occurred. {str(e)}"
@mcp.tool()
def health() -> str:
"""
Health check endpoint for monitoring services
Returns:
str: Health status message
"""
return "OK - Taboola MCP Server is running"
def main():
"""
Run the MCP server in either local (STDIO) or remote (HTTP) mode
"""
parser = argparse.ArgumentParser(description="Taboola MCP Server")
parser.add_argument(
"--mode",
choices=["local", "remote"],
default="local",
help="Server mode: 'local' for STDIO transport, 'remote' for HTTP server (default: local)"
)
parser.add_argument(
"--host",
default="0.0.0.0",
help="Host to bind to in remote mode (default: 0.0.0.0)"
)
parser.add_argument(
"--port",
type=int,
default=8000,
help="Port to bind to in remote mode (default: 8000)"
)
args = parser.parse_args()
# Support environment variables for configuration
mode = os.getenv("MCP_MODE", args.mode)
host = os.getenv("MCP_HOST", args.host)
port = int(os.getenv("MCP_PORT", str(args.port)))
print(f"Starting MCP server in {mode} mode...")
if mode == "remote":
print(f"Remote server will be available at: http://{host}:{port}")
print("Connect using HTTP transport with the above URL")
# Run as HTTP server
mcp.run(transport="http", host=host, port=port)
else:
print("Local server using STDIO transport")
print("Connect using STDIO transport for local connections")
# Run as STDIO server (default)
mcp.run()
if __name__ == "__main__":
main()