Skip to content

Fix mcp client rebuild bug && support labels for experiement && add metrics#70

Merged
JacksonMei merged 7 commits intomainfrom
jun/metrics
Mar 4, 2026
Merged

Fix mcp client rebuild bug && support labels for experiement && add metrics#70
JacksonMei merged 7 commits intomainfrom
jun/metrics

Conversation

@JacksonMei
Copy link
Collaborator

No description provided.

JacksonMei and others added 5 commits March 2, 2026 19:04
Add comprehensive Prometheus metrics (requests, latency, instance ops,
active instances gauge, uptime gauge) to api-service. Implement labels
propagation through full chain: SDK -> api-service -> faas-api-service
-> metaservice, enabling per-experiment/owner/app metric breakdown.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Share request metrics with MCP data plane traffic on port 8081.
Skip recording /health endpoint errors to avoid noise from
proxy-less K8s liveness probes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Redesign SDK logging to use stdlib hierarchy under "aenv" namespace.
Callers can redirect all SDK logs with one line: setup_logging(handler).
Default colored stdout output preserved for standalone usage.
Bump version to 0.1.5.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the aenvironment platform by introducing robust support for labels and comprehensive Prometheus metrics. The Python SDK receives version updates and a refactored logging system for better integration. On the Go API service side, the changes enable the assignment and tracking of labels for environment instances, providing greater organizational and analytical capabilities. Furthermore, a new metrics system has been implemented to monitor API performance and the state of FaaS instances, offering critical insights into system health and usage. These updates collectively improve the platform's observability, manageability, and extensibility.

