Skip to content

Implement Prometheus metrics endpoint#35

Merged
eranco74 merged 1 commit intoopenshift-assisted:masterfrom
maorfr:metrics
Jul 21, 2025
Merged

Implement Prometheus metrics endpoint#35
eranco74 merged 1 commit intoopenshift-assisted:masterfrom
maorfr:metrics

Conversation

@maorfr
Copy link
Copy Markdown
Member

@maorfr maorfr commented Jul 20, 2025

Part of https://issues.redhat.com/browse/MGMT-21159

Implemented Prometheus metrics endpoint and instrumentation for MCP tool usage:

  • Added prometheus_client dependency
  • Instrumented all MCP tools with request counts and duration histograms
  • Added metrics server on the MCP server port (/metrics endpoint)
  • Updated README with metrics documentation

The implementation is done using a decorator (inspired by redhat-community-ai-tools/jira-mcp-snowflake#12).

An alternative I considered was using a Middleware (inspired by #5), but it is challenging to pass the MCP tool name in such a way.

Summary by CodeRabbit

  • New Features
    • Introduced Prometheus metrics endpoint for monitoring tool usage and performance.
    • All tool actions are now tracked for request count and duration, with metrics accessible at /metrics.
  • Documentation
    • Updated README with details on available Prometheus metrics and usage instructions.
  • Chores
    • Added Prometheus client library as a project dependency.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 20, 2025

Warning

Rate limit exceeded

@maorfr has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 20 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f1ffd74 and 8b4b85d.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • pyproject.toml (1 hunks)
  • server.py (15 hunks)
  • service_client/__init__.py (1 hunks)
  • service_client/metrics.py (1 hunks)

Walkthrough

Prometheus metrics tracking and exposure have been added to the MCP server. A new metrics module defines request counters and latency histograms, and all tool functions are now decorated for metrics collection. The server now exposes a /metrics endpoint and runs via Uvicorn. Documentation and dependencies were updated accordingly.

Changes

File(s) Change Summary
README.md Added documentation describing Prometheus metrics, endpoint, and available metric labels.
pyproject.toml Added prometheus_client>=0.22.1 to dependencies.
service_client/metrics.py New module defining Prometheus metrics, tracking decorator, and a metrics endpoint handler.
service_client/init.py Exported metrics and track_tool_usage in __all__ for public API.
server.py Imported metrics, decorated all tool functions for tracking, changed app run logic to use Uvicorn and expose /metrics.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MCP_Server
    participant Prometheus

    Client->>MCP_Server: Call tool function (e.g., list_clusters)
    MCP_Server->>MCP_Server: track_tool_usage decorator increments request count and records latency
    MCP_Server-->>Client: Respond with tool result

    Prometheus->>MCP_Server: GET /metrics
    MCP_Server-->>Prometheus: Return current metrics in Prometheus format
Loading

Estimated code review effort

3 (90–240 minutes)

Possibly related PRs

Suggested labels

lgtm, jira/valid-reference

Poem

🥕
Metrics now hop where the clusters reside,
With counters and histograms side by side.
Every tool call leaves a trace,
Prometheus watches with a steady gaze.
Uvicorn runs, the server anew—
The rabbit records, just for you!
🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Jul 20, 2025

Welcome @maorfr! It looks like this is your first PR to openshift-assisted/assisted-service-mcp 🎉

@openshift-ci openshift-ci Bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Jul 20, 2025
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
README.md (1)

148-152: Improve documentation readability

The documentation accurately describes the metrics, but the repetitive sentence structure makes it harder to read.

Consider restructuring for better readability:

-* **assisted_service_mcp_tool_request_count** - Number of tool requests.
-* **assisted_service_mcp_tool_request_duration_sum** - Total time to run the tool, in seconds.
-* **assisted_service_mcp_tool_request_duration_count** - Total number of tool requests measured.
-* **assisted_service_mcp_tool_request_duration_bucket** - Number of tool requests organized in buckets.
+* **assisted_service_mcp_tool_request_count** - Total number of tool requests
+* **assisted_service_mcp_tool_request_duration** - Histogram tracking request latency with the following components:
+  * **_sum** - Total time to run tools, in seconds
+  * **_count** - Total number of requests measured  
+  * **_bucket** - Requests organized by latency buckets
service_client/metrics.py (2)

27-32: Consider adjusting histogram buckets for better observability

The histogram buckets (0.1, 1.0, 10.0, 30.0, inf) may not provide optimal granularity for API request latencies. Most API calls would likely fall in the 0.1-1.0 second range.

Consider using more granular buckets for better observability:

-    buckets=(0.1, 1.0, 10.0, 30.0, float("inf")),
+    buckets=(0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, float("inf")),

This provides better granularity for typical API response times.


52-53: Add type hints and parameter validation

The metrics endpoint function lacks type hints and doesn't validate the request parameter.

-async def metrics(request):
+async def metrics(request: Any) -> PlainTextResponse:
+    """Serve Prometheus metrics endpoint"""
     return PlainTextResponse(generate_latest(), media_type=CONTENT_TYPE_LATEST)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06b0bbd and e25ad89.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • pyproject.toml (1 hunks)
  • server.py (15 hunks)
  • service_client/__init__.py (1 hunks)
  • service_client/metrics.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
service_client/__init__.py (1)
service_client/metrics.py (2)
  • metrics (52-53)
  • track_tool_usage (35-48)
server.py (2)
service_client/assisted_service_api.py (1)
  • InventoryClient (22-723)
service_client/metrics.py (2)
  • metrics (52-53)
  • track_tool_usage (35-48)
🪛 LanguageTool
README.md

[style] ~150-~150: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...l time to run the tool, in seconds. * **assisted_service_mcp_tool_request_duration_count...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~151-~151: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...l number of tool requests measured. * **assisted_service_mcp_tool_request_duration_bucke...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

🔇 Additional comments (7)
service_client/__init__.py (1)

10-12: LGTM: Clean module exports

The imports and __all__ exports follow Python best practices and correctly expose the new metrics functionality.

service_client/metrics.py (2)

20-24: LGTM: Well-defined metrics counter

The REQUEST_COUNT metric is properly defined with appropriate name, description, and labels.


35-48: Add exception handling to the metrics decorator

The decorator doesn't handle exceptions, which means failed requests won't be counted and timing context won't be properly closed.

 def track_tool_usage(tool_name: str) -> Callable:
     """Decorator to track tool usage metrics"""

     def decorator(func: Callable) -> Callable:
         @wraps(func)
         async def wrapper(*args, **kwargs) -> Any:
             REQUEST_COUNT.labels(tool=tool_name).inc()
-            with REQUEST_LATENCY.labels(tool=tool_name).time():
-                response = await func(*args, **kwargs)
-            return response
+            try:
+                with REQUEST_LATENCY.labels(tool=tool_name).time():
+                    response = await func(*args, **kwargs)
+                return response
+            except Exception:
+                # Re-raise the exception after metrics are recorded
+                raise

         return wrapper

     return decorator

This ensures metrics are properly recorded even when functions raise exceptions.

Likely an incorrect or invalid review comment.

server.py (4)

13-13: LGTM: Required import addition

The uvicorn import is correctly added to support the new server setup.


18-18: LGTM: Metrics imports

The imports for metrics functionality are correctly added.


548-550: LGTM: Proper server setup with metrics endpoint

The server setup correctly:

  • Creates an SSE app from the MCP instance
  • Adds the /metrics route for Prometheus scraping
  • Uses uvicorn to run the server on all interfaces

The switch from mcp.run(transport="sse") to this approach enables both SSE transport and HTTP metrics endpoint.


122-122: All @track_tool_usage decorator names match their functions
Verified that the decorator arguments align exactly with their corresponding async def names throughout server.py—no mismatches found.

Comment thread pyproject.toml Outdated
@eranco74
Copy link
Copy Markdown
Collaborator

/ok-to-test

@openshift-ci openshift-ci Bot added the ok-to-test Indicates a non-member PR verified by an org member that is safe to test. label Jul 20, 2025
@eranco74
Copy link
Copy Markdown
Collaborator

/lgtm

@openshift-ci openshift-ci Bot added the lgtm Indicates that a PR is ready to be merged. label Jul 20, 2025
Comment thread service_client/metrics.py
Copy link
Copy Markdown
Collaborator

@jhernand jhernand left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. I only have a minor suggestion to avoid repeating the name of the tool in the metrics decorator.

@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Jul 21, 2025

@jhernand: changing LGTM is restricted to collaborators

Details

In response to this:

Looks good to me. I only have a minor suggestion to avoid repeating the name of the tool in the metrics decorator.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@openshift-ci openshift-ci Bot removed the lgtm Indicates that a PR is ready to be merged. label Jul 21, 2025
@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Jul 21, 2025

New changes are detected. LGTM label has been removed.

@openshift-ci openshift-ci Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Jul 21, 2025
@maorfr maorfr force-pushed the metrics branch 4 times, most recently from 320498c to 50bcdbf Compare July 21, 2025 07:25
@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Jul 21, 2025

@jhernand: changing LGTM is restricted to collaborators

Details

In response to this:

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Jul 21, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: jhernand, maorfr

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@eranco74 eranco74 merged commit fe152fc into openshift-assisted:master Jul 21, 2025
12 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 21, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Oct 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ok-to-test Indicates a non-member PR verified by an org member that is safe to test. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants