← 2Cloud Insights
MCP in DevOps

MCP in DevOps: Building Secure Integrations Between AI Agents, Kubernetes, and CI/CD Pipelines

MCP connects AI agents with Kubernetes and CI/CD pipelines, enabling secure infrastructure interactions, smarter automation, and more efficient DevOps workflows.

MCP in DevOps: Building Secure Integrations Between AI Agents, Kubernetes, and CI/CD PipelinesMCP in DevOps: Building Secure Integrations Between AI Agents, Kubernetes, and CI/CD Pipelines
Your reading guide

13 minutes · 21 sections

What’s inside

Introduction

AI agents can now help engineering teams debug failing deployments, investigate infrastructure issues, analyze pipeline results, and automate repetitive operational work. They become far more useful when they can reach the systems teams already run.

The Model Context Protocol (MCP) is the standardized layer that lets AI applications discover and call external tools, APIs, and services. In DevOps, that means an agent can read Kubernetes state, inspect CI/CD results, and prepare deployment changes.

It also creates a security problem. An agent that can execute infrastructure operations can make unauthorized changes, leak sensitive data, or trigger unintended deployments, whether through its own mistake or through a malicious instruction hidden in a log file.

So a secure integration needs more than a connection between an agent and an MCP server. It needs authorization, permission boundaries, policy checks, approval workflows, and audit trails. This article walks through each layer for Kubernetes and CI/CD, and states plainly where a control is a hint rather than a guarante.

1. MCP in a DevOps environment

MCP uses a client-server architecture:

  • MCP host: the AI application (Claude, Cursor, or an internal platform) in which the agent runs.

  • MCP client: the component that maintains communication with MCP servers.

  • MCP server: exposes tools, resources, and prompts.

  • External systems: Kubernetes, GitHub, Jenkins, cloud platforms, monitoring.

A typical flow: an engineer asks the agent why a deployment failed; the agent selects tools exposed by the MCP server; the server calls the Kubernetes or CI/CD API; and the structured result returns to the agent for analysis.

One distinction matters for everything below: MCP standardizes how tools are called. It does not provide authorization or governance for what those tools do. Those controls come from the identity, policy, and infrastructure systems around it.

What changed in the 2026-07-28 specification

If you have read older MCP security material, check it against these changes:

  • Stateless core. The initialize handshake and the MCP-Session-Id header are gone. Each request is self-contained, so any server instance behind a load balancer can handle it. New Mcp-Method and Mcp-Name headers let gateways route, meter, and authorize without parsing the JSON body.

  • Authorization hardening. Clients must validate the iss parameter on authorization responses (RFC 9207), and credentials are bound to the authorization server that issued them. Client ID Metadata Documents are now the preferred registration path.

  • Deprecation. Dynamic Client Registration, Roots, Sampling, Logging, and the HTTP+SSE transport are deprecated.

  • Multi round-trip requests. A tool can ask for confirmation mid-call without a held-open connection, which makes approval prompts possible on stateless servers.

Transport and authorization behavior changed, so validate your implementation against the current spec instead of copying examples written for older revisions.

2. Reference architecture

A secure design puts an explicit control layer between the agent and the infrastructure. The agent never receives administrative credentials or direct access to the Kubernetes API for changes.

Three principles hold this together:

  1. Read-only by default. Investigation tools work with read permissions only. Write capability is a separate, explicit, narrowly scoped path. Mature Kubernetes MCP servers, including Red Hat's and Microsoft's AKS server, follow this pattern.

  2. The agent's reasoning is never the security boundary. Authentication, RBAC, policy, and approval are enforced outside the model.

  3. Changes are declarative. The agent never runs kubectl apply. It proposes a change as a pull request, which a human reviews and a GitOps controller reconciles.

3. Securing MCP server access