Highlights

  • Version Updates: The Python SDK's aenvironment package version has been updated from 0.1.4 to 0.1.5 in pyproject.toml and aenv/__init__.py.
  • Enhanced Logging in Python SDK: The Python SDK's logging system has been refactored to use a single root logger, aenv, and introduces a setup_logging function for easier external integration. Error messages for function execution and health checks have also been improved.
  • Support for Labels in Environment Instances: Environment instances now support user-defined labels. This includes updates to the Python client (scheduler_client.py), core environment logic (environment.py), and data models (models.py). The Go API service (env_instance.go, models/env_instance.go, faas_client.go, faas_model/function.go) has also been updated to handle these labels, including their propagation from DeployConfig.
  • Introduction of Prometheus Metrics: The Go API service now integrates Prometheus metrics to monitor HTTP requests, business operations (instance and service creation/deletion), and active instance states. This includes new metric definitions, a dedicated metrics collector for FaaS instances, and updated middleware for recording HTTP request metrics.
  • Comprehensive Testing for Labels and Metrics: New test files (env_instance_labels_test.go, metrics_test.go, faas_client_test.go) have been added to ensure the correct functionality and integration of labels and metrics across the API service.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • aenv/pyproject.toml
    • Updated project version from 0.1.4 to 0.1.5.
  • aenv/src/aenv/init.py
    • Updated __version__ to 0.1.5.
    • Imported setup_logging from aenv.core.logging.
    • Added setup_logging to the __all__ export list.
  • aenv/src/aenv/client/scheduler_client.py
    • Added an optional labels parameter to the create_env_instance function signature.
    • Updated create_env_instance docstring to include labels parameter description.
    • Included labels in the logger.info message for environment instance creation.
    • Passed labels to the EnvInstanceCreateRequest during instance creation.
  • aenv/src/aenv/core/environment.py
    • Added an optional labels parameter to the Environment class constructor.
    • Stored labels as an instance attribute self.labels.
    • Added a quiet boolean parameter to _call_function to control logging verbosity for transient issues.
    • Modified _call_function to use logger.debug instead of logger.error when quiet is true for certain exceptions.
    • Updated error messages in _call_function for clarity, changing 'failed' to 'not ready' or 'encountered an issue'.
    • Updated call_tool log message to include arguments.
    • Modified call_tool error message for clarity, changing 'failed' to 'encountered an issue'.
    • Passed quiet=True to _call_function during health checks to suppress verbose logging for expected retries.
    • Updated health check debug log message to include attempt number.
    • Passed self.labels to create_env_instance during environment instance creation.
  • aenv/src/aenv/core/logging.py
    • Replaced logging.config and logging.Manager imports with direct logging and sys imports.
    • Refactored logging configuration from a dictionary-based log_config to a programmatic approach.
    • Introduced _STYLES dictionary for colored formatter configurations.
    • Added _make_handler helper function to create colorlog.ColoredFormatter stream handlers.
    • Initialized a single root logger _root_logger named 'aenv' with a default colored handler.
    • Modified getLogger to return child loggers that propagate to the _root_logger, simplifying handler management.
    • Added setup_logging function to allow external code to replace or clear SDK log handlers.
  • aenv/src/aenv/core/models.py
    • Added an optional labels field (Dict[str, str]) to the EnvInstance model with a description 'Resource labels'.
    • Added an optional labels field (Dict[str, str]) to the EnvInstanceCreateRequest model with a description 'Resource labels'.
  • aenv/src/aenv/server/mcp_server.py
    • Simplified FastMCP initialization by removing explicit host, port, and log_level parameters, relying on defaults or internal configuration.
  • api-service/controller/env_instance.go
    • Imported the new api-service/metrics package.
    • Added a Labels field of type map[string]string to the CreateEnvInstanceRequest struct, marked as omitempty.
    • Integrated metrics.InstanceOpsTotal to track 'create' operations with 'error' status in various failure paths within CreateEnvInstance.
    • Added logic to set req.Labels into backendEnv.DeployConfig if labels are provided in the request.
    • Integrated metrics.InstanceOpsTotal to track 'create' operations with 'success' status upon successful instance creation.
    • Integrated metrics.InstanceOpsTotal to track 'get' operations with 'error' and 'success' statuses in GetEnvInstance.
    • Integrated metrics.InstanceOpsTotal to track 'delete' operations with 'error' and 'success' statuses in DeleteEnvInstance.
    • Integrated metrics.InstanceOpsTotal to track 'list' operations with 'error' and 'success' statuses in ListEnvInstances.
  • api-service/controller/env_instance_labels_test.go
    • Added a new test file for EnvInstanceController related to labels.
    • Implemented mockEnvInstanceService for testing purposes.
    • Added TestCreateEnvInstanceRequest_LabelsBinding to verify JSON binding of labels in CreateEnvInstanceRequest.
    • Added TestCreateEnvInstance_LabelsPassedToDeployConfig to ensure labels are correctly set in DeployConfig.
    • Added TestCreateEnvInstance_LabelsOnResponse to confirm labels are included in the EnvInstance response.
    • Added TestCreateEnvInstanceRequest_FullRoundTrip to test JSON serialization and deserialization of requests with labels.
    • Added TestCreateEnvInstanceRequest_HTTPRequest to simulate and verify HTTP request handling with labels.
  • api-service/controller/env_service.go
    • Imported the new api-service/metrics package.
    • Integrated metrics.ServiceOpsTotal to track 'create' operations with 'error' and 'success' statuses in CreateEnvService.
    • Integrated metrics.ServiceOpsTotal to track 'get' operations with 'error' and 'success' statuses in GetEnvService.
    • Integrated metrics.ServiceOpsTotal to track 'delete' operations with 'error' and 'success' statuses in DeleteEnvService.
    • Integrated metrics.ServiceOpsTotal to track 'update' operations with 'error' and 'success' statuses in UpdateEnvService.
    • Integrated metrics.ServiceOpsTotal to track 'list' operations with 'error' and 'success' statuses in ListEnvServices.
  • api-service/main.go
    • Imported the new api-service/metrics package.
    • Applied middleware.MetricsMiddleware() to the mcpRouter to collect HTTP request metrics.
    • Introduced a conditional block to start a metrics.Collector for FaaS mode, which periodically collects and updates instance metrics.
  • api-service/metrics/collector.go
    • Added a new file to define the Collector for instance metrics.
    • Defined InstanceLister interface for abstracting instance listing.
    • Implemented Collector struct with lister, interval, and stopCh.
    • Provided NewCollector to create a new metrics collector.
    • Implemented Start method to begin a periodic collection loop in a goroutine.
    • Implemented Stop method to halt the collector.
    • Implemented collect method to fetch instances, reset gauges, and update ActiveInstances and InstanceUptimeSeconds Prometheus metrics based on instance labels.
  • api-service/metrics/metrics.go
    • Added a new file to define Prometheus metrics.
    • Defined subsystem as 'aenv_api'.
    • Defined BusinessLabelKeys for instance metrics: 'env', 'experiment', 'owner', 'app'.
    • Declared RequestsTotal (CounterVec) for total HTTP requests.
    • Declared RequestDurationMs (HistogramVec) for HTTP request durations.
    • Declared InstanceOpsTotal (CounterVec) for total instance operations.
    • Declared ServiceOpsTotal (CounterVec) for total service operations.
    • Declared ActiveInstances (GaugeVec) for the number of currently active instances.
    • Declared InstanceUptimeSeconds (GaugeVec) for instance uptime.
  • api-service/metrics/metrics_test.go
    • Added a new test file for Prometheus metrics.
    • Implemented mockInstanceLister for testing the collector.
    • Added TestMetricsEndpointAvailable to verify that custom metrics appear in the /metrics output.
    • Added TestMetricsMiddleware to ensure the middleware correctly records HTTP request metrics.
    • Added TestCollectorCollect to verify the Collector correctly updates ActiveInstances and InstanceUptimeSeconds gauges.
    • Added TestCollectorWithNilLabels to ensure the collector handles nil instance labels gracefully.
    • Added TestCollectorWithError to ensure the collector handles errors during instance listing gracefully.
  • api-service/middleware/metrics.go
    • Removed old requestCount, requestDuration, requestSize, and responseSize metrics.
    • Refactored MetricsMiddleware to use the new api-service/metrics package for RequestsTotal and RequestDurationMs.
    • Updated MetricsMiddleware to determine the endpoint using c.FullPath() or c.Request.URL.Path.
  • api-service/models/env_instance.go
    • Added a Labels field of type map[string]string to the EnvInstance struct, marked as omitempty.
  • api-service/service/faas_client.go
    • Removed comment regarding datasource as runtime name.
    • Modified CreateEnvInstance to extract labels from req.DeployConfig.
    • Added logic in CreateEnvInstance to ensure labels map is initialized and to set a default 'env' label if not provided by the user.
    • Updated CreateInstanceByFunction call in CreateEnvInstance to pass the extracted labels.
    • Updated CreateEnvInstance to set the Labels field on the returned models.EnvInstance.
    • Modified CreateInstanceByFunction function signature to accept a labels parameter.
    • Passed the labels parameter to faas_model.FunctionInitializeOptions in CreateInstanceByFunction.
    • Updated GetEnvInstance to populate the Labels field of the returned models.EnvInstance from the FaaS instance data.
    • Updated ListEnvInstances to populate the Labels field of each models.EnvInstance in the returned list.
  • api-service/service/faas_client_test.go
    • Added a new test file for FaaSClient related to labels.
    • Added TestCreateEnvInstance_LabelsExtractedFromDeployConfig to verify the correct extraction and default setting of labels from DeployConfig.
    • Added TestCreateEnvInstance_LabelsSetOnResult to confirm that labels are correctly applied to the resulting EnvInstance object.
  • api-service/service/faas_model/function.go
    • Added a Labels field of type map[string]string to the FunctionInitializeOptions struct, marked as omitempty.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for labels on environment instances and adds extensive Prometheus metrics for monitoring, alongside a significant refactoring of the Python SDK's logging. While these features enhance observability, security concerns were identified regarding the logging of sensitive information (environment variables, tool arguments) at high-visibility levels (INFO/ERROR) and the use of unbounded user-supplied input as Prometheus label values, which poses a Denial of Service (DoS) risk due to high cardinality. The review also focuses on improving code clarity and reducing repetition in the new metrics implementation and cleaning up the refactored logging module. It is recommended to sanitize logs, strictly control or aggregate metric labels derived from untrusted input, and refactor repetitive metric reporting for better code clarity.

