Python MCP server
Create a Model Context Protocol server using Python and FastMCP with Apify Actor integration for pay-per-event monetization.
src/main.py
1"""Main entry point for the MCP Server Actor."""2
3import os4
5from apify import Actor6from fastmcp import FastMCP7
8# Initialize the Apify Actor environment9# This call configures the Actor for its environment and should be called at startup10
11
12def get_server() -> FastMCP:13 """Create an MCP server with implementation details."""14 server = FastMCP('python-mcp-empty', '1.0.0')15
16 @server.tool() # type: ignore[misc]17 def add(a: float, b: float) -> dict:18 """Add two numbers together and return the sum with structured output.19
20 Args:21 a: First number to add22 b: Second number to add23
24 Returns:25 Dictionary with the sum result and structured output26 """27 # Note: We can't await here in sync context, so charging happens in async wrapper28 sum_result = a + b29 structured_content = {30 'result': sum_result,31 'operands': {'a': a, 'b': b},32 'operation': 'addition',33 }34
35 return {36 'type': 'text',37 'text': f'The sum of {a} and {b} is {sum_result}',38 'structuredContent': structured_content,39 }40
41 @server.resource(uri='https://example.com/calculator', name='calculator-info') # type: ignore[misc]42 def calculator_info() -> str:43 """Get information about the calculator service."""44 return 'This is a simple calculator MCP server that can add two numbers together.'45
46 return server47
48
49async def main() -> None:50 """Run the MCP Server Actor.51
52 This function:53 1. Initializes the Actor54 2. Creates and configures the MCP server55 3. Starts the HTTP server with Streamable HTTP transport56 4. Handles MCP requests57 """58 await Actor.init()59
60 # Get port from environment or default to 300061 port = int(os.environ.get('APIFY_CONTAINER_PORT', '3000'))62
63 server = get_server()64
65 try:66 Actor.log.info('Starting MCP server with FastMCP')67
68 # Start the FastMCP server with HTTP transport69 # This starts the server on the specified port and handles MCP protocol messages70 await server.run_http_async(71 host='0.0.0.0', # noqa: S104 - Required for container networking72 port=port,73 )74 except KeyboardInterrupt:75 Actor.log.info('Shutting down server...')76 except Exception as error:77 Actor.log.error(f'Server failed to start: {error}')78 raise79
80
81if __name__ == '__main__':82 import asyncio83
84 asyncio.run(main())MCP server template
A template for creating a Model Context Protocol server using FastMCP on Apify platform.
This template includes a simple example MCP server with:
- An
addtool that adds two numbers together with structured output - A dummy
calculator-inforesource endpoint - Pay Per Event monetization support
How to use
- Modify the server: Edit
src/main.pyto add your own tools and resources - Add new tools: Use the
@server.tool()decorator to register new tools - Add new resources: Use the
@server.resource()decorator to register new resources - Update billing: Configure billing events in
.actor/pay_per_event.jsonand charge for tool calls
The server runs on port 3000 (or APIFY_CONTAINER_PORT if set) and exposes the MCP protocol at the /mcp endpoint.
Running locally
pip install -r requirements.txtAPIFY_META_ORIGIN=STANDBY python -m src
The server will start and listen for MCP requests at http://localhost:3000/mcp
Deploying to Apify
Push your Actor to the Apify platform and configure standby mode.
Then connect to the Actor endpoint with your MCP client: https://me--my-mcp-server.apify.actor/mcp using the Streamable HTTP transport.
Important: When connecting to your deployed MCP server, pass your Apify API token in the Authorization header as a Bearer token:
Authorization: Bearer <YOUR_APIFY_API_TOKEN>
Pay per event
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 with the tool-call event:
{"tool-call": {"eventTitle": "Price for completing a tool call","eventDescription": "Flat fee for completing a tool call.","eventPriceUsd": 0.05}}
In the Actor, trigger the event with:
await Actor.charge(event_name='tool-call')
This approach allows you to programmatically charge users directly from your Actor, covering the costs of execution and related services.
To set up the PPE model for this Actor:
- Configure Pay Per Event: establish the Pay Per Event pricing schema in the Actor's Monetization settings. First, set the Pricing model to
Pay per eventand add the schema. An example schema can be found in .actor/pay_per_event.json.
Resources
Crawlee + BeautifulSoup
Crawl and scrape websites using Crawlee and BeautifulSoup. Start from a given start URLs, and store results to Apify dataset.
Empty Python project
Empty template with basic structure for the Actor with Apify SDK that allows you to easily add your own functionality.
One‑Page HTML Scraper with BeautifulSoup
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.