-
Notifications
You must be signed in to change notification settings - Fork 8
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
feat: add optional SSE middleware to obtain Grafana info from headers #21
Closed
Closed
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
50c2d9c
feat: add optional SSE middleware to obtain Grafana info from headers
sd2k 697748d
Use separate contextvar with client in it
sd2k 0fae385
Add type annotation to run_sse_async monkeypatch
sd2k ddc6022
Add test for middleware
sd2k 23fd6c9
Rename authorization to api_key
sd2k 87d4168
Correctly reset settings and client tokens
sd2k 762c60c
Fail fast if Grafana override settings are not provided in sse request
sd2k 69bcb0c
Remove incorrect bit of test comment
sd2k 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 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 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 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 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 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,106 @@ | ||
from dataclasses import dataclass | ||
|
||
from mcp.server import FastMCP | ||
from starlette.datastructures import Headers | ||
|
||
from .client import GrafanaClient, grafana_client | ||
from .settings import GrafanaSettings, grafana_settings | ||
|
||
|
||
@dataclass | ||
class GrafanaInfo: | ||
""" | ||
Simple container for the Grafana URL and API key. | ||
""" | ||
|
||
api_key: str | ||
url: str | ||
|
||
@classmethod | ||
def from_headers(cls, headers: Headers) -> "GrafanaInfo | None": | ||
if (url := headers.get("X-Grafana-URL")) is not None and ( | ||
key := headers.get("X-Grafana-API-Key") | ||
) is not None: | ||
return cls(api_key=key, url=url) | ||
return None | ||
|
||
|
||
class GrafanaMiddleware: | ||
""" | ||
Middleware that sets up Grafana info for the current request. | ||
|
||
Grafana info will be stored in the `grafana_info` contextvar, which can be | ||
used by tools/resources etc to access the Grafana configuration for the | ||
current request, if it was provided. | ||
|
||
This should be used as a context manager before handling the /sse request. | ||
""" | ||
|
||
def __init__(self, request): | ||
self.request = request | ||
self.settings_token = None | ||
self.client_token = None | ||
|
||
async def __aenter__(self): | ||
if (info := GrafanaInfo.from_headers(self.request.headers)) is not None: | ||
current_settings = grafana_settings.get() | ||
new_settings = GrafanaSettings( | ||
url=info.url, | ||
api_key=info.api_key, | ||
tools=current_settings.tools, | ||
) | ||
self.settings_token = grafana_settings.set(new_settings) | ||
self.client_token = grafana_client.set( | ||
GrafanaClient.from_settings(new_settings) | ||
) | ||
|
||
async def __aexit__(self, exc_type, exc_val, exc_tb): | ||
if self.settings_token is not None: | ||
grafana_settings.reset(self.settings_token) | ||
if self.client_token is not None: | ||
grafana_client.reset(self.client_token) | ||
|
||
|
||
async def run_sse_async_with_middleware(self: FastMCP) -> None: | ||
""" | ||
Run the server using SSE transport, with a middleware that extracts | ||
Grafana authentication information from the request headers. | ||
|
||
The vast majority of this code is the same as the original run_sse_async | ||
method (see https://github.com/modelcontextprotocol/python-sdk/blob/44c0004e6c69e336811bb6793b7176e1eda50015/src/mcp/server/fastmcp/server.py#L436-L468). | ||
""" | ||
|
||
from mcp.server.sse import SseServerTransport | ||
from starlette.applications import Starlette | ||
from starlette.routing import Mount, Route | ||
import uvicorn | ||
|
||
sse = SseServerTransport("/messages/") | ||
|
||
async def handle_sse(request): | ||
async with GrafanaMiddleware(request): | ||
async with sse.connect_sse( | ||
request.scope, request.receive, request._send | ||
) as streams: | ||
await self._mcp_server.run( | ||
streams[0], | ||
streams[1], | ||
self._mcp_server.create_initialization_options(), | ||
) | ||
|
||
starlette_app = Starlette( | ||
debug=self.settings.debug, | ||
routes=[ | ||
Route("/sse", endpoint=handle_sse), | ||
Mount("/messages/", app=sse.handle_post_message), | ||
], | ||
) | ||
|
||
config = uvicorn.Config( | ||
starlette_app, | ||
host=self.settings.host, | ||
port=self.settings.port, | ||
log_level=self.settings.log_level.lower(), | ||
) | ||
server = uvicorn.Server(config) | ||
await server.serve() |
This file contains 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 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 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 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 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 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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would love to do away with all of these annoying
.get()
calls, tools definitely shouldn't be able to modify this contextvar...