func (ctrl *EnvInstanceController) CreateEnvInstance(c *gin.Context) {
var req CreateEnvInstanceRequest
if err := c.ShouldBindJSON(&req); err != nil {
metrics.InstanceOpsTotal.WithLabelValues("create", req.EnvName, "error").Inc()
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The application uses user-supplied input (req.EnvName and id from URL parameters) as label values for Prometheus metrics (InstanceOpsTotal). This poses a significant risk of Denial of Service (DoS) due to high cardinality if an attacker provides a large number of unique values. Beyond this security concern, the current implementation also has repetitive calls to metrics.InstanceOpsTotal. Consider refactoring to use a defer statement to centralize metrics reporting, which can improve code clarity and potentially aid in sanitizing or aggregating label values.

func (ctrl *EnvServiceController) CreateEnvService(c *gin.Context) {
var req CreateEnvServiceRequest
if err := c.ShouldBindJSON(&req); err != nil {
metrics.ServiceOpsTotal.WithLabelValues("create", req.EnvName, "error").Inc()
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The env_service controller uses user-supplied input (req.EnvName and id) as label values for ServiceOpsTotal metrics. This poses a significant risk of Denial of Service (DoS) due to high cardinality if an attacker provides many unique values for these fields. Similar to env_instance.go, the metrics reporting calls are repetitive. Consider using a defer statement to centralize the logic, which can improve code clarity and help manage label cardinality.


logger.info(
f"Creating environment instance: {name}, datasource: {datasource}, ttl: {ttl}, environment_variables: {environment_variables}, arguments: {arguments}, owner: {owner}, url: {self.base_url}"
f"Creating environment instance: {name}, datasource: {datasource}, ttl: {ttl}, environment_variables: {environment_variables}, arguments: {arguments}, owner: {owner}, labels: {labels}, url: {self.base_url}"
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The create_env_instance method logs the entire environment_variables and labels dictionaries at the INFO level. These dictionaries are highly likely to contain sensitive information such as API keys, passwords, or Personally Identifiable Information (PII) required for the environment setup. Logging this information can lead to sensitive data leakage in log files.

logger.error(
f"{self._log_prefix()} Function '{function_url}' execution http request failed: {error_msg} | "
_log = logger.debug if quiet else logger.error
_log(
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The _call_function and call_tool methods log the arguments passed to them at INFO or ERROR levels. These arguments could contain sensitive data intended for the tools or functions being executed. Logging them directly poses a risk of sensitive information disclosure.

logger.error(
f"{self._log_prefix()} Function '{function_url}' execution failed: {str(e)} | "
_log = logger.debug if quiet else logger.error
_log(
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The _call_function and call_tool methods log the arguments passed to them at INFO or ERROR levels. These arguments could contain sensitive data intended for the tools or functions being executed. Logging them directly poses a risk of sensitive information disclosure.


logger.info(
f"{self._log_prefix()} Executing tool: {actual_tool_name} in environment {self.env_name}"
f"{self._log_prefix()} Executing tool: {actual_tool_name} in environment {self.env_name}, arguments={arguments}"
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The _call_function and call_tool methods log the arguments passed to them at INFO or ERROR levels. These arguments could contain sensitive data intended for the tools or functions being executed. Logging them directly poses a risk of sensitive information disclosure.

@@ -664,15 +670,17 @@ async def call_tool(

except Exception as e:
logger.error(
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The _call_function and call_tool methods log the arguments passed to them at INFO or ERROR levels. These arguments could contain sensitive data intended for the tools or functions being executed. Logging them directly poses a risk of sensitive information disclosure.

app := inst.Labels["app"]

// Increment active instance count
ActiveInstances.WithLabelValues(env, experiment, owner, app).Inc()
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The metrics collector extracts labels (env, experiment, owner, app) from instance labels, which are originally provided by users. These are then used as label values for ActiveInstances and InstanceUptimeSeconds gauges. This allows an attacker to inject arbitrary labels and cause high cardinality in the metrics system, potentially leading to a Denial of Service (DoS).

Comment on lines +78 to +79
metrics.RequestsTotal.WithLabelValues(method, endpoint, status).Inc()
metrics.RequestDurationMs.WithLabelValues(method, endpoint, status).Observe(durationMs)
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The MetricsMiddleware uses the request path as a label value for RequestsTotal and RequestDurationMs metrics when c.FullPath() is empty. An attacker can send requests with many unique paths (e.g., random strings) to inflate the number of time series in Prometheus, leading to high cardinality and potential Denial of Service (DoS).

Comment on lines 82 to 83
name: Optional[str] = None,
type_: Optional[Literal["plain", "benchmark", "colored", "system"]] = None,
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The type_ parameter in the getLogger function signature is no longer used after the logging refactoring. It appears to be a leftover from the previous implementation. To improve code clarity and maintainability, it should be removed.

    name: Optional[str] = None

Previously, each call_tool() and list_tools() used `async with client:`
which created and destroyed a full MCP session (initialize → tools/call
→ DELETE) on every invocation. This wasted ~1.5s per call in session
overhead and could cause 60s timeouts under load when re-initialization
blocked.

Add _ensure_mcp_session() that lazily enters the Client async context
on first use and keeps the session alive for all subsequent calls. The
session is only torn down in release(). Includes lock protection for
concurrent access and automatic reconnection if the session is lost.

Measured improvement: 10× echo calls from ~16s → ~5s total, subsequent
calls from ~1.5s → ~0.6s each. Eliminates 60s timeout risk entirely.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@JacksonMei JacksonMei changed the title Fix mcp client rebuild and support labels & metrics Fix mcp client rebuild bug && support labels for experiement && add metrics Mar 4, 2026
Remove mockEnvInstanceService and mockBackendClient that were defined
but never used, causing golangci-lint unused errors in CI.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@JacksonMei JacksonMei merged commit d0f0587 into main Mar 4, 2026
1 check passed
@JacksonMei JacksonMei deleted the jun/metrics branch March 4, 2026 09:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants