Back to template gallery

Python MCP server

Demonstrates how to convert a Python stdio or SSE-based Model Context Protocol server into an Apify Actor.

Language

python

Tools

mcp

Features

src/main.py

src/server.py

1"""Main entry point for the MCP Server Actor."""
2
3import os
4
5from apify import Actor
6
7from .const import ChargeEvents
8from .server import ProxyServer
9
10# Actor configuration
11STANDBY_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 safe
14HOST = '0.0.0.0' # noqa: S104 - Required for container networking in Apify platform
15PORT = (Actor.is_at_home() and int(os.environ.get('ACTOR_STANDBY_PORT'))) or 5001
16
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 args
20from mcp.client.stdio import StdioServerParameters # noqa: E402
21
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 variables
26)
27
28# 2) For SSE server type, you need to provide the url, you can also specify headers if needed with Authorization
29# from .models import SseServerParameters # noqa: ERA001
30#
31# MCP_SERVER_PARAMS = SseServerParameters( # noqa: ERA001, RUF100
32# url='https://actors-mcp-server.apify.actor/sse', # noqa: ERA001
33# headers={'Authorization': 'YOUR-API-KEY'}, # Optional headers, e.g., for authentication # noqa: ERA001
34# ) # noqa: ERA001, RUF100
35# ------------------------------------------------------------------------------
36
37
38async def main() -> None:
39 """Run the MCP Server Actor.
40
41 This function:
42 1. Initializes the Actor
43 2. Charges for Actor startup
44 3. Creates and starts the proxy server
45 4. Configures charging for MCP operations using Actor.charge
46
47 The proxy server will charge for different MCP operations like:
48 - Tool calls
49 - Prompt operations
50 - Resource access
51 - List operations
52
53 Charging events are defined in .actor/pay_per_event.json
54 """
55 async with Actor:
56 # Initialize and charge for Actor startup
57 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 return
65
66 try:
67 # Create and start the server with charging enabled
68 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 operations
86 # The proxy server will use this to charge for different operations
87 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

  1. 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',
    )
  2. Add any required dependencies to the requirements.txt file (e.g. arxiv-mcp-server).
  3. Deploy to Apify and enable standby mode.
  4. 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 startup
await Actor.charge('tool-call') # Charge for tool execution

To set up the PPE model:

  1. Go to your Actor's Publication settings.
  2. Set the Pricing model to Pay per event.
  3. 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

  1. Stdio Server (StdioServerParameters):
    • Spawns a local process that implements the MCP protocol over stdio.
    • Configure using the command parameter to specify the executable and the args 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
)
  1. 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 the auth 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 functionality
  • create_proxy_server: Creates an MCP server instance that proxies requests
  • charge_mcp_operation: Handles charging for different MCP operations

MCP operations

The proxy supports all standard MCP operations:

  • list_tools(): List available tools
  • call_tool(): Execute a tool with arguments
  • list_prompts(): List available prompts
  • get_prompt(): Get a specific prompt
  • list_resources(): List available resources
  • read_resource(): Read a specific resource

Each operation can be configured for charging in the PPE model.

📚 Resources

Already have a solution in mind?

Sign up for a free Apify account and deploy your code to the platform in just a few minutes! If you want a head start without coding it yourself, browse our Store of existing solutions.