-
Notifications
You must be signed in to change notification settings - Fork 562
feat(MCP): Expose Prometheus metrics #7705
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 all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
3e69cef
feat(MCP): Expose Prometheus metrics
khvn26 2909453
feat(MCP): Measure the tool catalogue size
khvn26 5ff350b
refactor(MCP): Inline metric sample lookups in tests
khvn26 a7abb07
test(MCP): Use assert_metric fixture from flagsmith-common
khvn26 2f00a68
refactor(MCP): Name metric constants after the metrics they hold
khvn26 0a91671
fix(MCP): Tool result size metric counts the payload twice
khvn26 439b721
feat(MCP): Break down tool result size by content type
khvn26 dad0065
refactor(MCP): Drop the total content label from tool result sizes
khvn26 c3d34bb
docs(MCP): Tighten the tool result size metric description
khvn26 a46aa41
test(MCP): Cover the metrics endpoint next to the other custom routes
khvn26 3bdce4b
test(MCP): Snapshot the metrics exposition
khvn26 cad1db3
feat(MCP): Serve Prometheus metrics on a dedicated port
khvn26 b67bcc1
test(MCP): Mock run() collaborators with pytest-mock
khvn26 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
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,89 @@ | ||
| import time | ||
| from collections.abc import Sequence | ||
|
|
||
| import mcp.types as mt | ||
| import pydantic_core | ||
| from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext | ||
| from fastmcp.tools.base import Tool, ToolResult | ||
| from prometheus_client import Gauge, Histogram | ||
|
|
||
| flagsmith_mcp_tool_call_duration_seconds = Histogram( | ||
| "flagsmith_mcp_tool_call_duration_seconds", | ||
| "Time spent serving an MCP tool call, including the upstream " | ||
| "Flagsmith API request.", | ||
| labelnames=["tool", "status"], | ||
| ) | ||
| flagsmith_mcp_tool_result_bytes = Histogram( | ||
| "flagsmith_mcp_tool_result_bytes", | ||
| "Serialised size of a tool call result's text content and " | ||
| "structuredContent. Helps approximate the call's token cost: clients " | ||
| "render either or both into the agent's context.", | ||
| labelnames=["tool", "content"], | ||
| buckets=(256, 1024, 4096, 16384, 65536, 262144, 1048576, float("inf")), | ||
| ) | ||
| flagsmith_mcp_tool_catalogue_bytes = Gauge( | ||
| "flagsmith_mcp_tool_catalogue_bytes", | ||
| "Serialised size of the tool catalogue returned by tools/list. A proxy " | ||
| "for the token cost every MCP session pays before any tool is called.", | ||
| ) | ||
|
|
||
|
|
||
| class PrometheusMiddleware(Middleware): | ||
| """Record Prometheus metrics for MCP tool calls.""" | ||
|
|
||
| async def on_call_tool( | ||
| self, | ||
| context: MiddlewareContext[mt.CallToolRequestParams], | ||
| call_next: CallNext[mt.CallToolRequestParams, ToolResult], | ||
| ) -> ToolResult: | ||
| tool = context.message.name | ||
| start = time.perf_counter() | ||
| try: | ||
| result = await call_next(context) | ||
| except Exception: | ||
| flagsmith_mcp_tool_call_duration_seconds.labels( | ||
| tool=tool, status="error" | ||
| ).observe(time.perf_counter() - start) | ||
| raise | ||
| flagsmith_mcp_tool_call_duration_seconds.labels( | ||
| tool=tool, status="success" | ||
| ).observe(time.perf_counter() - start) | ||
| # Text blocks already hold the serialised payload; structuredContent | ||
| # costs one compact dump, matching its wire encoding. | ||
| unstructured_bytes = sum( | ||
| len(block.text.encode()) | ||
| for block in result.content | ||
| if isinstance(block, mt.TextContent) | ||
| ) | ||
| structured_bytes = ( | ||
| len(pydantic_core.to_json(result.structured_content, fallback=str)) | ||
| if result.structured_content is not None | ||
| else 0 | ||
| ) | ||
| for content, size in ( | ||
| ("unstructured", unstructured_bytes), | ||
| ("structured", structured_bytes), | ||
| ): | ||
| flagsmith_mcp_tool_result_bytes.labels( | ||
| tool=tool, | ||
| content=content, | ||
| ).observe(size) | ||
| return result | ||
|
|
||
| async def on_list_tools( | ||
| self, | ||
| context: MiddlewareContext[mt.ListToolsRequest], | ||
| call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]], | ||
| ) -> Sequence[Tool]: | ||
| tools = await call_next(context) | ||
| flagsmith_mcp_tool_catalogue_bytes.set( | ||
| len( | ||
| pydantic_core.to_json( | ||
| [ | ||
| tool.to_mcp_tool().model_dump(exclude_none=True, by_alias=True) | ||
| for tool in tools | ||
| ] | ||
| ) | ||
| ) | ||
| ) | ||
| return tools |
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,81 @@ | ||
| import pytest | ||
| from common.test_tools import AssertMetricFixture | ||
| from fastmcp import Client | ||
| from fastmcp.client.transports import FastMCPTransport | ||
| from fastmcp.exceptions import ToolError | ||
| from prometheus_client import REGISTRY | ||
| from respx import MockRouter | ||
|
|
||
|
|
||
| async def test_metrics__successful_tool_call__records_duration_and_result_size( | ||
| client: Client[FastMCPTransport], | ||
| respx_mock: MockRouter, | ||
| assert_metric: AssertMetricFixture, | ||
| ) -> None: | ||
| # Given | ||
| respx_mock.get("https://api.flagsmith.com/environments/").respond( | ||
| json={"results": []} | ||
| ) | ||
|
|
||
| # When | ||
| await client.call_tool("list_environments", {}) | ||
|
|
||
| # Then | ||
| assert_metric( | ||
| name="flagsmith_mcp_tool_call_duration_seconds_count", | ||
| labels={"tool": "list_environments", "status": "success"}, | ||
| value=1, | ||
| ) | ||
| for content in ("unstructured", "structured"): | ||
| assert_metric( | ||
| name="flagsmith_mcp_tool_result_bytes_count", | ||
| labels={"tool": "list_environments", "content": content}, | ||
| value=1, | ||
| ) | ||
| content_sum = REGISTRY.get_sample_value( | ||
| "flagsmith_mcp_tool_result_bytes_sum", | ||
| {"tool": "list_environments", "content": content}, | ||
| ) | ||
| assert content_sum is not None | ||
| assert content_sum > 0 | ||
|
|
||
|
|
||
| async def test_metrics__failing_tool_call__records_error_duration_only( | ||
| client: Client[FastMCPTransport], | ||
| respx_mock: MockRouter, | ||
| assert_metric: AssertMetricFixture, | ||
| ) -> None: | ||
| # Given | ||
| respx_mock.get("https://api.flagsmith.com/environments/").respond(status_code=502) | ||
|
|
||
| # When | ||
| with pytest.raises(ToolError): | ||
| await client.call_tool("list_environments", {}) | ||
|
|
||
| # Then | ||
| assert_metric( | ||
| name="flagsmith_mcp_tool_call_duration_seconds_count", | ||
| labels={"tool": "list_environments", "status": "error"}, | ||
| value=1, | ||
| ) | ||
| assert ( | ||
| REGISTRY.get_sample_value( | ||
| "flagsmith_mcp_tool_result_bytes_count", | ||
| {"tool": "list_environments", "content": "unstructured"}, | ||
| ) | ||
| is None | ||
| ) | ||
|
|
||
|
|
||
| async def test_metrics__tools_list__records_catalogue_size( | ||
| client: Client[FastMCPTransport], | ||
| ) -> None: | ||
| # Given the server started via the client fixture | ||
| # When | ||
| tools = await client.list_tools() | ||
|
|
||
| # Then a catalogue of two tools weighs at least a name and a schema each | ||
| assert tools | ||
| catalogue_bytes = REGISTRY.get_sample_value("flagsmith_mcp_tool_catalogue_bytes") | ||
| assert catalogue_bytes is not None | ||
| assert catalogue_bytes > len(tools) * 50 | ||
|
emyller marked this conversation as resolved.
|
||
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
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.
Uh oh!
There was an error while loading. Please reload this page.