Back to template gallery

Python MCP server

An MCP server that gives AI assistants like Claude and Cursor your own tools, with built-in pay-per-event billing.

Language

python

Tools

mcp

Use cases

Ai

Integration

my_actor/main.py

my_actor/__main__.py

1"""Main entry point for the MCP Server Actor."""
2
3import os
4
5import uvicorn
6from apify import Actor
7from fastmcp import FastMCP
8from starlette.requests import Request
9from starlette.responses import PlainTextResponse
10
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 + b
25 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 server
41
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 kept
53 # 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: S104
59 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 raise

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 add tool that adds two numbers together with structured output
  • A dummy calculator-info resource endpoint
  • Pay Per Event monetization  support

How to use

  1. Modify the server: Edit src/main.py to add your own tools and resources
  2. Add new tools: Use the @server.tool() decorator to register new tools
  3. Add new resources: Use the @server.resource() decorator to register new resources
  4. Update billing: Configure billing events in .actor/pay_per_event.json and 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.

Running locally

pip install -r requirements.txt
APIFY_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 event and add the schema. An example schema can be found in pay_per_event.json.

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.