Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 2 additions & 90 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js";
import { ipKeyGenerator } from "express-rate-limit";
import { normalizeProxyClientIpForRateLimit } from "./utils/proxy-client-ip.js";
import { getForwardedPublicBaseUrl } from "./utils/forwarded-public-base-url.js";
import { formatPrometheusMetrics } from "./server/metrics.js";
import { normalizeGitLabApiUrl } from "./utils/url.js";
import {
estimateMergeCommitCount,
Expand Down Expand Up @@ -13088,98 +13089,9 @@ async function startStreamableHTTPServer(): Promise<void> {
},
});

const escapePrometheusLabel = (value: unknown) =>
String(value).replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/"/g, '\\"');

const formatPrometheusMetrics = () => {
const snapshot = getMetricsSnapshot();
const configLabels = Object.entries({
max_sessions: snapshot.config.maxSessions,
max_requests_per_minute: snapshot.config.maxRequestsPerMinute,
session_timeout_seconds: snapshot.config.sessionTimeoutSeconds,
remote_auth_enabled: snapshot.config.remoteAuthEnabled,
mcp_oauth_enabled: snapshot.config.mcpOAuthEnabled,
stateless_mode_enabled: snapshot.config.statelessModeEnabled,
stateless_rotation_key: snapshot.config.statelessRotationKey,
})
.map(([key, value]) => `${key}="${escapePrometheusLabel(value)}"`)
.join(",");

return [
"# HELP gitlab_mcp_requests_processed_total Total MCP requests processed",
"# TYPE gitlab_mcp_requests_processed_total counter",
`gitlab_mcp_requests_processed_total ${snapshot.requestsProcessed}`,
"",
"# HELP gitlab_mcp_requests_rejected_total Requests rejected, by reason",
"# TYPE gitlab_mcp_requests_rejected_total counter",
`gitlab_mcp_requests_rejected_total{reason="rate_limit"} ${snapshot.rejectedByRateLimit}`,
`gitlab_mcp_requests_rejected_total{reason="capacity"} ${snapshot.rejectedByCapacity}`,
"",
"# HELP gitlab_mcp_auth_failures_total Authentication failures",
"# TYPE gitlab_mcp_auth_failures_total counter",
`gitlab_mcp_auth_failures_total ${snapshot.authFailures}`,
"",
"# HELP gitlab_mcp_sessions_total Total sessions created",
"# TYPE gitlab_mcp_sessions_total counter",
`gitlab_mcp_sessions_total ${snapshot.totalSessions}`,
"",
"# HELP gitlab_mcp_sessions_expired_total Sessions expired due to inactivity",
"# TYPE gitlab_mcp_sessions_expired_total counter",
`gitlab_mcp_sessions_expired_total ${snapshot.expiredSessions}`,
"",
"# HELP gitlab_mcp_active_sessions Currently active sessions",
"# TYPE gitlab_mcp_active_sessions gauge",
`gitlab_mcp_active_sessions ${snapshot.activeSessions}`,
"",
"# HELP gitlab_mcp_authenticated_sessions Currently authenticated sessions",
"# TYPE gitlab_mcp_authenticated_sessions gauge",
`gitlab_mcp_authenticated_sessions ${snapshot.authenticatedSessions}`,
"",
"# HELP gitlab_mcp_client_pool_size Current GitLab client pool size",
"# TYPE gitlab_mcp_client_pool_size gauge",
`gitlab_mcp_client_pool_size ${snapshot.gitlabClientPool.size}`,
"",
"# HELP gitlab_mcp_client_pool_max_size Maximum GitLab client pool size",
"# TYPE gitlab_mcp_client_pool_max_size gauge",
`gitlab_mcp_client_pool_max_size ${snapshot.gitlabClientPool.maxSize}`,
"",
"# HELP gitlab_mcp_uptime_seconds Process uptime in seconds",
"# TYPE gitlab_mcp_uptime_seconds gauge",
`gitlab_mcp_uptime_seconds ${snapshot.uptime}`,
"",
"# HELP gitlab_mcp_memory_usage_bytes Node.js memory usage by type",
"# TYPE gitlab_mcp_memory_usage_bytes gauge",
...Object.entries(snapshot.memoryUsage).map(
([key, value]) => `gitlab_mcp_memory_usage_bytes{type="${escapePrometheusLabel(key)}"} ${value}`
),
"",
"# HELP gitlab_mcp_stateless_requests_total Stateless MCP requests processed",
"# TYPE gitlab_mcp_stateless_requests_total counter",
`gitlab_mcp_stateless_requests_total ${snapshot.statelessRequests}`,
"",
"# HELP gitlab_mcp_stateless_auth_total Stateless auth successes, by source",
"# TYPE gitlab_mcp_stateless_auth_total counter",
`gitlab_mcp_stateless_auth_total{source="header"} ${snapshot.statelessAuthFromHeader}`,
`gitlab_mcp_stateless_auth_total{source="sealed_session_id"} ${snapshot.statelessAuthFromSealedSid}`,
"",
"# HELP gitlab_mcp_stateless_auth_failures_total Stateless auth failures",
"# TYPE gitlab_mcp_stateless_auth_failures_total counter",
`gitlab_mcp_stateless_auth_failures_total ${snapshot.statelessAuthFailures}`,
"",
"# HELP gitlab_mcp_stateless_session_id_rotations_total Stateless session id rotations",
"# TYPE gitlab_mcp_stateless_session_id_rotations_total counter",
`gitlab_mcp_stateless_session_id_rotations_total ${snapshot.statelessSidRotated}`,
"",
"# HELP gitlab_mcp_config_info Static configuration (value is always 1)",
"# TYPE gitlab_mcp_config_info gauge",
`gitlab_mcp_config_info{${configLabels}} 1`,
"",
].join("\n");
};

