Python MCP Server Template
Pricing
from $0.01 / 1,000 results
Python MCP Server Template
"🚀 Python MCP Server Template provides a ready-to-use framework for quickly setting up Minecraft server backends. Lightweight, modular, and customizable, it supports plugin integration, player management, and real-time server monitoring, making server deployment fast and hassle-free.
Pricing
from $0.01 / 1,000 results
Rating
0.0
(0)
Developer

Ellustar
Actor stats
0
Bookmarked
2
Total users
1
Monthly active users
3 days ago
Last modified
Categories
Share
🚀 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
- Session management: Automatic session timeout and cleanup for idle connections (see Session management challenges for details)
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.txtfile (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"}}}
- Note: SSE endpoint serving has been deprecated, but SSE client connections are still supported.
- Using Streamable HTTP transport:
💰 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:
{"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:
{"search_papers": {"eventTitle": "arXiv paper search","eventDescription": "Fee for searching papers on arXiv using the search_papers tool.","eventPriceUsd": 0.001},"list_papers": {"eventTitle": "arXiv paper listing","eventDescription": "Fee for listing available papers using the list_papers tool.","eventPriceUsd": 0.001},"download_paper": {"eventTitle": "arXiv paper download","eventDescription": "Fee for downloading a paper from arXiv using the download_paper tool.","eventPriceUsd": 0.01},"read_paper": {"eventTitle": "arXiv paper reading","eventDescription": "Fee for reading the full content of a paper using the read_paper tool.","eventPriceUsd": 0.01}}
3. No charging (free service)
Comment out all charging lines in the code for a free service.
How to implement charging
-
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. -
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) -
Add custom events to
src/const.pyif needed:class ChargeEvents(str, Enum):# Your custom eventsCUSTOM_OPERATION = 'custom-operation' -
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:
- Add charge event to
ChargeEventsenum - Add tool entry to
TOOL_WHITELISTdictionary with format:tool_name: (event_name, count) - Update pricing in
pay_per_event.json - 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
- Stdio server (
StdioServerParameters):- Spawns a local process that implements the MCP protocol over stdio.
- Configure using the
commandparameter to specify the executable and theargsparameter for additional arguments. - Optionally, use the
envparameter 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
urlparameter to specify the server's endpoint. - Set the appropriate
server_type(ServerType.HTTP or ServerType.SSE). - Optionally, use the
headersparameter to include custom headers (e.g., for authentication) and theauthparameter 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.
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.chargein 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 gatewaycharge_mcp_operation: Handles charging for different MCP operationsTOOL_WHITELIST: Dictionary mapping tool names to (event_name, count) tuples for authorization and chargingProxyServer: Main server class with session management and timeout handlingSESSION_TIMEOUT_SECS: Configurable timeout for idle session termination
MCP operations
The MCP gateway 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.
Session management challenges
MCP connections may not properly close when clients disconnect, keeping containers alive indefinitely.
- Containers remain running even after client disconnection
- Setting
statelessmode andjson_response=truedoesn't resolve the issue - Only manual session deletion via
DELETE /mcpproperly terminates connections
Workaround:
The template implements automatic session cleanup using internal DELETE requests after a configurable timeout (SESSION_TIMEOUT_SECS = 300 seconds). This ensures containers are properly terminated when idle.
This is a temporary solution until the MCP specification or client implementations provide a more robust mechanism for session management.
📚 Resources
- What is Anthropic's Model Context Protocol?
- How to use MCP with Apify Actors
- Apify MCP server
- Apify MCP server documentation
- Apify MCP client
- MCP Servers hosted at Apify
- Model Context Protocol documentation
- Apify SDK documentation
Getting started
For complete information see this article. In short, you will:
- Build the Actor
- Run the Actor
Pull the Actor for local development
If you would like to develop locally, you can pull the existing Actor from Apify console using Apify CLI:
-
Install
apify-cliUsing Homebrew
$brew install apify-cliUsing NPM
$npm -g install apify-cli -
Pull the Actor by its unique
<ActorId>, which is one of the following:- unique name of the Actor to pull (e.g. "apify/hello-world")
- or ID of the Actor to pull (e.g. "E2jjCZBezvAZnX8Rb")
You can find both by clicking on the Actor title at the top of the page, which will open a modal containing both Actor unique name and Actor ID.
This command will copy the Actor into the current directory on your local machine.
$apify pull <ActorId>
Documentation reference
To learn more about Apify and Actors, take a look at the following resources: