This document describes how the ReportPortal MCP Server is put together: process layout, request flow, key packages, and the constraints/limitations you need to know before changing it. It is aimed at engineers picking up the project with little or no prior context.
See also: Development & Style Guide · Release Workflow
A Model Context Protocol (MCP) server that exposes ReportPortal (test reporting + TMS) capabilities as MCP tools and prompts, so any MCP-compatible AI assistant (Claude, Cursor, Copilot, ...) can query/mutate ReportPortal data through natural language.
It is a single Go binary (cmd/reportportal-mcp-server) that can run in one of
two transport modes, selected at startup by the MCP_MODE environment
variable:
| Mode | Transport | Typical use |
|---|---|---|
stdio (default) |
stdin/stdout, one process per client | Local AI tool integrations (Claude Desktop, Cursor, VS Code) |
http |
Streamable HTTP / SSE via github.com/modelcontextprotocol/go-sdk |
Shared/remote deployments serving many clients concurrently |
Both modes share the same tool/prompt registration code — only the transport, authentication source, and HTTP client tuning differ.
┌───────────────────────────────┐
│ cmd/.../main.go │
│ builds *cli.Command via │
│ config.InitAppConfig(...) │
└───────────────┬────────────────┘
│ MCP_MODE env var
┌───────────────────┴───────────────────┐
│ │
MCP_MODE=stdio MCP_MODE=http
│ │
▼ ▼
internal/reportportal/mcp_handlers/server.go internal/reportportal/http_server.go
RunStdioServer(ctx, cmd) RunStreamingServer(ctx, cmd)
- reads RP_API_TOKEN/RP_HOST/RP_PROJECT - Chi router + middleware
from CLI flags (env-bound) - per-request token/project
- builds *mcp.Server via NewServer(...) via HTTP headers
- runs over mcp.StdioTransport - builds *mcp.Server via
NewHTTPServer(...)
│ │
└───────────────────┬───────────────────┘
▼
mcp_handlers.RegisterLaunchTools / RegisterTestItemTools /
RegisterTMSTools — register mcp.Tool + typed handler pairs
│
▼
gorp.Client (github.com/reportportal/goRP/v5)
generated OpenAPI client for ReportPortal's REST API
│
▼
ReportPortal instance (RP_HOST)
Cross-cutting concerns hang off the same wiring:
- Analytics (
internal/reportportal/analytics) — optional, batches anonymous usage metrics to Google Analytics 4. - Middleware (
internal/reportportal/middleware) — injects the bearer token/project into outgoing ReportPortal requests (QueryParamsMiddleware) and extracts them from incoming HTTP requests (HTTPTokenMiddleware). - Prompts (
internal/reportportal/mcp_handlers/prompts/*.yaml) — declarative MCP prompts loaded at startup viainternal/promptreader. - Context propagation (
internal/reportportal/utils/ctx_utils.go) — the token and project key travel throughcontext.Context, not global state.
| Package | Responsibility |
|---|---|
cmd/reportportal-mcp-server |
Process entrypoint; wires signal handling + config.InitAppConfig. |
cmd/verify-testdata |
Standalone CLI that replays internal/integration/testdata/*.json fixtures against a live running server (see Development guide). |
internal/config |
CLI flag/env-var definitions (cli.go), TLS config construction (tls.go), build-time version vars (Version/Commit/Date, injected via -ldflags). |
internal/reportportal |
HTTP-mode server: Chi router, middleware stack, health/info/metrics endpoints, graceful shutdown (http_server.go). |
internal/reportportal/mcp_handlers |
stdio-mode server bootstrap (server.go) and all MCP tool implementations, split by domain: launches.go, items.go, tms.go. These three files hold only mcp.Tool definitions/handlers and their Register*Tools function — non-tool helpers live in internal/reportportal/utils/mcp_utils.go instead (see Development guide §2). Also prompt loading glue. |
internal/reportportal/mcp_handlers/prompts |
YAML prompt definitions (embedded via //go:embed). |
internal/reportportal/analytics |
Google Analytics 4 usage tracking (opt-out), instance-ID discovery, batching. |
internal/reportportal/middleware |
HTTP middleware: token/project extraction (HTTP mode) and injection (outgoing RP client). |
internal/reportportal/utils |
Shared helpers used across all tool handlers: pagination, project-key resolution, JSON-schema builders, response helpers, context helpers, TMS manual-scenario building/validation. |
internal/promptreader |
Parses prompt YAML into mcp.Prompt + mcp.PromptHandler pairs, with Go text/template rendering of arguments. |
internal/integration |
Black-box integration test harness (mock ReportPortal + mock LLM client + real MCP server) driven by JSON fixtures. |
helm-charts/reportportal-mcp-server |
Kubernetes Helm chart for HTTP-mode deployments. |
main.gobuilds a*cli.Commandand runs it;MCP_MODE(unset ⇒stdio) selectsmcphandlers.RunStdioServer.RunStdioServerrequiresRP_API_TOKEN(flag/env), optionally storesRP_PROJECTin the rootcontext.Contextviautils.WithProjectInContext.mcphandlers.NewServer(...)builds onegorp.Clientfor the whole process, configured with the token viagorp.WithApiKeyAuthand aQueryParamsMiddlewarethat also merges any query params carried on the request context.- All tools are registered once; the server then blocks on
mcpServer.Run(ctx, &mcp.StdioTransport{}), i.e. one client per process, one token for the whole process lifetime.
RunStreamingServerbuilds anHTTPServerConfigfrom CLI flags (no token — HTTP mode never readsRP_API_TOKEN/--token).NewHTTPServerbuilds one sharedgorp.Clientwith an empty fallback token; the real token is injected per-request.- A Chi router is configured with (in order): CORS → RequestID → RealIP →
Logger → Recoverer → conditional timeout (skipped for SSE) → Throttle
(
--max-workers, defaultNumCPU()*2) → route dispatch. - On the
/mcp,/api/mcpgroup:HTTPTokenMiddlewarereadsAuthorization: Bearer <token>andX-Projectheaders and stores them in the request context;mcpMiddlewarerejects anything that is not a JSON POST, an SSE GET, or a session-terminating DELETE. - Requests are dispatched to
mcp.NewStreamableHTTPHandler, which calls the shared*mcp.Server. Because token/project live in the request context (not a struct field), the samegorp.Clientand tool handlers are safely reused across concurrent requests from different users —QueryParamsMiddlewarereads the per-request context at the moment the outgoing RP HTTP request is built.
utils.ExtractProject(ctx, args.ProjectKey)resolves the effective project: context value (env var in stdio /X-Projectheader in HTTP) always wins; theprojectKeytool argument is only a fallback.- Handler builds/executes a
gorp-generated OpenAPI request, or (for some TMS endpoints not yet in the generated client) a rawnet/httprequest built fromrpClient.GetConfig()— seetoolGetMilestonesByFilterininternal/reportportal/mcp_handlers/tms.gofor the pattern. utils.ReadAPIResponse/utils.ReadResponseBodyconvert the HTTP response into an*mcp.CallToolResult, passing the raw JSON body straight through instead of the typed decoded struct (see limitation below).- If analytics is enabled,
utils.WithAnalyticswraps the handler and firesTrackMCPEventbefore execution.
github.com/modelcontextprotocol/go-sdk/mcp— official MCP Go SDK; providesmcp.Server,mcp.AddTool(generic, schema-inferring), stdio and Streamable HTTP transports.github.com/reportportal/goRP/v5— generated OpenAPI client for ReportPortal's REST API (pkg/gorp,pkg/openapi). Since it's generated, not every TMS endpoint may be present yet; see §6.github.com/urfave/cli/v3— CLI flags/env-var binding (internal/config/cli.go).github.com/go-chi/chi/v5— HTTP router used only in HTTP mode.github.com/google/jsonschema-go/jsonschema— builds theInputSchemafor every tool (see Development guide).
These are structural properties of the current design — read them before "fixing" something that is actually intentional, and update this list when you change the underlying behavior.
- One RP client per process, not per user (stdio mode). stdio mode is single-tenant by design: one token, one project, one OS process per MCP client connection. It cannot serve multiple ReportPortal users concurrently. HTTP mode is multi-tenant instead (token/project come from headers).
RP_PROJECT/RP_API_TOKENare silently ignored in HTTP mode. By design — HTTP mode is meant to be shared, so per-user secrets must travel per-request (Authorizationheader,X-Projectheader). This is a common source of "why isn't my env var working" support questions; see the README's Troubleshooting section.--insecureand--tls-ca-certare mutually exclusive. Enforced in bothconfig.BuildTLSConfigand the CLIAction. Setting both is a startup error, not a silent override.- Never overwrite
rpClient.APIClient.GetConfig().HTTPClientafter client creation without re-adding the OAuth2 Bearer-token transport — doing so silently drops authentication. This exact regression is covered byTestNewServer_BearerTokenSentWithTLSConfig/..._BearerTokenSentWithoutTLSininternal/reportportal/mcp_handlers/server_test.go. If you need a custom*http.Client(e.g. custom TLS), build it viabuildHTTPClient/createHTTPClientand thread it throughoauth2.HTTPClientin the auth context — don't replace the client used by the OAuth2-wrapped transport directly. - The generated ReportPortal OpenAPI client is incomplete for some TMS
endpoints (e.g. milestones). Handlers work around this by issuing raw
net/httprequests built fromrpClient.GetConfig()(scheme/host/default headers/middleware) instead of a generated method. When the upstreamgoRPclient adds the missing operation, prefer migrating the handler to the typed client. - Polymorphic
oneOfresponses can fail client-side decoding even on a successful HTTP call (e.g.TmsTestCaseRS.ManualScenario, which is a discriminated union ofTEXT/STEPSscenario shapes).utils.ReadAPIResponsedeliberately ignores decode errors when the HTTP status is 2xx and returns the raw JSON body instead — do not "fix" this by surfacing the decode error, and do not rely on the typed decoded struct downstream of these calls. - Import Launch from File has a hard upload cap. Default 50 MiB decoded
size, further capped by the selected plugin's advertised
details.maxFileSize. Base64 payloads are measured after decoding. There is no streaming/chunked upload path — large files must be pre-split/compressed by the caller. - Analytics
GetAnalyticArg()deliberately obfuscates the GA4 API secret with XOR/base64 tricks so it isn't trivially greppable in the binary or source. It is not a security boundary (the value ends up in every built binary) — it only stops the secret from being copy-pasted from agit blame/stringsat a glance. Do not add a "cleaner" plain-string constant; do not treat it as a secret that needs rotation-on-leak handling. - Analytics is best-effort and fails open. If
NewAnalyticsfails (e.g. missing GA4 secret at build time) the server logs a warning and continues withanalyticsInstance == nil; every analytics call is a nil-safe no-op (TrackMCPEvent,incrementMetric, etc. all checka == nil). Never make analytics failures fatal or block a tool call on analytics I/O — events are fire-and-forget, batched everyBatchSendInterval(10s) in a background goroutine. - No persistent state / no database. The server is stateless between
requests beyond the in-memory analytics counters; all "state" lives in
ReportPortal itself. Restarting the process loses only unsent analytics
counters (≤
BatchSendIntervalof data). - HTTP mode has no built-in authentication of its own endpoints beyond
passing through whatever bearer token the caller supplies to ReportPortal
—
/health,/info,/metricsare unauthenticated by design (they leak no RP data). MCP endpoints rely entirely on ReportPortal validating the forwarded token; the server does not cache/verify tokens itself beyond the lightweightutils.ValidateRPTokenformat check (UUID or ≥16 chars) used to decide whether to even forward a header. - TMS tools require ReportPortal 26.1+ with TMS enabled; non-TMS tools require 25.1+ / service-api ≥ 5.14.0. Calling TMS tools against an older instance will surface as ReportPortal API errors (404/400), not a clean "unsupported version" message from this server.
- Windows path handling in
//go:embed. Prompt files are read withfilepath.Clean(dir)+"/"+entry.Name()— forward slash is hard-coded becauseembed.FSalways uses/, even when the host OS (e.g. Windows) uses\. Don't switch this tofilepath.Join. - Go version drift risk.
go.modcurrently pinsgo 1.27.0; the rootREADME.md"Prerequisites" section may quote a different minimum (e.g. 1.24.4). Treatgo.modand.golangci.yml'sGOLANGCI_LINT_VERSIONcomment as the source of truth and keep the README in sync when bumping. - No request-level rate limiting against ReportPortal itself — only
local concurrency is throttled (
--max-workers/ ChiThrottle). A misbehaving client can still overwhelm the upstream ReportPortal instance if--max-workersis set too high for that instance's capacity.
- Local binary / Docker, stdio — the common case for IDE/desktop AI tool integrations (see README "Installation").
- Local binary / Docker, HTTP — for local testing of the HTTP transport
(
task docker:run MCP_MODE=http), ordocker-compose.yamlfor a minimal standalone HTTP deployment. - Kubernetes via Helm (
helm-charts/reportportal-mcp-server) — HTTP mode only, fronted by an Ingress; see the chart's own README for values. - GitHub Container images —
develop-*(fromdevelop),rc/*/hotfix/*branch images, PR "feature" images, and tagged releases on Docker Hub — see Release Workflow.