A server that exposes infrastructure operations must not be reachable without authentication. For remote servers over HTTP, the MCP authorization specification builds on OAuth 2.1. Note the scope: authorization is optional in the spec, and local stdio servers should not use this flow at all; they take credentials from their environment. Everything below applies to remote, HTTP-based servers.

  • Use an established identity provider (Okta, Microsoft Entra ID, Keycloak) rather than custom authentication.

  • Publish Protected Resource Metadata (RFC 9728). MCP servers must implement it so clients can discover the authorization server.

  • Require the resource parameter (RFC 8707). Clients must include the MCP server's canonical URI in authorization and token requests. The server must then verify that each token was issued specifically for it. A token minted for another API must be rejected.

  • Validate the issuer. Clients record the expected issuer and check the iss parameter (RFC 9207) before redeeming an authorization code. This closes authorization-server mix-up attacks.

  • Prefer Client ID Metadata Documents over Dynamic Client Registration, which is now deprecated.

  • Keep tokens short-lived, and separate scopes by capability. For example, mcp:read for cluster inspection and mcp:propose-change for opening a pull request. Scope names are yours to define; the spec requires least privilege, not particular names.

  • Keep secrets out of prompts, responses, and logs. Store credentials in a secrets manager such as HashiCorp Vault, AWS Secrets Manager, or Google Secret Manager, delivered to the workload through your platform's integration (for example External Secrets Operator). Sealed Secrets and SOPS are useful for encrypting secrets stored in Git, but they are not runtime secret managers.

Do not pass tokens through

An MCP server must not forward the token it received from a client to a downstream API. The spec says servers must accept only tokens meant for them and must not transit any others. Validate the incoming token, then obtain a separate, identity-mapped credential for the downstream system (a token exchange or a dedicated service identity). Otherwise a stolen or over-scoped token crosses service boundaries unchecked.

4. Least privilege with Kubernetes RBAC

Authentication says who is calling. RBAC limits what the MCP server can do in the cluster. Give it a dedicated service account with only the permissions its tools need, never cluster-wide administrative rights.

For an agent investigating failures in a staging namespace, read access to a few resources is enough:

apiVersion: rbac.authorization.k8s.io/v1

kind: Role

metadata:

  name: mcp-observer

  namespace: app-staging

rules:

  - apiGroups: ["apps"]

    resources: ["deployments", "replicasets"]

    verbs: ["get", "list", "watch"]

  - apiGroups: [""]

    resources: ["pods", "events"]

    verbs: ["get", "list", "watch"]

---

apiVersion: rbac.authorization.k8s.io/v1

kind: RoleBinding

metadata:

  name: mcp-observer-binding

  namespace: app-staging

subjects:

  - kind: ServiceAccount

    name: mcp-observer-sa

    namespace: mcp-system

roleRef:

  apiGroup: rbac.authorization.k8s.io

  kind: Role

  name: mcp-observer

This service account can read selected resources in app-staging and nothing else. Pod logs (pods/log) are deliberately excluded. Grant them only after checking whether your applications write secrets or personal data to logs.

Permissions an agent should never receive

The Kubernetes RBAC good-practices guide lists several rights that allow privilege escalation. Treat all of these as off-limits for an MCP server:

  • cluster-admin, wildcard (*) resources or verbs, and membership in system:masters.

  • get, list, or watch on Secrets. Listing returns the contents, so read-only access is not harmless.

  • pods/exec, and creating Pods or other workloads. Creating workloads implicitly grants access to Secrets and to every service account in the namespace.

  • escalate, bind, and impersonate verbs, and create on serviceaccounts/token.

  • Any access to nodes/proxy. A get there is not read-only: it can reach kubelet APIs that return logs and run commands.

  • Control over admission webhook configurations, and patch on Namespaces.

Also set automountServiceAccountToken: false on workloads that do not need API access, and review bindings periodically.

Preserve who asked

