Back to template gallery

Python MCP server

Create a Model Context Protocol server using Python and FastMCP with Apify Actor integration for pay-per-event monetization.

Language

python

Tools

mcp

Use cases

Ai

Features

src/main.py

1"""Main entry point for the MCP Server Actor."""
2
3import os
4
5from apify import Actor
6from fastmcp import FastMCP
7
8# Initialize the Apify Actor environment
9# This call configures the Actor for its environment and should be called at startup
10
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 add
22 b: Second number to add
23
24 Returns:
25 Dictionary with the sum result and structured output
26 """
27 # Note: We can't await here in sync context, so charging happens in async wrapper
28 sum_result = a + b
29 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 server
47
48
49async def main() -> None:
50 """Run the MCP Server Actor.
51
52 This function:
53 1. Initializes the Actor
54 2. Creates and configures the MCP server
55 3. Starts the HTTP server with Streamable HTTP transport
56 4. Handles MCP requests
57 """
58 await Actor.init()
59
60 # Get port from environment or default to 3000
61 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 transport
69 # This starts the server on the specified port and handles MCP protocol messages
70 await server.run_http_async(
71 host='0.0.0.0', # noqa: S104 - Required for container networking
72 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 raise
79
80
81if __name__ == '__main__':
82 import asyncio
83
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 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.

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 .actor/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.