Python MCP server
Demonstrates how to convert a Python stdio or SSE-based Model Context Protocol server into an Apify Actor.
src/main.py
src/server.py
1"""Main entry point for the MCP Server Actor."""2
3import os4
5from apify import Actor6
7from .const import ChargeEvents8from .server import ProxyServer9
10# Actor configuration11STANDBY_MODE = os.environ.get('APIFY_META_ORIGIN') == 'STANDBY'12# Bind to all interfaces (0.0.0.0) as this is running in a containerized environment (Apify Actor)13# The container's network is isolated, so this is safe14HOST = '0.0.0.0' # noqa: S104 - Required for container networking in Apify platform15PORT = (Actor.is_at_home() and int(os.environ.get('ACTOR_STANDBY_PORT'))) or 500116
17# EDIT THIS SECTION ------------------------------------------------------------18# Configuration constants - You need to override these values. You can also pass environment variables if needed.19# 1) For stdio server type, you need to provide the command and args20from mcp.client.stdio import StdioServerParameters # noqa: E40221
22MCP_SERVER_PARAMS = StdioServerParameters(23 command='uv',24 args=['run', 'arxiv-mcp-server'],25 env={'YOUR-ENV_VAR', os.getenv('YOUR-ENV-VAR')}, # Optional environment variables26)27
28# 2) For SSE server type, you need to provide the url, you can also specify headers if needed with Authorization29# from .models import SseServerParameters # noqa: ERA00130#31# MCP_SERVER_PARAMS = SseServerParameters( # noqa: ERA001, RUF10032# url='https://actors-mcp-server.apify.actor/sse', # noqa: ERA00133# headers={'Authorization': 'YOUR-API-KEY'}, # Optional headers, e.g., for authentication # noqa: ERA00134# ) # noqa: ERA001, RUF10035# ------------------------------------------------------------------------------36
37
38async def main() -> None:39 """Run the MCP Server Actor.40
41 This function:42 1. Initializes the Actor43 2. Charges for Actor startup44 3. Creates and starts the proxy server45 4. Configures charging for MCP operations using Actor.charge46
47 The proxy server will charge for different MCP operations like:48 - Tool calls49 - Prompt operations50 - Resource access51 - List operations52
53 Charging events are defined in .actor/pay_per_event.json54 """55 async with Actor:56 # Initialize and charge for Actor startup57 Actor.log.info('Starting MCP Server Actor')58 await Actor.charge(ChargeEvents.ACTOR_START.value)59
60 if not STANDBY_MODE:61 msg = 'This Actor is not meant to be run directly. It should be run in standby mode.'62 Actor.log.error(msg)63 await Actor.exit(status_message=msg)64 return65
66 try:67 # Create and start the server with charging enabled68 url = os.environ.get('ACTOR_STANDBY_URL', HOST)69 Actor.log.info('Starting MCP proxy server')70 Actor.log.info(f' - proxy server host: {os.environ.get("ACTOR_STANDBY_URL", HOST)}')71 Actor.log.info(f' - proxy server port: {PORT}')72
73 Actor.log.info('Put this in your client config:')74 Actor.log.info(75 f"""76 {{77 "mcpServers": {{78 "arxiv-mcp-server": {{79 "url": "{url}/sse"80 }}81 }}82 }}83 """84 )85 # Pass Actor.charge to enable charging for MCP operations86 # The proxy server will use this to charge for different operations87 proxy_server = ProxyServer(MCP_SERVER_PARAMS, HOST, PORT, actor_charge_function=Actor.charge)88 await proxy_server.start()89 except Exception as e:90 Actor.log.exception(f'Server failed to start: {e}')91 await Actor.exit()92 raise
🚀 Python MCP Server Template
A Python template for deploying and monetizing a Model Context Protocol (MCP) server in the cloud using the Apify platform.
This template enables you to:
- Deploy any Python stdio MCP server (e.g., ArXiv MCP Server), or connect to an existing remote MCP server using SSE transport
- Expose your MCP server via Server-Sent Events (SSE) transport
- Monetize your server using Apify's Pay Per Event (PPE) model
✨ Features
- Support for both stdio-based and SSE-based MCP servers
- Built-in charging: Integrated Pay Per Event (PPE) for:
- Server startup
- Tool calls
- Resource access
- Prompt operations
- List operations
- Easy configuration: Simple setup through environment variables and configuration files
Quick Start
- Configure your MCP server in
src/main.py
:# For stdio server:MCP_SERVER_PARAMS = StdioServerParameters(command='your-command',args=['your', 'args'],)# For SSE server:MCP_SERVER_PARAMS = SseServerParameters(url='your-server-url',) - Add any required dependencies to the
requirements.txt
file (e.g. arxiv-mcp-server). - Deploy to Apify and enable standby mode.
- Connect using an MCP client:
{"mcpServers": {"your-server": {"url": "https://your-actor.apify.actor/sse"}}}
💰 Pricing
This template uses the Pay Per Event (PPE) monetization model, which provides flexible pricing based on defined events.
To charge users, define events in JSON format and save them on the Apify platform. Here is an example schema:
{"actor-start": {"eventTitle": "MCP server startup","eventDescription": "Initial fee for starting the Actor MCP Server","eventPriceUsd": 0.1},"tool-call": {"eventTitle": "MCP tool call","eventDescription": "Fee for executing MCP tools","eventPriceUsd": 0.05}}
In the Actor, trigger events with:
await Actor.charge('actor-start') # Charge for server startupawait Actor.charge('tool-call') # Charge for tool execution
To set up the PPE model:
- Go to your Actor's Publication settings.
- Set the Pricing model to
Pay per event
. - Add the pricing schema (see .actor/pay_per_event.json for a complete example).
🔧 How It Works
This template implements a proxy server that can connect to either a stdio-based or SSE-based MCP server and expose it via SSE transport. Here's how it works:
Server types
- Stdio Server (
StdioServerParameters
):- Spawns a local process that implements the MCP protocol over stdio.
- Configure using the
command
parameter to specify the executable and theargs
parameter for additional arguments. - Optionally, use the
env
parameter to pass environment variables to the process.
Example:
MCP_SERVER_PARAMS = StdioServerParameters(command='uv',args=['run', 'arxiv-mcp-server'],env={'YOUR_ENV_VAR', os.getenv('YOUR-ENV-VAR')}, # Optional environment variables)
- SSE Server (
SseServerParameters
):- Connects to a remote MCP server via SSE transport.
- Configure using the
url
parameter to specify the server's endpoint. - Optionally, use the
headers
parameter to include custom headers (e.g., for authentication) and theauth
parameter for additional authentication mechanisms.
Example:
MCP_SERVER_PARAMS = SseServerParameters(url='https://mcp.apify.com/sse',headers={'Authorization': os.getenv('YOUR-AUTH-TOKEN')}, # Replace with your authentication token)
- Tips:
- Ensure the remote server supports SSE transport and is accessible from the Actor's environment.
- Use environment variables to securely store sensitive information like tokens or API keys.
Environment variables:
Environment variables can be securely stored and managed at the Actor level on the Apify platform. These variables are automatically injected into the Actor's runtime environment, allowing you to:
- Keep sensitive information like API keys secure.
- Simplify configuration by avoiding hardcoded values in your code.
Proxy implementation
The proxy server (ProxyServer
class) handles:
- Creating a Starlette web server with SSE endpoints (
/sse
and/messages/
) - Managing connections to the underlying MCP server
- Forwarding requests and responses between clients and the MCP server
- Handling charging through the
actor_charge_function
Key components:
ProxyServer
: Main class that manages the proxy functionalitycreate_proxy_server
: Creates an MCP server instance that proxies requestscharge_mcp_operation
: Handles charging for different MCP operations
MCP operations
The proxy supports all standard MCP operations:
list_tools()
: List available toolscall_tool()
: Execute a tool with argumentslist_prompts()
: List available promptsget_prompt()
: Get a specific promptlist_resources()
: List available resourcesread_resource()
: Read a specific resource
Each operation can be configured for charging in the PPE model.
📚 Resources
Start with Python
Scrape single page with provided URL with HTTPX and extract data from page's HTML with Beautiful Soup.
Starter
BeautifulSoup
Example of a web scraper that uses Python HTTPX to scrape HTML from URLs provided on input, parses it using BeautifulSoup and saves results to storage.
Playwright + Chrome
Crawler example that uses headless Chrome driven by Playwright to scrape a website. Headless browsers render JavaScript and can help when getting blocked.
Selenium + Chrome
Scraper example built with Selenium and headless Chrome browser to scrape a website and save the results to storage. A popular alternative to Playwright.
Empty Python project
Empty template with basic structure for the Actor with Apify SDK that allows you to easily add your own functionality.
Standby Python project
Template with basic structure for an Actor using Standby mode that allows you to easily add your own functionality.
Starter