// Metrics endpoint
app.get("/metrics", (_req: Request, res: Response) => {
res.type("text/plain; version=0.0.4").send(formatPrometheusMetrics());
res.type("text/plain; version=0.0.4").send(formatPrometheusMetrics(getMetricsSnapshot()));
});

app.get("/metrics.json", (_req: Request, res: Response) => {
Expand Down
116 changes: 116 additions & 0 deletions server/metrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
export interface MetricsSnapshot {
requestsProcessed: number;
rejectedByRateLimit: number;
rejectedByCapacity: number;
authFailures: number;
totalSessions: number;
expiredSessions: number;
activeSessions: number;
authenticatedSessions: number;
gitlabClientPool: { size: number; maxSize: number };
uptime: number;
memoryUsage: NodeJS.MemoryUsage;
statelessRequests: number;
statelessAuthFromHeader: number;
statelessAuthFromSealedSid: number;
statelessAuthFailures: number;
statelessSidRotated: number;
config: {
maxSessions: number;
maxRequestsPerMinute: number;
sessionTimeoutSeconds: number;
remoteAuthEnabled: boolean;
mcpOAuthEnabled: boolean;
statelessModeEnabled: boolean;
statelessRotationKey: boolean;
};
}

export function escapePrometheusLabel(value: unknown): string {
return String(value).replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/"/g, '\\"');
}

export function formatPrometheusMetrics(snapshot: MetricsSnapshot): string {
const configLabels = Object.entries({
max_sessions: snapshot.config.maxSessions,
max_requests_per_minute: snapshot.config.maxRequestsPerMinute,
session_timeout_seconds: snapshot.config.sessionTimeoutSeconds,
remote_auth_enabled: snapshot.config.remoteAuthEnabled,
mcp_oauth_enabled: snapshot.config.mcpOAuthEnabled,
stateless_mode_enabled: snapshot.config.statelessModeEnabled,
stateless_rotation_key: snapshot.config.statelessRotationKey,
})
.map(([key, value]) => `${key}="${escapePrometheusLabel(value)}"`)
.join(",");

return [
"# HELP gitlab_mcp_requests_processed_total Total MCP requests processed",
"# TYPE gitlab_mcp_requests_processed_total counter",
`gitlab_mcp_requests_processed_total ${snapshot.requestsProcessed}`,
"",
"# HELP gitlab_mcp_requests_rejected_total Requests rejected, by reason",
"# TYPE gitlab_mcp_requests_rejected_total counter",
`gitlab_mcp_requests_rejected_total{reason="rate_limit"} ${snapshot.rejectedByRateLimit}`,
`gitlab_mcp_requests_rejected_total{reason="capacity"} ${snapshot.rejectedByCapacity}`,
"",
"# HELP gitlab_mcp_auth_failures_total Authentication failures",
"# TYPE gitlab_mcp_auth_failures_total counter",
`gitlab_mcp_auth_failures_total ${snapshot.authFailures}`,
"",
"# HELP gitlab_mcp_sessions_total Total sessions created",
"# TYPE gitlab_mcp_sessions_total counter",
`gitlab_mcp_sessions_total ${snapshot.totalSessions}`,
"",
"# HELP gitlab_mcp_sessions_expired_total Sessions expired due to inactivity",
"# TYPE gitlab_mcp_sessions_expired_total counter",
`gitlab_mcp_sessions_expired_total ${snapshot.expiredSessions}`,
"",
"# HELP gitlab_mcp_active_sessions Currently active sessions",
"# TYPE gitlab_mcp_active_sessions gauge",
`gitlab_mcp_active_sessions ${snapshot.activeSessions}`,
"",
"# HELP gitlab_mcp_authenticated_sessions Currently authenticated sessions",
"# TYPE gitlab_mcp_authenticated_sessions gauge",
`gitlab_mcp_authenticated_sessions ${snapshot.authenticatedSessions}`,
"",
"# HELP gitlab_mcp_client_pool_size Current GitLab client pool size",
"# TYPE gitlab_mcp_client_pool_size gauge",
`gitlab_mcp_client_pool_size ${snapshot.gitlabClientPool.size}`,
"",
"# HELP gitlab_mcp_client_pool_max_size Maximum GitLab client pool size",
"# TYPE gitlab_mcp_client_pool_max_size gauge",
`gitlab_mcp_client_pool_max_size ${snapshot.gitlabClientPool.maxSize}`,
"",
"# HELP gitlab_mcp_uptime_seconds Process uptime in seconds",
"# TYPE gitlab_mcp_uptime_seconds gauge",
`gitlab_mcp_uptime_seconds ${snapshot.uptime}`,
"",
"# HELP gitlab_mcp_memory_usage_bytes Node.js memory usage by type",
"# TYPE gitlab_mcp_memory_usage_bytes gauge",
...Object.entries(snapshot.memoryUsage).map(
([key, value]) => `gitlab_mcp_memory_usage_bytes{type="${escapePrometheusLabel(key)}"} ${value}`
),
"",
"# HELP gitlab_mcp_stateless_requests_total Stateless MCP requests processed",
"# TYPE gitlab_mcp_stateless_requests_total counter",
`gitlab_mcp_stateless_requests_total ${snapshot.statelessRequests}`,
"",
"# HELP gitlab_mcp_stateless_auth_total Stateless auth successes, by source",
"# TYPE gitlab_mcp_stateless_auth_total counter",
`gitlab_mcp_stateless_auth_total{source="header"} ${snapshot.statelessAuthFromHeader}`,
`gitlab_mcp_stateless_auth_total{source="sealed_session_id"} ${snapshot.statelessAuthFromSealedSid}`,
"",
"# HELP gitlab_mcp_stateless_auth_failures_total Stateless auth failures",
"# TYPE gitlab_mcp_stateless_auth_failures_total counter",
`gitlab_mcp_stateless_auth_failures_total ${snapshot.statelessAuthFailures}`,
"",
"# HELP gitlab_mcp_stateless_session_id_rotations_total Stateless session id rotations",
"# TYPE gitlab_mcp_stateless_session_id_rotations_total counter",
`gitlab_mcp_stateless_session_id_rotations_total ${snapshot.statelessSidRotated}`,
"",
"# HELP gitlab_mcp_config_info Static configuration (value is always 1)",
"# TYPE gitlab_mcp_config_info gauge",
`gitlab_mcp_config_info{${configLabels}} 1`,
"",
].join("\n");
}
50 changes: 50 additions & 0 deletions test/server/metrics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, test } from "node:test";
import assert from "node:assert";
import { escapePrometheusLabel, formatPrometheusMetrics } from "../../server/metrics.js";

describe("Prometheus metrics formatting", () => {
test("escapes label values", () => {
assert.strictEqual(escapePrometheusLabel('a"b\\c\nd'), 'a\\"b\\\\c\\nd');
});

test("formats current MCP metrics", () => {
const body = formatPrometheusMetrics({
requestsProcessed: 2,
rejectedByRateLimit: 1,
rejectedByCapacity: 0,
authFailures: 3,
totalSessions: 4,
expiredSessions: 5,
activeSessions: 6,
authenticatedSessions: 7,
gitlabClientPool: { size: 8, maxSize: 100 },
uptime: 9,
memoryUsage: {
rss: 10,
heapTotal: 11,
heapUsed: 12,
external: 13,
arrayBuffers: 14,
},
statelessRequests: 15,
statelessAuthFromHeader: 16,
statelessAuthFromSealedSid: 17,
statelessAuthFailures: 18,
statelessSidRotated: 19,
config: {
maxSessions: 1000,
maxRequestsPerMinute: 60,
sessionTimeoutSeconds: 3600,
remoteAuthEnabled: true,
mcpOAuthEnabled: false,
statelessModeEnabled: false,
statelessRotationKey: false,
},
});

assert.match(body, /# HELP gitlab_mcp_requests_processed_total/);
assert.match(body, /gitlab_mcp_requests_processed_total 2/);
assert.match(body, /gitlab_mcp_requests_rejected_total\{reason="rate_limit"\} 1/);
assert.match(body, /gitlab_mcp_config_info\{[^}]*remote_auth_enabled="true"/);
});
Comment on lines +10 to +49

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

LGTM!

The test provides solid coverage of the core formatting logic. If you want to strengthen the test suite, consider adding assertions for additional metric lines (e.g., memory_usage_bytes labels, stateless counters) to ensure comprehensive validation of the Prometheus exposition format.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/server/metrics.test.ts` around lines 10 - 49, The test "formats current
MCP metrics" currently has limited assertions and doesn't validate all the
metrics being generated. Add additional assert.match calls to verify the
Prometheus exposition format for memory usage metrics (such as
memory_usage_bytes with appropriate labels for rss, heapTotal, heapUsed,
external, and arrayBuffers), and stateless-related counters (such as
gitlab_mcp_stateless_requests_total,
gitlab_mcp_stateless_auth_from_header_total,
gitlab_mcp_stateless_auth_from_sealed_sid_total,
gitlab_mcp_stateless_auth_failures_total, and
gitlab_mcp_stateless_sid_rotated_total) to ensure comprehensive validation of
the output.

});
Comment thread
cursor[bot] marked this conversation as resolved.
Loading