Back to template gallery

Python MCP server

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

Language

python

Tools

mcp

Use cases

Ai

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 TOOL_WHITELIST, 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
17SERVER_NAME = 'arxiv-mcp-server' # Name of the MCP server, without spaces
18
19# EDIT THIS SECTION ------------------------------------------------------------
20# Configuration constants - You need to override these values. You can also pass environment variables if needed.
21# 1) If you are wrapping stdio server type, you need to provide the command and args
22from mcp.client.stdio import StdioServerParameters # noqa: E402
23
24server_type = ServerType.STDIO
25MCP_SERVER_PARAMS = StdioServerParameters(
26 command='uv',
27 args=['run', 'arxiv-mcp-server'],
28 env={'YOUR-ENV_VAR': os.getenv('YOUR-ENV-VAR') or ''}, # Optional environment variables
29)
30
31# 2) If you are connecting to a Streamable HTTP or SSE server, you need to provide the url and headers if needed
32# from .models import RemoteServerParameters # noqa: ERA001
33
34# server_type = ServerType.HTTP # or ServerType.SSE, depending on your server type # noqa: ERA001
35# MCP_SERVER_PARAMS = RemoteServerParameters( # noqa: ERA001, RUF100
36# url='https://your-mcp-server', # noqa: ERA001
37# headers={'Authorization': 'Bearer YOUR-API-KEY'}, # Optional headers, e.g., for authentication # noqa: ERA001
38# ) # noqa: ERA001, RUF100
39# ------------------------------------------------------------------------------
40
41
42async def main() -> None:
43 """Run the MCP Server Actor.
44
45 This function:
46 1. Initializes the Actor
47 2. Charges for Actor startup
48 3. Creates and starts the proxy server
49 4. Configures charging for MCP operations using Actor.charge
50
51 CHARGING STRATEGIES:
52 The template supports multiple charging approaches:
53
54 1. GENERIC MCP CHARGING:
55 - Charge for all tool calls with a flat rate (TOOL_CALL event)
56 - Charge for resource operations (RESOURCE_LIST, RESOURCE_READ)
57 - Charge for prompt operations (PROMPT_LIST, PROMPT_GET)
58 - Charge for tool listing (TOOL_LIST)
59
60 2. DOMAIN-SPECIFIC CHARGING (arXiv example):
61 - Charge different amounts for different tools
62 - search_papers: $0.01 per search
63 - list_papers: $0.001 per listing
64 - download_paper: $0.005 per download
65 - read_paper: $0.02 per paper read
66
67 3. NO CHARGING:
68 - Comment out all charging lines for free service
69
70 Charging events are defined in .actor/pay_per_event.json
71 """
72 async with Actor:
73 # Initialize and charge for Actor startup
74 Actor.log.info('Starting MCP Server Actor')
75 await Actor.charge(ChargeEvents.ACTOR_START.value)
76
77 url = os.environ.get('ACTOR_STANDBY_URL', HOST)
78 if not STANDBY_MODE:
79 msg = (
80 'Actor is not designed to run in the NORMAL mode. Use MCP server URL to connect to the server.\n'
81 f'Connect to {url}/mcp to establish a connection.\n'
82 'Learn more at https://mcp.apify.com/'
83 )
84 Actor.log.info(msg)
85 await Actor.exit(status_message=msg)
86 return
87
88 try:
89 # Create and start the server with charging enabled
90 Actor.log.info('Starting MCP server')
91 Actor.log.info('Add the following configuration to your MCP client to use Streamable HTTP transport:')
92 Actor.log.info(
93 f"""
94 {{
95 "mcpServers": {{
96 "{SERVER_NAME}": {{
97 "url": "{url}/mcp",
98 }}
99 }}
100 }}
101 """
102 )
103 # Pass Actor.charge to enable charging for MCP operations
104 # The proxy server will use this to charge for different operations
105 proxy_server = ProxyServer(
106 SERVER_NAME,
107 MCP_SERVER_PARAMS,
108 HOST,
109 PORT,
110 server_type,
111 actor_charge_function=Actor.charge,
112 tool_whitelist=TOOL_WHITELIST,
113 )
114 await proxy_server.start()
115 except Exception as e:
116 Actor.log.exception(f'Server failed to start: {e}')
117 await Actor.exit()
118 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 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
  • Gateway: Acts as a controlled entry point to MCP servers with charging and authorization logic

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:

    • Using Streamable HTTP transport:
      {
      "mcpServers": {
      "your-server": {
      "url": "https://your-actor.apify.actor/mcp"
      }
      }
      }
    • Note: SSE endpoint serving has been deprecated, but SSE client connections are still supported.

💰 Pricing

