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 .models import ServerType9from .server import ProxyServer10
11# Actor configuration12STANDBY_MODE = os.environ.get('APIFY_META_ORIGIN') == 'STANDBY'13# Bind to all interfaces (0.0.0.0) as this is running in a containerized environment (Apify Actor)14# The container's network is isolated, so this is safe15HOST = '0.0.0.0' # noqa: S104 - Required for container networking at Apify platform16PORT = (Actor.is_at_home() and int(os.environ.get('ACTOR_STANDBY_PORT') or '5001')) or 500117
18# EDIT THIS SECTION ------------------------------------------------------------19# Configuration constants - You need to override these values. You can also pass environment variables if needed.20# 1) If you are wrapping stdio server type, you need to provide the command and args21from mcp.client.stdio import StdioServerParameters # noqa: E40222
23server_type = ServerType.STDIO24MCP_SERVER_PARAMS = StdioServerParameters(25 command='uv',26 args=['run', 'arxiv-mcp-server'],27 env={'YOUR-ENV_VAR': os.getenv('YOUR-ENV-VAR') or ''}, # Optional environment variables28)29
30# 2) If you are wrapping Streamable HTTP or SSE server type, you need to provide the url and headers if needed31# from .models import RemoteServerParameters # noqa: ERA00132
33# server_type = ServerType.HTTP # or ServerType.SSE, depending on your server type # noqa: ERA00134# MCP_SERVER_PARAMS = RemoteServerParameters( # noqa: ERA001, RUF10035# url='https://mcp.apify.com', # noqa: ERA00136# headers={'Authorization': 'Bearer YOUR-API-KEY'}, # Optional headers, e.g., for authentication # noqa: ERA00137# ) # noqa: ERA001, RUF10038# ------------------------------------------------------------------------------39
40
41async def main() -> None:42 """Run the MCP Server Actor.43
44 This function:45 1. Initializes the Actor46 2. Charges for Actor startup47 3. Creates and starts the proxy server48 4. Configures charging for MCP operations using Actor.charge49
50 The proxy server will charge for different MCP operations like:51 - Tool calls52 - Prompt operations53 - Resource access54 - List operations55
56 Charging events are defined in .actor/pay_per_event.json57 """58 async with Actor:59 # Initialize and charge for Actor startup60 Actor.log.info('Starting MCP Server Actor')61 await Actor.charge(ChargeEvents.ACTOR_START.value)62
63 if not STANDBY_MODE:64 msg = 'This Actor is not meant to be run directly. It should be run in standby mode.'65 Actor.log.error(msg)66 await Actor.exit(status_message=msg)67 return68
69 try:70 # Create and start the server with charging enabled71 url = os.environ.get('ACTOR_STANDBY_URL', HOST)72 Actor.log.info('Starting MCP server')73 Actor.log.info(f' - proxy server host: {os.environ.get("ACTOR_STANDBY_URL", HOST)}')74 Actor.log.info(f' - proxy server port: {PORT}')75
76 Actor.log.info('Add the following configuration to your MCP client to use Streamable HTTP transport:')77 Actor.log.info(78 f"""79 {{80 "mcpServers": {{81 "arxiv-mcp-server": {{82 "url": "{url}/mcp",83 }}84 }}85 }}86 """87 )88 # Pass Actor.charge to enable charging for MCP operations89 # The proxy server will use this to charge for different operations90 proxy_server = ProxyServer(MCP_SERVER_PARAMS, HOST, PORT, server_type, actor_charge_function=Actor.charge)91 await proxy_server.start()92 except Exception as e:93 Actor.log.exception(f'Server failed to start: {e}')94 await Actor.exit()95 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 Streamable HTTP or SSE transport
- Expose your MCP server via legacy Server-Sent Events (SSE) or Streamable HTTP transport
- Monetize your server using Apify's Pay Per Event (PPE) model
✨ Features
- Support for stdio-based, Streamable HTTP, 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:server_type = ServerType.STDIOMCP_SERVER_PARAMS = StdioServerParameters(command='your-command',args=['your', 'args'],)# For HTTP or SSE server:# server_type = ServerType.HTTP # or ServerType.SSE# MCP_SERVER_PARAMS = RemoteServerParameters(# 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:
- Using Streamable HTTP transport:
{"mcpServers": {"your-server": {"url": "https://your-actor.apify.actor/mcp"}}}
- The template also supports legacy SSE transport via the
/sse
endpoint.
- Using Streamable HTTP transport:
💰 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', 1) # Charge for server startupawait Actor.charge('tool-call', 1) # 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 a stdio-based, Streamable HTTP, or SSE-based MCP server and expose it via legacy Server-Sent Events (SSE) transport or Streamable HTTP 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:
server_type = ServerType.STDIOMCP_SERVER_PARAMS = StdioServerParameters(command='uv',args=['run', 'arxiv-mcp-server'],env={'YOUR_ENV_VAR': os.getenv('YOUR-ENV-VAR')}, # Optional environment variables)
- Remote Server (
RemoteServerParameters
):- Connects to a remote MCP server via HTTP or SSE transport.
- Configure using the
url
parameter to specify the server's endpoint. - Set the appropriate
server_type
(ServerType.HTTP or ServerType.SSE). - Optionally, use the
headers
parameter to include custom headers (e.g., for authentication) and theauth
parameter for additional authentication mechanisms.
Example:
server_type = ServerType.HTTPMCP_SERVER_PARAMS = RemoteServerParameters(url='https://mcp.apify.com',headers={'Authorization': 'Bearer YOUR-API-KEY'}, # Replace with your authentication token)
Note: SSE transport is also supported by setting server_type = ServerType.SSE
.
- Tips:
- Ensure the remote server supports the transport type you're using 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 legacy SSE (
/sse
and/messages/
) and Streamable HTTP (/mcp
) endpoints - 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.
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.