Python MCP server
An MCP server that gives AI assistants like Claude and Cursor your own tools, with built-in pay-per-event billing.
my_actor/main.py
my_actor/__main__.py
1"""Main entry point for the MCP Server Actor."""2
3import os4
5import uvicorn6from apify import Actor7from fastmcp import FastMCP8from starlette.requests import Request9from starlette.responses import PlainTextResponse10
11
12def get_server() -> FastMCP:13 """Create an MCP server with tools and resources."""14 server = FastMCP('python-mcp-empty', '1.0.0')15
16 @server.custom_route('/', methods=['GET'])17 async def readiness_probe(_request: Request) -> PlainTextResponse:18 """Answer the readiness probe that the platform sends before it routes requests to the run."""19 return PlainTextResponse('ok')20
21 @server.tool()22 def add(a: float, b: float) -> dict:23 """Add two numbers together and return the sum."""24 result = a + b25 return {26 'type': 'text',27 'text': f'The sum of {a} and {b} is {result}',28 'structuredContent': {29 'result': result,30 'operands': {'a': a, 'b': b},31 'operation': 'addition',32 },33 }34
35 @server.resource(uri='https://example.com/calculator', name='calculator-info')36 def calculator_info() -> str:37 """Get information about the calculator service."""38 return 'This is a simple calculator MCP server that can add two numbers together.'39
40 return server41
42
43async def main() -> None:44 """Run the MCP Server Actor."""45 await Actor.init()46
47 port = int(os.environ.get('APIFY_CONTAINER_PORT', '3000'))48
49 server = get_server()50
51 # Stateless mode: each request gets a fresh transport and nothing is kept in memory between requests.52 # The platform starts more runs under load and sends each request to any of them, so a session kept53 # in the memory of one run would be missing in the others, and the client would get "Session not found".54 app = server.http_app(transport='streamable-http', stateless_http=True)55
56 try:57 Actor.log.info(f'Starting MCP server on port {port}')58 config = uvicorn.Config(app, host='0.0.0.0', port=port, log_level='info') # noqa: S10459 await uvicorn.Server(config).serve()60 except KeyboardInterrupt:61 Actor.log.info('Shutting down...')62 except Exception as e:63 Actor.log.error(f'Server failed: {e}')64 raiseA 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
- 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.
The server runs in stateless HTTP mode , so it keeps no MCP session in memory. The platform can start more runs of your Actor under load and send each request to any of them. Keep it stateless: store anything that must outlive a request in a dataset or key-value store .
The Dockerfile also sets FASTMCP_ENABLE_SUBSCRIPTIONS_LISTEN=false, so the server refuses the long-lived subscriptions/listen stream of the 2026-07-28 MCP protocol. An open stream can keep a run alive after the client is gone, and you pay for the idle run.
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
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>
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 pay_per_event.json.
Python site crawler (Crawlee + BeautifulSoup)
A crawler that follows links and gets data from static pages, with Crawlee handling retries and request queues. Uses BeautifulSoup, Python's most popular HTML parser. Can't run client-side JavaScript.
Empty Python Actor
An Actor with the Apify SDK set up, so you can build any tool you need.
Python one-page scraper (BeautifulSoup)
A scraper that gets data from one web page with BeautifulSoup. The simplest way to start scraping.
Empty Python Actor (uv)
An Actor with the Apify SDK set up and dependencies managed by the uv package manager, so you can build any tool you need.
Python site crawler (BeautifulSoup)
A lightweight crawler that follows links and gets data from static pages with BeautifulSoup. Good for blogs, news, or product listings, but it can't run client-side JavaScript.
Python browser crawler (Playwright)
A crawler that uses a real browser through Playwright, so it gets data HTTP crawlers miss. Good for social feeds, dashboards, or single-page apps.