Skip to main content

Flask integration for Model Context Protocol (MCP)

Project description

Flask-MCP-Plus-Plus

Flask integration for Model Context Protocol (MCP) - a framework for building MCP servers with Flask.

License: apache-2-0 Python Version Flask

Overview

Flask-MCP-Plus provides a simple and intuitive way to create Model Context Protocol (MCP) servers using Flask. It allows developers to easily expose tools, resources, and prompts that can be consumed by MCP clients, facilitating rich interactions between language models and external systems.

Features

  • Easy Integration: Seamless integration with Flask applications
  • Type Safety: Built-in support for type hints and Pydantic validation
  • Tool Support: Define MCP tools with automatic schema generation
  • Resource Management: Handle static and dynamic resources with URI templates
  • Prompt Generation: Create dynamic prompts for AI models
  • JSON Schema Generation: Automatic generation of JSON schemas from Python functions
  • Streaming Support: Streamable HTTP responses for large data

Installation

pip install flask-mcp-plus

Quick Start

Here's a basic example to get you started:

from flask import Flask
from flask_mcp_plus import MCP

app = Flask(__name__)
mcp = MCP()
mcp.init_app(app, "my_mcp_server", __name__)


# Define a simple tool
@mcp.tool
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b


# Define a resource
@mcp.resource("http://example.com/data.json")
def get_data():
    """Return some static data."""
    return {"message": "Hello, MCP!"}


# Define a prompt
@mcp.prompt
def greeting(name: str) -> str:
    """Create a personalized greeting."""
    return f"Hello, {name}!"


if __name__ == "__main__":
    app.run(debug=True)

Use in Client

To use your Flask-MCP-Plus server with an MCP client, you need to configure the client to connect to your server's endpoint.
The configuration format varies depending on the specific MCP client you're using, but generally follows this structure:

{
  "mcpServers": {
    "my_mcp_server": {
      "autoApprove": [],
      "disabled": false,
      "timeout": 60,
      "type": "streamableHttp",
      "url": "http://127.0.0.1:5000/mcp"
    }
  }
}

Core Concepts

Tools

Tools are functions that can be called by MCP clients. They can accept parameters and return structured results.

from flask_mcp_plus import Text, Field
from typing import Annotated


@mcp.tool(
    name="calculate_sum",
    title="Calculate Sum",
    description="Add two floating point numbers",
    icons=[
        {
            "src": "https://example.com/calculator-icon.png",
            "mimeType": "image/png",
            "sizes": ["48x48"]
        }
    ]
)
def add_float(a: Annotated[float, Field(description="The first number")],
              b: Annotated[float, Field(description="The second number")]) -> Text:
    return Text(text=str(a + b))

Resources

Resources provide data that can be fetched by URI. Flask-MCP-Plus supports both static URIs and dynamic URI templates with parameters.

@mcp.resource("file://data/config.json")
def get_config():
    """Return static configuration data."""
    return {"setting1": "value1", "setting2": "value2"}


# Dynamic resource with path parameters
@mcp.resource("file://data/users/{user_id}.json")
def get_user(user_id: str):
    """Return user data by ID."""
    return {"id": user_id, "name": f"User {user_id}"}

Prompts

Prompts are specialized functions that return structured content to guide AI models.

from flask_mcp_plus import Message, Text


@mcp.prompt
def daily_fact() -> Message:
    """Return a daily fact as a message."""
    return Message(
        content=Text(text="The capital of France is Paris.")
    )

Advanced Usage

Custom Output Schema

For tools that return structured data, you can specify a custom JSON schema:

@mcp.tool(
    output_schema={
        "type": "object",
        "properties": {
            "result": {"type": "string"},
            "success": {"type": "boolean"}
        },
        "required": ["result", "success"]
    }
)
def api_call():
    return {
        "result": "Operation completed successfully",
        "success": True
    }

Multiple Content Types

Tools can return multiple content types in a single response:

from flask_mcp_plus import Image, Text


@mcp.tool
def multi_data():
    return [
        Image(data=base64_image_data),
        Text(text="Here's an image and some text")
    ]

Running the Examples

The repository includes comprehensive examples in the src/example/ directory:

  • tools.py - Examples of various tool definitions
  • resources.py - Examples of resource handling
  • prompt.py - Examples of prompt creation

To run an example:

cd src/example
python tools.py

Configuration

The MCP server can be configured with various options:

mcp = MCP()
mcp.init_app(
    app,
    name="my-awesome-server",
    import_name=__name__,
    url_prefix="/mcp",  # Endpoint prefix for MCP routes
    version="1.0.0"
)

Development

Prerequisites

  • Python 3.9+
  • Flask 3+
  • Pydantic 2+

Setup

# Clone the repository
https://github.com/maocatooo/flask-mcp-plus
cd flask-mcp-plus

# Install dependencies
uv sync

License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

Related Projects

Support

If you encounter any issues or have questions, please file an issue on the GitHub repository.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_mcp_plus-0.1.0.tar.gz (9.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_mcp_plus-0.1.0-py3-none-any.whl (7.9 kB view details)

Uploaded Python 3

File details

Details for the file flask_mcp_plus-0.1.0.tar.gz.

File metadata

  • Download URL: flask_mcp_plus-0.1.0.tar.gz
  • Upload date:
  • Size: 9.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.22

File hashes

Hashes for flask_mcp_plus-0.1.0.tar.gz
Algorithm Hash digest
SHA256 fd87c0a61cd9a65351b2038486b21ab5e3ec86d77d3d17877e4c06003647d074
MD5 ace6bcdfcc70f9b29c85d723623d9ed2
BLAKE2b-256 4bcf750d50c8379e42a78f8af7b081c6655208f8824f432f8d7e130503a7294a

See more details on using hashes here.

File details

Details for the file flask_mcp_plus-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: flask_mcp_plus-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.22

File hashes

Hashes for flask_mcp_plus-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7a75d5a528e2e26a94d2af41e4e7a585885d2b4cac85bbdd64642a2e6a7f94fd
MD5 a98e6a143bc31e5afe09d3f6d4b40ed8
BLAKE2b-256 79578599ee1460143392d4a358bef4a73f8047a8dbab23f57a945f50134e20ac

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page