This template uses the Pay Per Event (PPE) monetization model, which provides flexible pricing based on defined events.

Charging strategy options

The template supports multiple charging approaches that you can customize based on your needs:

1. Generic MCP charging

Charge for standard MCP operations with flat rates:

{
"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
},
"resource-read": {
"eventTitle": "MCP resource access",
"eventDescription": "Fee for accessing full content or resources",
"eventPriceUsd": 0.0001
},
"prompt-get": {
"eventTitle": "MCP prompt processing",
"eventDescription": "Fee for processing AI prompts",
"eventPriceUsd": 0.0001
}
}

2. Domain-specific charging (arXiv example)

Charge different amounts for different tools based on computational cost:

{
"actor-start": {
"eventTitle": "arXiv MCP server startup",
"eventDescription": "Initial fee for starting the arXiv MCP Server Actor",
"eventPriceUsd": 0.1
},
"search_papers": {
"eventTitle": "arXiv paper search",
"eventDescription": "Fee for searching papers on arXiv",
"eventPriceUsd": 0.001
},
"list_papers": {
"eventTitle": "arXiv paper listing",
"eventDescription": "Fee for listing available papers",
"eventPriceUsd": 0.001
},
"download_paper": {
"eventTitle": "arXiv paper download",
"eventDescription": "Fee for downloading a paper from arXiv",
"eventPriceUsd": 0.001
},
"read_paper": {
"eventTitle": "arXiv paper reading",
"eventDescription": "Fee for reading the full content of a paper",
"eventPriceUsd": 0.01
}
}

3. No charging (free service)

Comment out all charging lines in the code for a free service.

How to implement charging

  1. Define your events in .actor/pay_per_event.json (see examples above). This file is not actually used at Apify platform but serves as a reference.

  2. Enable charging in code by uncommenting the appropriate lines in src/mcp_gateway.py:

    # For generic charging:
    await charge_mcp_operation(actor_charge_function, ChargeEvents.TOOL_CALL)
    # For domain-specific charging:
    if tool_name == 'search_papers':
    await charge_mcp_operation(actor_charge_function, ChargeEvents.SEARCH_PAPERS)
  3. Add custom events to src/const.py if needed:

    class ChargeEvents(str, Enum):
    # Your custom events
    CUSTOM_OPERATION = 'custom-operation'
  4. Set up PPE model on Apify:

    • Go to your Actor's Publication settings
    • Set the Pricing model to Pay per event
    • Add your pricing schema from pay_per_event.json

Authorized tools

This template includes tool authorization - only tools listed in src/const.py can be executed:

Note: The TOOL_WHITELIST dictionary only applies to tools (executable functions). Prompts (like deep-paper-analysis) are handled separately and don't need to be added to this list.

Tool whitelist for MCP server Only tools listed here will be present to the user and allowed to execute. Format of the dictionary: {tool_name: (charge_event_name, default_count)} To add new authorized tools, add an entry with the tool name and its charging configuration.

TOOL_WHITELIST = {
ChargeEvents.SEARCH_PAPERS.value: (ChargeEvents.SEARCH_PAPERS.value, 1),
ChargeEvents.LIST_PAPERS.value: (ChargeEvents.LIST_PAPERS.value, 1),
ChargeEvents.DOWNLOAD_PAPER.value: (ChargeEvents.DOWNLOAD_PAPER.value, 1),
ChargeEvents.READ_PAPER.value: (ChargeEvents.READ_PAPER.value, 1),
}

To add new tools:

  1. Add charge event to ChargeEvents enum
  2. Add tool entry to TOOL_WHITELIST dictionary with format: tool_name: (event_name, count)
  3. Update pricing in pay_per_event.json
  4. Update pricing at Apify platform

Unauthorized tools are blocked with clear error messages.

🔧 How it works

This template implements a MCP gateway that can connect to a stdio-based, Streamable HTTP, or SSE-based MCP server and expose it via 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.

Gateway implementation

The MCP gateway (create_gateway function) handles:

  • Creating a Starlette web server with Streamable HTTP (/mcp) endpoint
  • Managing connections to the underlying MCP server
  • Forwarding requests and responses between clients and the MCP server
  • Handling charging through the actor_charge_function (Actor.charge in Apify Actors)
  • Tool authorization: Only allowing whitelisted tools to execute
  • Access control: Blocking unauthorized tool calls with clear error messages

Key components:

  • create_gateway: Creates an MCP server instance that acts as a gateway
  • charge_mcp_operation: Handles charging for different MCP operations
  • TOOL_WHITELIST: Dictionary mapping tool names to (event_name, count) tuples for authorization and charging

MCP operations

The MCP gateway 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.