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 .models import ServerType
9from .server import ProxyServer
10
11# Actor configuration
12STANDBY_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 safe
15HOST = '0.0.0.0' # noqa: S104 - Required for container networking at Apify platform
16PORT = (Actor.is_at_home() and int(os.environ.get('ACTOR_STANDBY_PORT') or '5001')) or 5001
17
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 args
21from mcp.client.stdio import StdioServerParameters # noqa: E402
22
23server_type = ServerType.STDIO
24MCP_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 variables
28)
29
30# 2) If you are wrapping Streamable HTTP or SSE server type, you need to provide the url and headers if needed
31# from .models import RemoteServerParameters # noqa: ERA001
32
33# server_type = ServerType.HTTP # or ServerType.SSE, depending on your server type # noqa: ERA001
34# MCP_SERVER_PARAMS = RemoteServerParameters( # noqa: ERA001, RUF100
35# url='https://mcp.apify.com', # noqa: ERA001
36# headers={'Authorization': 'Bearer YOUR-API-KEY'}, # Optional headers, e.g., for authentication # noqa: ERA001
37# ) # noqa: ERA001, RUF100
38# ------------------------------------------------------------------------------
39
40
41async def main() -> None:
42 """Run the MCP Server Actor.
43
44 This function:
45 1. Initializes the Actor
46 2. Charges for Actor startup
47 3. Creates and starts the proxy server
48 4. Configures charging for MCP operations using Actor.charge
49
50 The proxy server will charge for different MCP operations like:
51 - Tool calls
52 - Prompt operations
53 - Resource access
54 - List operations
55
56 Charging events are defined in .actor/pay_per_event.json
57 """
58 async with Actor:
59 # Initialize and charge for Actor startup
60 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 return
68
69 try:
70 # Create and start the server with charging enabled
71 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 operations
89 # The proxy server will use this to charge for different operations
90 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:

✨ 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

  1. Configure your MCP server in src/main.py:

    # For stdio server:
    server_type = ServerType.STDIO
    MCP_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',
    # )
  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:

💰 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 startup
await Actor.charge('tool-call', 1) # 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 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

  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:

server_type = ServerType.STDIO
MCP_SERVER_PARAMS = StdioServerParameters(
command='uv',
args=['run', 'arxiv-mcp-server'],
env={'YOUR_ENV_VAR': os.getenv('YOUR-ENV-VAR')}, # Optional environment variables
)
  1. 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 the auth parameter for additional authentication mechanisms.

Example:

server_type = ServerType.HTTP
MCP_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 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.