-
Notifications
You must be signed in to change notification settings - Fork 0
Refactor codebase and configuration capabilities #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7d40f62
Refactor codebase and configuration capabilities
Agent-Hellboy 1d8d0d4
fix tests
Agent-Hellboy eb009fd
fix refactor
Agent-Hellboy ea6c5f8
fix refactor
Agent-Hellboy c34d04b
remove redundent code
Agent-Hellboy cfe78d2
improve coverage
Agent-Hellboy 07e9b2d
fix coverage and ci issues
Agent-Hellboy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| from pymcp.middleware import MiddlewareConfig | ||
|
|
||
| middleware_config = MiddlewareConfig( | ||
| cors={ | ||
| "allow_origins": ["https://myapp.com"], | ||
| "allow_methods": ["GET", "POST"], | ||
| "allow_headers": ["*"], | ||
| "allow_credentials": True, | ||
| }, | ||
| logging={ | ||
| "level": "DEBUG", | ||
| "format": "%(asctime)s %(levelname)s %(message)s", | ||
| }, | ||
| compression={"enabled": True}, | ||
| custom=[ | ||
| # Add custom middleware classes here if needed | ||
| ], | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| # Framework Middleware Configuration Guide | ||
|
|
||
| This guide explains how to configure middleware in your framework using the provided `MiddlewareConfig` class or via keyword arguments. | ||
|
|
||
| ## Default Middleware | ||
|
|
||
| The framework includes the following middleware by default: | ||
|
|
||
| - **CORS**: Allows cross-origin requests (default: all origins, all methods, all headers). | ||
| - **Logging**: Basic request/response logging (default: INFO level). | ||
| - **Error Handling**: Basic error handling to prevent leaking internal details. | ||
|
|
||
| Optional middleware you can enable/configure: | ||
| - **Compression**: GZip compression for responses. | ||
| - **Custom Middleware**: Add your own FastAPI-compatible middleware. | ||
|
|
||
| --- | ||
|
|
||
| ## Configuration Methods | ||
|
|
||
| You can configure middleware in two ways: | ||
|
|
||
| ### 1. Using `MiddlewareConfig` | ||
|
|
||
| ```python | ||
| from pymcp.server import create_app, MiddlewareConfig | ||
Agent-Hellboy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| config = MiddlewareConfig( | ||
| cors={ | ||
| "allow_origins": ["https://myapp.com"], | ||
| "allow_methods": ["GET", "POST"], | ||
| "allow_headers": ["*"], | ||
| "allow_credentials": True, | ||
| }, | ||
| logging={ | ||
| "level": "DEBUG", | ||
| "format": "%(asctime)s %(levelname)s %(message)s", | ||
| }, | ||
| error_handling={ | ||
| # Add custom error handlers if needed | ||
| }, | ||
| compression={ | ||
| "enabled": True | ||
| }, | ||
| custom=[ | ||
| # List of custom middleware classes | ||
| ] | ||
| ) | ||
|
|
||
| app = create_app(middleware_config=config) | ||
| ``` | ||
|
|
||
| ### 2. Using Keyword Arguments | ||
|
|
||
| ```python | ||
| from pymcp.server import create_app | ||
|
|
||
| app = create_app( | ||
| cors={ | ||
| "allow_origins": ["https://myapp.com"], | ||
| "allow_methods": ["GET", "POST"], | ||
| "allow_headers": ["*"], | ||
| "allow_credentials": True, | ||
| }, | ||
| logging={ | ||
| "level": "DEBUG", | ||
| "format": "%(asctime)s %(levelname)s %(message)s", | ||
| }, | ||
| compression={ | ||
| "enabled": True | ||
| }, | ||
| custom=[ | ||
| # List of custom middleware classes | ||
| ] | ||
| ) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Middleware Options | ||
|
|
||
| ### CORS | ||
| - `allow_origins`: List of allowed origins (default: `["*"]`) | ||
| - `allow_methods`: List of allowed HTTP methods (default: `["*"]`) | ||
| - `allow_headers`: List of allowed headers (default: `["*"]`) | ||
| - `allow_credentials`: Allow credentials (default: `True`) | ||
|
|
||
| ### Logging | ||
| - `level`: Log level (default: `"INFO"`) | ||
| - `format`: Log format string | ||
|
|
||
| ### Error Handling | ||
| - `custom_handler`: (Optional) Your custom error handler function | ||
|
|
||
| ### Compression | ||
| - `enabled`: Enable GZip compression (default: `False`) | ||
|
|
||
| ### Custom Middleware | ||
| - `custom`: List of FastAPI-compatible middleware classes to add | ||
|
|
||
| --- | ||
|
|
||
| ## Example: Adding Custom Middleware | ||
|
|
||
| ```python | ||
| from starlette.middleware.base import BaseHTTPMiddleware | ||
|
|
||
| class MyCustomMiddleware(BaseHTTPMiddleware): | ||
| async def dispatch(self, request, call_next): | ||
| # Custom logic here | ||
| response = await call_next(request) | ||
| return response | ||
|
|
||
| config = MiddlewareConfig(custom=[MyCustomMiddleware]) | ||
| app = create_app(middleware_config=config) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Best Practices | ||
| - Restrict CORS origins in production. | ||
| - Use appropriate log levels for your environment. | ||
| - Add custom error handlers for user-friendly error messages. | ||
| - Enable compression for large responses or slow networks. | ||
| - Add custom middleware for authentication, metrics, etc. | ||
|
|
||
| --- | ||
|
|
||
| ## Recommended Usage: config.py | ||
|
|
||
| For best practice, create a `config.py` file in your project root to define your middleware configuration. Then, import this config in your server entry point (e.g., `run_server.py`). | ||
|
|
||
| ### Example: config.py | ||
|
|
||
| ```python | ||
|
|
||
| from pymcp.applications import create_app | ||
| from pymcp.middleware import MiddlewareConfig | ||
|
|
||
| middleware_config = MiddlewareConfig( | ||
| cors={ | ||
| "allow_origins": ["https://myapp.com"], | ||
| "allow_methods": ["GET", "POST"], | ||
| "allow_headers": ["*"], | ||
| "allow_credentials": True, | ||
| }, | ||
| logging={ | ||
| "level": "DEBUG", | ||
| "format": "%(asctime)s %(levelname)s %(message)s", | ||
| }, | ||
| compression={ | ||
| "enabled": True | ||
| }, | ||
| custom=[ | ||
| # Add custom middleware classes here if needed | ||
| ] | ||
| ) | ||
| ``` | ||
|
|
||
| ### Example: run_server.py | ||
|
|
||
| ```python | ||
| from config import middleware_config | ||
| from pymcp.server import create_app | ||
|
|
||
| app = create_app(middleware_config=middleware_config) | ||
| ``` | ||
|
|
||
| This approach keeps your configuration clean and separated from your application logic. | ||
|
|
||
| For more details, see the framework documentation or contact the maintainers. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| """ | ||
| App factory for the MCP framework. | ||
| Provides the create_app function to instantiate and configure the FastAPI app. | ||
| """ | ||
|
|
||
| from typing import Optional | ||
|
|
||
| from fastapi import FastAPI | ||
|
|
||
| from .middleware import MiddlewareConfig, setup_middleware | ||
| from .server import router | ||
|
|
||
|
|
||
| def create_app(middleware_config: Optional[MiddlewareConfig] = None, **kwargs): | ||
| app = FastAPI() | ||
| config = middleware_config or MiddlewareConfig( | ||
| cors=kwargs.get("cors"), | ||
| logging=kwargs.get("logging"), | ||
| error_handling=kwargs.get("error_handling"), | ||
| compression=kwargs.get("compression"), | ||
| custom=kwargs.get("custom"), | ||
| ) | ||
| setup_middleware(app, config) | ||
| app.include_router(router) | ||
| return app |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| """ | ||
| Middleware configuration and setup for the MCP framework. | ||
| """ | ||
|
|
||
| from typing import Any, Dict, Optional | ||
|
|
||
| from fastapi.middleware.cors import CORSMiddleware | ||
| from fastapi.middleware.gzip import GZipMiddleware | ||
|
|
||
|
|
||
| class MiddlewareConfig: | ||
| """ | ||
| Configuration class for setting up middleware in the MCP server. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| cors: Optional[Dict[str, Any]] = None, | ||
| logging: Optional[Dict[str, Any]] = None, | ||
| error_handling: Optional[Dict[str, Any]] = None, | ||
| compression: Optional[Dict[str, Any]] = None, | ||
| custom: Optional[list] = None, | ||
| ): | ||
| self.cors = cors or { | ||
| "allow_origins": ["*"], | ||
| "allow_credentials": True, | ||
| "allow_methods": ["*"], | ||
| "allow_headers": ["*"], | ||
| } | ||
Agent-Hellboy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.logging = logging or { | ||
| "level": "INFO", | ||
| "format": "%(asctime)s %(levelname)s %(message)s", | ||
| } | ||
| self.error_handling = error_handling or {} | ||
| self.compression = compression or {"enabled": False} | ||
| self.custom = custom or [] | ||
|
|
||
|
|
||
| def setup_middleware(app, config: MiddlewareConfig): | ||
| """ | ||
| Apply middleware to the FastAPI app based on the provided MiddlewareConfig. | ||
| """ | ||
| # CORS | ||
| app.add_middleware( | ||
| CORSMiddleware, | ||
| allow_origins=config.cors["allow_origins"], | ||
| allow_credentials=config.cors["allow_credentials"], | ||
| allow_methods=config.cors["allow_methods"], | ||
| allow_headers=config.cors["allow_headers"], | ||
| ) | ||
|
|
||
| # Compression | ||
| if config.compression.get("enabled", False): | ||
| app.add_middleware(GZipMiddleware) | ||
| # Custom middleware | ||
| for mw in config.custom: | ||
| if not hasattr(mw, "__call__"): | ||
| raise ValueError(f"Custom middleware {mw} is not callable") | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| app.add_middleware(mw) | ||
| # Error handling can be added here as needed | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.