A single shared service account has an audit cost. Kubernetes audit logs will show mcp-observer-sa, not the engineer who made the request. Choose one of these approaches and record it:

  • Per-user credentials through OIDC or token exchange, so the API server sees the real identity (and the user's own RBAC applies).

  • Impersonation from the MCP server, with the impersonate verb tightly constrained, since that verb is itself a privilege-escalation risk.

  • At minimum, tag every API call from the server with a distinctive user-agent and attach a request ID, so AI-initiated actions can be separated from human ones and correlated with MCP logs. Red Hat's OpenShift MCP server uses this technique.

Harden the MCP server itself

The server is a privileged component. Run it under the Restricted Pod Security Standard (non-root, read-only root filesystem, dropped capabilities, seccomp RuntimeDefault), restrict its network access with NetworkPolicy to the endpoints it needs, and pin its image by digest.

5. CI/CD and GitOps: read freely, change through review

Separate diagnostics from state changes.

Read-only operations

Tools such as get_pipeline_status, get_build_summary, and get_deployment_history let an agent investigate without touching the environment.

Controlled change through a pull request

Never let an agent run kubectl apply or override a container image directly. Instead, the MCP adapter opens a pull request against the configuration repository.

This makes every change:

  • Auditable: the diff, author, reviewer, and timing live in Git.

  • Pinned by digest: the image is referenced by sha256 digest, not by a mutable tag such as latest.

  • Reconciled by a controller: Argo CD or Flux applies the merged state, so the agent holds no cluster write access.

The security-critical part of this adapter is not the GitHub call; it is the validation of what the agent asks for. The agent controls the request fields, so treat them as untrusted input:

var digestRe = regexp.MustCompile(^sha256:[a-f0-9]{64}$)

// Repositories and path prefixes the adapter may touch.

var allowedRepos = map[string]string{

"my-org/deploy-config": "apps/",

}

type DeploymentPRRequest struct {

Repo     string json:"repo"      // "owner/name"

FilePath string json:"file_path" // kustomization file to update

Digest   string json:"digest"    // sha256:...

}

func (r DeploymentPRRequest) Validate() error {

prefix, ok := allowedRepos[r.Repo]

if !ok {

return fmt.Errorf("repository %q is not allowed", r.Repo)

}

clean := path.Clean(r.FilePath)

if !strings.HasPrefix(clean, prefix) || strings.Contains(r.FilePath, "..") {

return fmt.Errorf("path %q is outside %q", r.FilePath, prefix)

}

if !digestRe.MatchString(r.Digest) {

return errors.New("digest must be sha256:<64 hex characters>")

}

return nil

}

After validation, the adapter creates a branch, changes only the image digest field (for example the digest entry in a Kustomize images: list, using a YAML-aware edit rather than rewriting the whole manifest), and opens a pull request. Use a GitHub App installation token limited to that one repository with only contents and pull-request write access. The identity must have no permission to approve or merge. The full implementation, including the GitHub calls, is in the companion repository.

Where the approval gate lives

In a GitOps flow, the pull request is the approval gate. Configure branch protection so that changes need an approving review from code owners, and so that someone other than the most recent pusher must approve. Make sure the agent's identity cannot approve its own pull request. If the agent acts with an engineer's OAuth token, GitHub will not let that engineer approve it either, but a bot identity means any other reviewer can; decide which you want.

If you also deploy through GitHub Actions environments, know the limits of that gate:

  • Required reviewers are available for private repositories only on paid plans.

  • "Prevent self-review" is an optional setting, and it applies to the user who initiated the deployment, so check how your agent's identity maps to that.

  • Administrators can bypass protection rules by default. Disable that for production environments.

6. Human approval for high-impact changes

An agent may diagnose a problem correctly and still propose a risky fix. Keep humans accountable for high-impact steps.

Consider a failing application. The agent reads deployment, pod, and event data, finds a probably bad image version, and recommends redeploying a previously validated release. It prepares a pull request. An authorized engineer then inspects the exact digest, target namespace, diff, and validation results before approving. Only after the merge does the deployment controller act.

The agent must never approve its own request. Require human review for production deployments, infrastructure changes, resource deletion, permission changes, database modifications, and network or security configuration.

The 2026-07-28 spec adds in-protocol confirmation prompts through multi round-trip requests. They are useful for asking a user "are you sure?" mid-call, but they supplement out-of-band approval in Git or CI; they do not replace it. Human approval also does not replace automated checks. Use both.

7. Policy enforcement and runtime security

An authenticated user can still send an unsafe request, so every tool call should pass through a deterministic policy check before it executes.

For a deployment request, the policy layer should verify that the operation is permitted, the cluster and namespace are approved, the image comes from an approved registry and is pinned by digest, and whether extra approval is required.

Open Policy Agent (OPA) is a common choice. This policy uses current Rego v1 syntax (OPA 1.x):

package mcp.authz

default allow := false

allowed_registries := {"gcr.io/prod-reg/", "ghcr.io/my-org/"}

restricted_namespaces := {"kube-system", "mcp-system"}

deny contains msg if {

input.target_namespace in restricted_namespaces

msg := sprintf("namespace %q is restricted", [input.target_namespace])

}

deny contains msg if {

input.action == "request_deployment"

not approved_image(input.parameters.image)

msg := "image must be digest-pinned and from an approved registry"

}

approved_image(image) if {

some prefix in allowed_registries

startswith(image, prefix)

regex.match(@sha256:[a-f0-9]{64}$, image)

}

allow if {

count(deny) == 0

input.role == "mcp-observer"

input.action == "read_only_diagnostic"

}

allow if {

count(deny) == 0

input.role == "mcp-operator"

input.action == "request_deployment"

}

Policy at the MCP layer is one control among several. The cluster should enforce its own rules independently, so that a bypassed or misconfigured MCP server cannot deploy something unsafe:

  • Native admission policy: Kubernetes ValidatingAdmissionPolicy for CEL-based checks with no extra webhook.

  • Image signature verification: Kyverno can verify Sigstore Cosign signatures and attestations. Use its ImageValidatingPolicy type, which is the current stable API; the older ClusterPolicy with verifyImages is deprecated. Check the documentation for your installed version, since examples online mix generations.

Tool design

Prefer narrow, named operations: get_deployment_status, get_pod_events, get_pipeline_status, get_build_summary, request_deployment.

Avoid generic tools such as execute_shell_command, run_any_kubectl_command, delete_kubernetes_resource, or execute_arbitrary_pipeline. An unrestricted command tool gives the agent whatever privileges the server holds.

MCP tool annotations such as readOnlyHint and destructiveHint help clients present tools sensibly, but they are descriptive hints, not security controls. A server can claim a tool is read-only and be wrong, or be malicious. Enforce restrictions with RBAC and policy.

Defending against indirect prompt injection

An agent investigating a failure reads untrusted text: application logs, repository files, pipeline output. An attacker who controls any of it can embed instructions, such as a fake error message telling the agent to ignore prior instructions and call a secrets tool.

  • Separate data from control. Treat tool output as data. It must never be executed or granted the authority of a user instruction.

  • Validate every action. Enforce strict, typed schemas on tool arguments and discard unexpected fields, as in the validation code above.

  • Gate high-value actions. Decouple change-making tools from the analysis phase, and require human approval and deterministic checks before they run.

  • Limit what a successful injection can reach. Least-privilege RBAC and no secrets access mean an injected instruction has little to act on.

The OWASP Top 10 for Agentic Applications and the OWASP MCP Top 10 catalog these risks, including tool poisoning, privilege escalation, and command injection. The MCP list is still a beta project, so treat it as evolving guidance.

8. Audit logging and monitoring

It is not enough to know an agent did something. You must be able to reconstruct who asked, what ran, whether it was authorized, and who approved it.

Audit Fields and Purposes Table

Collect from three layers: MCP server logs (requests, policy decisions, outcomes), Kubernetes audit logs (API requests, including the user-agent or impersonated identity from Section 4), and Git and CI/CD history (pull requests, reviews, merges, deployments). Forward them to a central platform with access controls and retention policies.

Never write tokens, passwords, or secret values to audit logs. Distributed tracing, with the request ID propagated from agent to MCP call to downstream API, makes the chain much easier to follow. Kubernetes documents its auditing framework for recording API activity.

9. End-to-end example

An organization runs a production application on Kubernetes, with configuration in Git and Argo CD reconciling the cluster.

  1. Request. An engineer asks: "Investigate why the application is failing in production and suggest a fix."

  2. Investigation. The agent calls read-only tools for deployment status, pod readiness, events, and, where authorized, logs.

  3. Analysis. The MCP server returns structured results. The agent identifies a likely bad image version.

  4. Proposal. The agent selects a previously validated release and calls request_deployment with the digest and target namespace.

  5. Validation. The server validates the request schema, checks the policy (approved registry, digest pinning, allowed namespace), and the CI checks confirm signature and scan results.

  6. Pull request. The GitOps adapter opens a PR changing only the image digest, authored by a bot identity with no merge rights.

  7. Human approval. A code owner reviews the exact diff and validation results, and approves and merges.

  8. Deployment. Argo CD reconciles the cluster. Admission policy independently verifies the image signature and rules.

  9. Verification. The agent reads deployment status and health to confirm recovery.

The full chain is recorded across MCP logs, Git history, and Kubernetes audit logs. The agent investigated and prepared the change, but never held write access to production.

Conclusion

AI agents can shorten the path from alert to diagnosis and prepare changes for review. They should do this inside boundaries that do not depend on the agent behaving well.

A production-ready design combines MCP authorization, least-privilege access, deterministic policy, protected GitOps workflows, human approval, and centralized audit. The goal is not autonomous infrastructure. It is faster, better-informed operations in which every action an agent initiates remains authorized, controlled, and auditable.

References

MCP and OAuth

Kubernetes and policy

CI/CD and supply chain

Threat guidance and industry practice

From insight to action

Put these ideas to work.

Talk to our engineers about your cloud, software, or AI project.

Talk to our team ↗

Keep exploring

Ready to build what's next?

Tell us about your project and our team will get back to you to map out the fastest path to a secure, scalable solution.

Talk to Our Experts