Skip to content
Back to search

mcp_forge

这是一个专为开发企业级MCP server而设计的通用开发框架

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/mlzoo--mcp-forge/badge.svg)](/listings/mlzoo--mcp-forge)

HTML

<a href="/listings/mlzoo--mcp-forge"><img src="/api/listings/mlzoo--mcp-forge/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Environment Setup

This framework uses `uv` as its package manager, providing faster dependency resolution and virtual environment management. For installation instructions, see the [uv official documentation](https://docs.astral.sh/uv/getting-started/installation/).

# Install dependencies and set up the development environment
make install

Launch Example Service

# Start the development server
make dev

Once the service is running, you can: - Access the API documentation at `http://localhost:5000/docs` - Connect to the MCP endpoint at `http://localhost:5000/mcp` using an MCP client (e.g., Cursor, Claude Desktop)

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 315 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # MCP Server Development Framework
  2. [中文文档](README_cn.md)
  3. ## Overview
  4. A professional framework designed for enterprise-level Model Context Protocol (MCP) tool development, standardizing the MCP server development process to help developers rapidly build high-quality AI tools. By integrating FastAPI with FastAPI-MCP, this framework enables seamless transformation from traditional APIs to AI-callable tools.
  5. ### Key Features
  6. - **MCP Tool Standardization**: Automatically convert traditional FastAPI endpoints into AI model-callable MCP tools
  7. - **Interface-Implementation Separation**: Support clear separation between interface definitions and implementations, facilitating testing and environment switching
  8. - **Dependency Injection Design**: Leverage FastAPI's dependency injection mechanism for flexible component composition and decoupling
  9. - **Complete Development Pipeline**: Provide comprehensive toolchain support from development to testing and deployment
  10. - **Example-Driven Documentation**: Demonstrate best practices through practical examples to accelerate onboarding
  11. This framework is particularly suitable for:
  12. - AI tool development teams
  13. - Developers looking to transform existing APIs into AI tools
  14. - Organizations implementing standardized microservice architectures
  15. ## Architecture
  16. ### Core Architecture
  17. ```
  18. ┌─────────────┐ ┌───────────────┐ ┌─────────────────┐
  19. │ API Layer │ ──→ │ Service Layer │ ──→ │ Implementation │
  20. └─────────────┘ └───────────────┘ └─────────────────┘
  21. ↓
  22. ┌─────────────┐
  23. │ MCP Endpoint│ ←── FastAPI-MCP Auto-Conversion
  24. └─────────────┘
  25. ```
  26. ### Key Components
  27. - **FastAPI Application**: Provides the HTTP API service foundation
  28. - **FastAPI-MCP**: Converts API endpoints to MCP tools
  29. - **Service Interface Layer**: Defines service contracts through abstract base classes
  30. - **Dependency Injection Providers**: Manages service instance creation and injection
  31. - **Implementation Classes**: Includes Mock and Real implementations with environment-based switching
  32. ## Technology Stack
  33. - **Python 3.10+**: Utilizing latest language features and type annotations
  34. - **FastAPI**: High-performance asynchronous web framework
  35. - **FastAPI-MCP**: Automatically exposes FastAPI endpoints as MCP tools
  36. - **Development Toolchain**: Includes code quality checking and testing tools
  37. ## Quick Start
  38. ### Environment Setup
  39. This framework uses `uv` as its package manager, providing faster dependency resolution and virtual environment management. For installation instructions, see the [uv official documentation](https://docs.astral.sh/uv/getting-started/installation/).
  40. ```bash
  41. # Install dependencies and set up the development environment
  42. make install
  43. ```
  44. ### Launch Example Service
  45. ```bash
  46. # Start the development server
  47. make dev
  48. ```
  49. Once the service is running, you can:
  50. - Access the API documentation at `http://localhost:5000/docs`
  51. - Connect to the MCP endpoint at `http://localhost:5000/mcp` using an MCP client (e.g., Cursor, Claude Desktop)
  52. ## Project Structure
  53. ```
  54. .
  55. ├── main.py # Application entry point and route definitions
  56. ├── services/ # Service layer implementations
  57. │ └── parking_service.py # Example service (replaceable with custom services)
  58. ├── pyproject.toml # Project configuration and dependency definitions
  59. └── Makefile # Development and build tasks
  60. ```
  61. ## MCP Tool Development Guide
  62. ### Development Process Overview
  63. 1. **Define Service Interfaces**: Create abstract base classes to define service contracts
  64. 2. **Implement Services**: Develop Mock or Real implementations based on requirements
  65. 3. **Create API Endpoints**: Develop API interfaces using FastAPI
  66. 4. **Enable MCP Service**: Expose endpoints as AI tools through FastAPI-MCP
  67. ### Service Interfaces and Implementations
  68. ```python
  69. # 1. Service Interface Definition
  70. from abc import ABC, abstractmethod
  71. from typing import Dict, Any
  72. class DataService(ABC):
  73. @abstractmethod
  74. def get_data(self, id: str) -> Dict[str, Any]:
  75. """Data retrieval interface"""
  76. pass
  77. # 2A. Mock Implementation - for development and testing
  78. class DataServiceMockImpl(DataService):
  79. def get_data(self, id: str) -> Dict[str, Any]:
  80. return {"id": id, "name": "Test Data", "mock": True}
  81. # 2B. Real Implementation - for production environment
  82. class DataServiceImpl(DataService):
  83. def __init__(self, database_url: str):
  84. self.db = Database(database_url)
  85. def get_data(self, id: str) -> Dict[str, Any]:
  86. return self.db.query("SELECT * FROM data WHERE id = :id", {"id": id})
  87. # 3. Dependency Injection Configuration
  88. def get_data_service() -> DataService:
  89. # Choose implementation based on environment
  90. return DataServiceMockImpl() # or return DataServiceImpl(settings.DATABASE_URL)
  91. ```
  92. ### API and MCP Tool Definition
  93. ```python
  94. from fastapi import FastAPI, Depends
  95. from fastapi_mcp import FastApiMCP
  96. from pydantic import BaseModel, Field
  97. app = FastAPI()
  98. # Request model
  99. class ItemRequest(BaseModel):
  100. query: str = Field(..., description="Search query parameter")
  101. limit: int = Field(10, description="Result limit")
  102. # API endpoint - automatically converted to an MCP tool
  103. @app.post("/items/search", operation_id="search_items")
  104. async def search_items(
  105. request: ItemRequest,
  106. service: DataService = Depends(get_data_service)
  107. ):
  108. result = service.search_items(request.query, request.limit)
  109. return {"items": result["items"], "total": len(result["items"])}
  110. # Create and mount MCP service
  111. mcp = FastApiMCP(
  112. app,
  113. name="example-service",
  114. description="Example MCP service",
  115. base_url="http://localhost:5000",
  116. include_operations=["search_items"]
  117. )
  118. # Mount MCP service at specified path
  119. mcp.mount(mount_path="/mcp")
  120. ```
  121. ## Dependency Injection Explained
  122. FastAPI's dependency injection system is an integral part of this framework, providing powerful and flexible dependency management capabilities.
  123. ### Dependency Injection Fundamentals
  124. Dependency injection is a design pattern that allows dependencies (such as services, database connections, etc.) to be injected into components that use them, rather than having components create and manage dependencies themselves. In FastAPI, dependency injection is implemented through the `Depends` function.
  125. ```python
  126. from fastapi import Depends
  127. def get_db():
  128. """Database connection provider"""
  129. db = connect_to_db()
  130. try:
  131. yield db # Using yield enables lifecycle management of dependencies
  132. finally:
  133. db.close()
  134. @app.get("/items/")
  135. async def get_items(db = Depends(get_db)):
  136. return db.query(Item).all()
  137. ```
  138. ### Dependency Types
  139. FastAPI supports several types of dependency injection:
  140. 1. **Function Dependencies**: As shown above, using functions as dependency providers
  141. 2. **Class Dependencies**: Using classes as dependencies for more complex dependency management
  142. ```python
  143. class DatabaseDependency:
  144. def __init__(self, settings = Depends(get_settings)):
  145. self.settings = settings
  146. def __call__(self):
  147. db = connect_to_db(self.settings.db_url)
  148. try:
  149. yield db
  150. finally:
  151. db.close()
  152. @app.get("/users/")
  153. async def get_users(db = Depends(DatabaseDependency())):
  154. return db.query(User).all()
  155. ```
  156. 3. **Nested Dependencies**: Dependencies can depend on other dependencies, forming a dependency tree
  157. ### Application in MCP Tool Development
  158. In this framework, dependency injection is primarily used for:
  159. 1. **Service Instance Management**: Injecting service implementations into API endpoints
  160. 2. **Environment Adaptation**: Selecting different service implementations based on runtime environment
  161. 3. **Resource Lifecycle Management**: Managing the creation and release of resources like database connections
  162. ## FastAPI-MCP Features
  163. ### Automatic MCP Tool Generation
  164. FastAPI-MCP can automatically convert FastAPI endpoints into MCP tools:
  165. ```python
  166. from fastapi import FastAPI
  167. from fastapi_mcp import FastApiMCP
  168. app = FastAPI()
  169. # Define a standard FastAPI endpoint
  170. @app.post("/predict", operation_id="predict_sentiment")
  171. async def predict_sentiment(text: str):
  172. return {"sentiment": "positive", "confidence": 0.92}
  173. # Create and mount MCP service - automatically converts the above endpoint to an MCP tool
  174. mcp = FastApiMCP(
  175. app,
  176. name="sentiment-analysis",
  177. description="Sentiment analysis service",
  178. base_url="http://localhost:5000",
  179. include_operations=["predict_sentiment"]
  180. )
  181. # Mount MCP service at specified path
  182. mcp.mount(mount_path="/mcp")
  183. ```
  184. ### Tool Naming Best Practices
  185. MCP tool names default to the API endpoint's `operation_id`. We recommend following these naming conventions:
  186. - Use clear, descriptive names
  187. - Adopt a verb_noun format (e.g., `predict_sentiment`, `find_nearby_parking`)
  188. - Explicitly set `operation_id` rather than relying on auto-generation
  189. ```python
  190. # Recommended: Explicitly set operation_id
  191. @app.post("/parking/nearby", operation_id="find_nearby_parking")
  192. async def find_nearby(request: NearbyRequest):
  193. # Implementation logic...
  194. pass
  195. # Not recommended: Relying on auto-generated operation_id (generates something like "find_nearby_parking_nearby_post")
  196. @app.post("/parking/nearby")
  197. async def find_nearby(request: NearbyRequest):
  198. # Implementation logic...
  199. pass
  200. ```
  201. ## Testing and Quality Assurance
  202. This framework supports multi-level testing strategies:
  203. ```bash
  204. # Run code quality checks
  205. make check
  206. # Run test suite
  207. make test
  208. ```
  209. ### Testing Strategies
  210. - **Unit Testing**: Test individual components using Mock service implementations
  211. - **Integration Testing**: Test interactions between components
  212. - **API Testing**: Verify HTTP interface behavior
  213. - **MCP Tool Testing**: Validate AI tool functionality
  214. ## Performance Optimization
  215. To ensure high performance of MCP tools, we recommend:
  216. - **Asynchronous Processing**: Leverage FastAPI's async features for concurrent request handling
  217. - **Caching Strategies**: Implement caching for frequently requested data
  218. - **Batch Processing**: Design APIs that support batch operations to reduce call frequency
  219. ## Contribution Guidelines
  220. Contributions to this framework are welcome:
  221. 1. Fork the repository
  222. 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
  223. 3. Commit your changes (`git commit -m 'Add amazing feature'`)
  224. 4. Push to the branch (`git push origin feature/amazing-feature`)
  225. 5. Create a Pull Request
  226. ## License
  227. [MIT License](LICENSE)
  228. ## References
  229. - [FastAPI](https://fastapi.tiangolo.com/) - High-performance web framework
  230. - [FastAPI-MCP](https://github.com/tadata-org/fastapi_mcp) - MCP tool auto-generation library

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.