mseep-fastapi-mcp-sse 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mseep-fastapi-mcp-sse
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: A working example to create a FastAPI server with SSE-based MCP support
5
- Home-page:
6
- Author: mseep
7
5
  Author-email: mseep <support@skydeck.ai>
8
- Maintainer-email: mseep <support@skydeck.ai>
9
- Requires-Python: >=3.6
10
- Description-Content-Type: text/markdown
6
+ Requires-Python: >=3.13
7
+ Description-Content-Type: text/plain
11
8
  License-File: LICENSE
12
9
  Requires-Dist: fastapi>=0.115.11
13
10
  Requires-Dist: httpx>=0.28.1
14
11
  Requires-Dist: mcp[cli]>=1.3.0
15
12
  Requires-Dist: unicorn>=2.1.3
16
- Dynamic: author
17
13
  Dynamic: license-file
18
- Dynamic: requires-python
19
14
 
20
- # Package managed by MseeP.ai
15
+ Package managed by MseeP.ai
@@ -0,0 +1,181 @@
1
+ # FastAPI MCP SSE
2
+
3
+ <p align="center">
4
+ <strong>English</strong> | <a href="/README.zh-CN.md">简体中文</a>
5
+ </p>
6
+
7
+ A Server-Sent Events (SSE) implementation using FastAPI framework with [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) integration.
8
+
9
+ ## What is MCP?
10
+
11
+ The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) is an open standard that enables AI models to interact with external tools and data sources. MCP solves several key challenges in AI development:
12
+
13
+ - **Context limitations**: Allows models to access up-to-date information beyond their training data
14
+ - **Tool integration**: Provides a standardized way for models to use external tools and APIs
15
+ - **Interoperability**: Creates a common interface between different AI models and tools
16
+ - **Extensibility**: Makes it easy to add new capabilities to AI systems without retraining
17
+
18
+ This project demonstrates how to implement MCP using Server-Sent Events (SSE) in a FastAPI web application.
19
+
20
+ ## Description
21
+
22
+ This project demonstrates how to implement Server-Sent Events (SSE) using the FastAPI framework while integrating Model Context Protocol (MCP) functionality. The key feature is the seamless integration of MCP's SSE capabilities within a full-featured FastAPI web application that includes custom routes.
23
+
24
+ ## Features
25
+
26
+ - Server-Sent Events (SSE) implementation with MCP
27
+ - FastAPI framework integration with custom routes
28
+ - Unified web application with both MCP and standard web endpoints
29
+ - Customizable route structure
30
+ - Clean separation of concerns between MCP and web functionality
31
+
32
+ ## Architecture
33
+
34
+ This project showcases a modular architecture that:
35
+
36
+ 1. Integrates MCP SSE endpoints (`/sse` and `/messages/`) into a FastAPI application
37
+ 2. Provides standard web routes (`/`, `/about`, `/status`, `/docs`, `/redoc`)
38
+ 3. Demonstrates how to maintain separation between MCP functionality and web routes
39
+
40
+ ## Installation & Usage Options
41
+
42
+ ### Prerequisites
43
+
44
+ Install [UV Package Manager](https://docs.astral.sh/uv/) - A fast Python package installer written in Rust:
45
+
46
+ ```cmd
47
+ powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
48
+ ```
49
+
50
+ ### Option 1: Quick Run Without Installation
51
+
52
+ Run the application directly without cloning the repository using UV's execution tool:
53
+
54
+ ```cmd
55
+ uvx --from git+https://github.com/panz2018/fastapi_mcp_sse.git start
56
+ ```
57
+
58
+ ### Option 2: Full Installation
59
+
60
+ #### Create Virtual Environment
61
+
62
+ Create an isolated Python environment for the project:
63
+
64
+ ```cmd
65
+ uv venv
66
+ ```
67
+
68
+ #### Activate Virtual Environment
69
+
70
+ Activate the virtual environment to use it:
71
+
72
+ ```cmd
73
+ .venv\Scripts\activate
74
+ ```
75
+
76
+ #### Install Dependencies
77
+
78
+ Install all required packages:
79
+
80
+ ```cmd
81
+ uv pip install -r pyproject.toml
82
+ ```
83
+
84
+ #### Start the Integrated Server
85
+
86
+ Launch the integrated FastAPI server with MCP SSE functionality:
87
+
88
+ ```cmd
89
+ python src/server.py
90
+ ```
91
+
92
+ or
93
+
94
+ ```cmd
95
+ uv run start
96
+ ```
97
+
98
+ ### Available Endpoints
99
+
100
+ After starting the server (using either Option 1 or Option 2), the following endpoints will be available:
101
+
102
+ - Main server: http://localhost:8000
103
+ - Standard web routes:
104
+ - Home page: http://localhost:8000/
105
+ - About page: http://localhost:8000/about
106
+ - Status API: http://localhost:8000/status
107
+ - Documentation (Swagger UI): http://localhost:8000/docs
108
+ - Documentation (ReDoc): http://localhost:8000/redoc
109
+ - MCP SSE endpoints:
110
+ - SSE endpoint: http://localhost:8000/sse
111
+ - Message posting: http://localhost:8000/messages/
112
+
113
+ ### Debug with MCP Inspector
114
+
115
+ For testing and debugging MCP functionality, use the MCP Inspector:
116
+
117
+ ```cmd
118
+ mcp dev ./src/weather.py
119
+ ```
120
+
121
+ ### Connect to MCP Inspector
122
+
123
+ 1. Open MCP Inspector at http://localhost:5173
124
+ 2. Configure the connection:
125
+ - Set Transport Type to `SSE`
126
+ - Enter URL: http://localhost:8000/sse
127
+ - Click `Connect`
128
+
129
+ ### Test the Functions
130
+
131
+ 1. Navigate to `Tools` section
132
+ 2. Click `List Tools` to see available functions:
133
+ - `get_alerts` : Get weather alerts
134
+ - `get_forcast` : Get weather forecast
135
+ 3. Select a function
136
+ 4. Enter required parameters
137
+ 5. Click `Run Tool` to execute
138
+
139
+ ## Extending the Application
140
+
141
+ ### Adding Custom Routes
142
+
143
+ The application structure makes it easy to add new routes using FastAPI's APIRouter:
144
+
145
+ 1. Define new route handlers in routes.py using the APIRouter:
146
+
147
+ ```python
148
+ @router.get("/new-route")
149
+ async def new_route():
150
+ return {"message": "This is a new route"}
151
+ ```
152
+
153
+ 2. All routes defined with the router will be automatically included in the main application
154
+
155
+ ### Customizing MCP Integration
156
+
157
+ The MCP SSE functionality is integrated in server.py through:
158
+
159
+ - Creating an SSE transport
160
+ - Setting up an SSE handler
161
+ - Adding MCP routes to the FastAPI application
162
+
163
+ ## Integration with [Continue](https://www.continue.dev/)
164
+
165
+ To use this MCP server with the Continue VS Code extension, add the following configuration to your Continue settings:
166
+
167
+ ```json
168
+ {
169
+ "experimental": {
170
+ "modelContextProtocolServers": [
171
+ {
172
+ "transport": {
173
+ "name": "weather",
174
+ "type": "sse",
175
+ "url": "http://localhost:8000/sse"
176
+ }
177
+ }
178
+ ]
179
+ }
180
+ }
181
+ ```
@@ -1,8 +1,7 @@
1
1
  [project]
2
2
  name = "mseep-fastapi-mcp-sse"
3
- version = "0.1.2"
3
+ version = "0.1.3"
4
4
  description = "A working example to create a FastAPI server with SSE-based MCP support"
5
- readme = "README.md"
6
5
  requires-python = ">=3.13"
7
6
  dependencies = [
8
7
  "fastapi>=0.115.11",
@@ -13,9 +12,10 @@ dependencies = [
13
12
  authors = [
14
13
  { name = "mseep", email = "support@skydeck.ai" },
15
14
  ]
16
- maintainers = [
17
- { name = "mseep", email = "support@skydeck.ai" },
18
- ]
15
+
16
+ [project.readme]
17
+ content-type = "text/plain"
18
+ text = "Package managed by MseeP.ai"
19
19
 
20
20
  [project.scripts]
21
21
  start = "server:run"
@@ -0,0 +1,57 @@
1
+ from fastapi import FastAPI, Request
2
+ from mcp.server.sse import SseServerTransport
3
+ from starlette.routing import Mount
4
+ from weather import mcp
5
+
6
+ # Create FastAPI application with metadata
7
+ app = FastAPI(
8
+ title="FastAPI MCP SSE",
9
+ description="A demonstration of Server-Sent Events with Model Context "
10
+ "Protocol integration",
11
+ version="0.1.0",
12
+ )
13
+
14
+ # Create SSE transport instance for handling server-sent events
15
+ sse = SseServerTransport("/messages/")
16
+
17
+ # Mount the /messages path to handle SSE message posting
18
+ app.router.routes.append(Mount("/messages", app=sse.handle_post_message))
19
+
20
+
21
+ # Add documentation for the /messages endpoint
22
+ @app.get("/messages", tags=["MCP"], include_in_schema=True)
23
+ def messages_docs():
24
+ """
25
+ Messages endpoint for SSE communication
26
+
27
+ This endpoint is used for posting messages to SSE clients.
28
+ Note: This route is for documentation purposes only.
29
+ The actual implementation is handled by the SSE transport.
30
+ """
31
+ pass # This is just for documentation, the actual handler is mounted above
32
+
33
+
34
+ @app.get("/sse", tags=["MCP"])
35
+ async def handle_sse(request: Request):
36
+ """
37
+ SSE endpoint that connects to the MCP server
38
+
39
+ This endpoint establishes a Server-Sent Events connection with the client
40
+ and forwards communication to the Model Context Protocol server.
41
+ """
42
+ # Use sse.connect_sse to establish an SSE connection with the MCP server
43
+ async with sse.connect_sse(request.scope, request.receive, request._send) as (
44
+ read_stream,
45
+ write_stream,
46
+ ):
47
+ # Run the MCP server with the established streams
48
+ await mcp._mcp_server.run(
49
+ read_stream,
50
+ write_stream,
51
+ mcp._mcp_server.create_initialization_options(),
52
+ )
53
+
54
+
55
+ # Import routes at the end to avoid circular imports
56
+ # This ensures all routes are registered to the app
57
+ import routes # noqa
@@ -1,20 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mseep-fastapi-mcp-sse
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: A working example to create a FastAPI server with SSE-based MCP support
5
- Home-page:
6
- Author: mseep
7
5
  Author-email: mseep <support@skydeck.ai>
8
- Maintainer-email: mseep <support@skydeck.ai>
9
- Requires-Python: >=3.6
10
- Description-Content-Type: text/markdown
6
+ Requires-Python: >=3.13
7
+ Description-Content-Type: text/plain
11
8
  License-File: LICENSE
12
9
  Requires-Dist: fastapi>=0.115.11
13
10
  Requires-Dist: httpx>=0.28.1
14
11
  Requires-Dist: mcp[cli]>=1.3.0
15
12
  Requires-Dist: unicorn>=2.1.3
16
- Dynamic: author
17
13
  Dynamic: license-file
18
- Dynamic: requires-python
19
14
 
20
- # Package managed by MseeP.ai
15
+ Package managed by MseeP.ai
@@ -1,7 +1,10 @@
1
1
  LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
- setup.py
4
+ src/app.py
5
+ src/routes.py
6
+ src/server.py
7
+ src/weather.py
5
8
  src/mseep_fastapi_mcp_sse.egg-info/PKG-INFO
6
9
  src/mseep_fastapi_mcp_sse.egg-info/SOURCES.txt
7
10
  src/mseep_fastapi_mcp_sse.egg-info/dependency_links.txt
@@ -0,0 +1,4 @@
1
+ app
2
+ routes
3
+ server
4
+ weather
@@ -0,0 +1,40 @@
1
+ from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
2
+ from fastapi import APIRouter
3
+ from app import app
4
+
5
+ # Create a router with a general tag for API documentation organization
6
+ router = APIRouter(tags=["General"])
7
+
8
+
9
+ @router.get("/")
10
+ async def homepage():
11
+ """Root endpoint that returns a simple HTML welcome page"""
12
+ html_content = (
13
+ "<h1>FastAPI MCP SSE</h1>"
14
+ "<p>Welcome to the SSE demo with MCP integration.</p>"
15
+ )
16
+ return HTMLResponse(html_content)
17
+
18
+
19
+ @router.get("/about")
20
+ async def about():
21
+ """About endpoint that returns information about the application"""
22
+ return PlainTextResponse(
23
+ "About FastAPI MCP SSE: A demonstration of Server-Sent Events "
24
+ "with Model Context Protocol integration."
25
+ )
26
+
27
+
28
+ @router.get("/status")
29
+ async def status():
30
+ """Status endpoint that returns the current server status"""
31
+ status_info = {
32
+ "status": "running",
33
+ "server": "FastAPI MCP SSE",
34
+ "version": "0.1.0",
35
+ }
36
+ return JSONResponse(status_info)
37
+
38
+
39
+ # Include the router in the main application
40
+ app.include_router(router)
@@ -0,0 +1,16 @@
1
+ import uvicorn
2
+ import os
3
+ from app import app
4
+
5
+ # Environment variable configuration
6
+ HOST = os.getenv("HOST", "0.0.0.0")
7
+ PORT = int(os.getenv("PORT", "8000"))
8
+
9
+
10
+ def run():
11
+ """Start the FastAPI server with uvicorn"""
12
+ uvicorn.run(app, host=HOST, port=PORT, log_level="info")
13
+
14
+
15
+ if __name__ == "__main__":
16
+ run()
@@ -0,0 +1,96 @@
1
+ from typing import Any
2
+ import httpx
3
+ from mcp.server.fastmcp import FastMCP
4
+
5
+ # Initialize FastMCP server
6
+ mcp = FastMCP("weather")
7
+
8
+ # Constants
9
+ NWS_API_BASE = "https://api.weather.gov"
10
+ USER_AGENT = "weather-app/1.0"
11
+
12
+
13
+ async def make_nws_request(url: str) -> dict[str, Any] | None:
14
+ """Make a request to the NWS API with proper error handling."""
15
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
16
+ async with httpx.AsyncClient() as client:
17
+ try:
18
+ response = await client.get(url, headers=headers, timeout=30.0)
19
+ response.raise_for_status()
20
+ return response.json()
21
+ except Exception:
22
+ return None
23
+
24
+
25
+ def format_alert(feature: dict) -> str:
26
+ """Format an alert feature into a readable string."""
27
+ props = feature["properties"]
28
+ return f"""
29
+ Event: {props.get('event', 'Unknown')}
30
+ Area: {props.get('areaDesc', 'Unknown')}
31
+ Severity: {props.get('severity', 'Unknown')}
32
+ Description: {props.get('description', 'No description available')}
33
+ Instructions: {props.get('instruction', 'No specific instructions provided')}
34
+ """
35
+
36
+
37
+ @mcp.tool()
38
+ async def get_alerts(state: str) -> str:
39
+ """Get weather alerts for a US state.
40
+
41
+ Args:
42
+ state: Two-letter US state code (e.g. CA, NY)
43
+ """
44
+ url = f"{NWS_API_BASE}/alerts/active/area/{state}"
45
+ data = await make_nws_request(url)
46
+
47
+ if not data or "features" not in data:
48
+ return "Unable to fetch alerts or no alerts found."
49
+
50
+ if not data["features"]:
51
+ return "No active alerts for this state."
52
+
53
+ alerts = [format_alert(feature) for feature in data["features"]]
54
+ return "\n---\n".join(alerts)
55
+
56
+
57
+ @mcp.tool()
58
+ async def get_forecast(latitude: float, longitude: float) -> str:
59
+ """Get weather forecast for a location.
60
+
61
+ Args:
62
+ latitude: Latitude of the location
63
+ longitude: Longitude of the location
64
+ """
65
+ # First get the forecast grid endpoint
66
+ points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
67
+ points_data = await make_nws_request(points_url)
68
+
69
+ if not points_data:
70
+ return "Unable to fetch forecast data for this location."
71
+
72
+ # Get the forecast URL from the points response
73
+ forecast_url = points_data["properties"]["forecast"]
74
+ forecast_data = await make_nws_request(forecast_url)
75
+
76
+ if not forecast_data:
77
+ return "Unable to fetch detailed forecast."
78
+
79
+ # Format the periods into a readable forecast
80
+ periods = forecast_data["properties"]["periods"]
81
+ forecasts = []
82
+ for period in periods[:5]: # Only show next 5 periods
83
+ forecast = f"""
84
+ {period['name']}:
85
+ Temperature: {period['temperature']}°{period['temperatureUnit']}
86
+ Wind: {period['windSpeed']} {period['windDirection']}
87
+ Forecast: {period['detailedForecast']}
88
+ """
89
+ forecasts.append(forecast)
90
+
91
+ return "\n---\n".join(forecasts)
92
+
93
+
94
+ if __name__ == "__main__":
95
+ # Initialize and run the server
96
+ mcp.run(transport="sse")
@@ -1 +0,0 @@
1
- # Package managed by MseeP.ai
@@ -1,20 +0,0 @@
1
-
2
- from setuptools import setup, find_packages
3
-
4
- setup(
5
- name="mseep-fastapi-mcp-sse",
6
- version="0.1.0",
7
- description="A working example to create a FastAPI server with SSE-based MCP support",
8
- author="mseep",
9
- author_email="support@skydeck.ai",
10
- url="",
11
- packages=find_packages(),
12
- classifiers=[
13
- "Programming Language :: Python :: 3",
14
- "License :: OSI Approved :: MIT License",
15
- "Operating System :: OS Independent",
16
- ],
17
- python_requires=">=3.6",
18
- install_requires=['fastapi>=0.115.11', 'httpx>=0.28.1', 'mcp[cli]>=1.3.0', 'unicorn>=2.1.3'],
19
- keywords=["mseep"] + [],
20
- )