From 6ef608ec6cc79e676bf43ca0a13b2835a9c71bb0 Mon Sep 17 00:00:00 2001 From: Francisco Ewerton de Araujo Silva Date: Sun, 22 Nov 2026 14:04:43 -0300 Subject: [PATCH 1/5] feat(mcp): add access tokens for the MCP server Add the createMcpToken, listMcpTokens and revokeMcpToken APIs. A token belongs to the user that creates it, may have an expiration date and is returned only on creation: the mcp_token table stores its SHA-256 hash. Add the mcp.enabled and mcp.async.job.wait settings in their own MCP group of the global settings. --- .../main/java/com/cloud/event/EventTypes.java | 4 + .../command/user/mcp/CreateMcpTokenCmd.java | 77 +++++++ .../command/user/mcp/ListMcpTokensCmd.java | 71 +++++++ .../command/user/mcp/RevokeMcpTokenCmd.java | 71 +++++++ .../api/response/McpTokenResponse.java | 98 +++++++++ .../org/apache/cloudstack/mcp/McpToken.java | 36 ++++ .../cloudstack/mcp/McpTokenService.java | 54 +++++ .../org/apache/cloudstack/mcp/McpTokenVO.java | 142 +++++++++++++ .../cloudstack/mcp/dao/McpTokenDao.java | 30 +++ .../cloudstack/mcp/dao/McpTokenDaoImpl.java | 60 ++++++ ...spring-engine-schema-core-daos-context.xml | 1 + .../META-INF/db/schema-42300to2400.sql | 20 ++ .../framework/config/ConfigKey.java | 2 + .../cloudstack/mcp/McpTokenManagerImpl.java | 186 +++++++++++++++++ .../spring-server-core-managers-context.xml | 2 + .../mcp/McpTokenManagerImplTest.java | 191 ++++++++++++++++++ tools/apidoc/gen_toc.py | 1 + 17 files changed, 1046 insertions(+) create mode 100644 api/src/main/java/org/apache/cloudstack/api/command/user/mcp/CreateMcpTokenCmd.java create mode 100644 api/src/main/java/org/apache/cloudstack/api/command/user/mcp/ListMcpTokensCmd.java create mode 100644 api/src/main/java/org/apache/cloudstack/api/command/user/mcp/RevokeMcpTokenCmd.java create mode 100644 api/src/main/java/org/apache/cloudstack/api/response/McpTokenResponse.java create mode 100644 api/src/main/java/org/apache/cloudstack/mcp/McpToken.java create mode 100644 api/src/main/java/org/apache/cloudstack/mcp/McpTokenService.java create mode 100644 engine/schema/src/main/java/org/apache/cloudstack/mcp/McpTokenVO.java create mode 100644 engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java create mode 100644 engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java create mode 100644 server/src/main/java/org/apache/cloudstack/mcp/McpTokenManagerImpl.java create mode 100644 server/src/test/java/org/apache/cloudstack/mcp/McpTokenManagerImplTest.java diff --git a/api/src/main/java/com/cloud/event/EventTypes.java b/api/src/main/java/com/cloud/event/EventTypes.java index 069886b7b09f..e849009f7ec7 100644 --- a/api/src/main/java/com/cloud/event/EventTypes.java +++ b/api/src/main/java/com/cloud/event/EventTypes.java @@ -333,6 +333,10 @@ public class EventTypes { public static final String EVENT_DELETE_SECRET_API_KEY = "DELETE.USER.KEY"; public static final String API_KEY_ACCESS_UPDATE = "API.KEY.ACCESS.UPDATE"; + // MCP (Model Context Protocol) server tokens + public static final String EVENT_MCP_TOKEN_CREATE = "MCP.TOKEN.CREATE"; + public static final String EVENT_MCP_TOKEN_REVOKE = "MCP.TOKEN.REVOKE"; + // Template Events public static final String EVENT_TEMPLATE_CREATE = "TEMPLATE.CREATE"; public static final String EVENT_TEMPLATE_DELETE = "TEMPLATE.DELETE"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/CreateMcpTokenCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/CreateMcpTokenCmd.java new file mode 100644 index 000000000000..2d9cb31a5d63 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/CreateMcpTokenCmd.java @@ -0,0 +1,77 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.mcp; + +import java.util.Date; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.McpTokenResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.mcp.McpTokenService; + +@APICommand(name = "createMcpToken", + description = "Creates an access token for the MCP (Model Context Protocol) server, owned by the calling user. " + + "The token is returned only by this call and cannot be retrieved later.", + responseObject = McpTokenResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = true, + authorized = {RoleType.User, RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin}, + since = "24.0.0") +public class CreateMcpTokenCmd extends BaseCmd { + @Inject + private McpTokenService mcpTokenService; + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of the token.") + private String name; + + @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, length = 1024, description = "Description of the token.") + private String description; + + @Parameter(name = ApiConstants.END_DATE, type = CommandType.DATE, description = "Expiration date of the token. If not informed, the token does not expire. " + + ApiConstants.PARAMETER_DESCRIPTION_END_DATE_POSSIBLE_FORMATS) + private Date endDate; + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public Date getEndDate() { + return endDate; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccountId(); + } + + @Override + public void execute() { + McpTokenResponse response = mcpTokenService.createToken(this); + response.setResponseName(getCommandName()); + setResponseObject(response); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/ListMcpTokensCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/ListMcpTokensCmd.java new file mode 100644 index 000000000000..19a2c271205c --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/ListMcpTokensCmd.java @@ -0,0 +1,71 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.mcp; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.ACL; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.McpTokenResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.mcp.McpTokenService; + +@APICommand(name = "listMcpTokens", + description = "Lists the access tokens for the MCP (Model Context Protocol) server of a user. The tokens themselves are never returned.", + responseObject = McpTokenResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.User, RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin}, + since = "24.0.0") +public class ListMcpTokensCmd extends BaseListCmd { + @Inject + private McpTokenService mcpTokenService; + + @ACL + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = McpTokenResponse.class, description = "ID of the token.") + private Long id; + + @Parameter(name = ApiConstants.USER_ID, type = CommandType.UUID, entityType = UserResponse.class, + description = "ID of the user that owns the tokens. Defaults to the calling user.") + private Long userId; + + public Long getId() { + return id; + } + + public Long getUserId() { + return userId; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccountId(); + } + + @Override + public void execute() { + ListResponse response = mcpTokenService.listTokens(this); + response.setResponseName(getCommandName()); + setResponseObject(response); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/RevokeMcpTokenCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/RevokeMcpTokenCmd.java new file mode 100644 index 000000000000..62491083b5a6 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/mcp/RevokeMcpTokenCmd.java @@ -0,0 +1,71 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.mcp; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.ACL; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.McpTokenResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.mcp.McpToken; +import org.apache.cloudstack.mcp.McpTokenService; + +import com.cloud.user.Account; + +@APICommand(name = "revokeMcpToken", + description = "Revokes an access token for the MCP (Model Context Protocol) server.", + responseObject = SuccessResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.User, RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin}, + since = "24.0.0") +public class RevokeMcpTokenCmd extends BaseCmd { + @Inject + private McpTokenService mcpTokenService; + + @ACL + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = McpTokenResponse.class, required = true, description = "ID of the token to be revoked.") + private Long id; + + public Long getId() { + return id; + } + + @Override + public long getEntityOwnerId() { + McpToken token = mcpTokenService.findById(id); + if (token != null) { + return token.getAccountId(); + } + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute() { + if (!mcpTokenService.revokeToken(this)) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to revoke the MCP token."); + } + setResponseObject(new SuccessResponse(getCommandName())); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/McpTokenResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/McpTokenResponse.java new file mode 100644 index 000000000000..1138853f1e16 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/McpTokenResponse.java @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import java.util.Date; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.mcp.McpToken; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value = McpToken.class) +public class McpTokenResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) + @Param(description = "ID of the MCP token.") + private String id; + + @SerializedName(ApiConstants.NAME) + @Param(description = "Name of the MCP token.") + private String name; + + @SerializedName(ApiConstants.DESCRIPTION) + @Param(description = "Description of the MCP token.") + private String description; + + @SerializedName(ApiConstants.USER_ID) + @Param(description = "ID of the user that owns the MCP token.") + private String userId; + + @SerializedName(ApiConstants.USERNAME) + @Param(description = "Username of the owner of the MCP token.") + private String username; + + @SerializedName(ApiConstants.END_DATE) + @Param(description = "Expiration date of the MCP token.") + private Date endDate; + + @SerializedName(ApiConstants.CREATED) + @Param(description = "Creation date of the MCP token.") + private Date created; + + @SerializedName(ApiConstants.TOKEN) + @Param(description = "The MCP token. Only returned when the token is created.", isSensitive = true) + private String token; + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public void setUsername(String username) { + this.username = username; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public void setCreated(Date created) { + this.created = created; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/mcp/McpToken.java b/api/src/main/java/org/apache/cloudstack/mcp/McpToken.java new file mode 100644 index 000000000000..66377314ee08 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/mcp/McpToken.java @@ -0,0 +1,36 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.mcp; + +import java.util.Date; + +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +/** + * Access token for the MCP (Model Context Protocol) server. Only the hash of the token is stored. + */ +public interface McpToken extends ControlledEntity, InternalIdentity, Identity { + long getUserId(); + + String getDescription(); + + Date getEndDate(); + + Date getCreated(); +} diff --git a/api/src/main/java/org/apache/cloudstack/mcp/McpTokenService.java b/api/src/main/java/org/apache/cloudstack/mcp/McpTokenService.java new file mode 100644 index 000000000000..9963b4dc9123 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/mcp/McpTokenService.java @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.mcp; + +import org.apache.cloudstack.api.command.user.mcp.CreateMcpTokenCmd; +import org.apache.cloudstack.api.command.user.mcp.ListMcpTokensCmd; +import org.apache.cloudstack.api.command.user.mcp.RevokeMcpTokenCmd; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.McpTokenResponse; +import org.apache.cloudstack.framework.config.ConfigKey; + +public interface McpTokenService { + String TOKEN_PREFIX = "csmcp_"; + + ConfigKey McpEnabled = new ConfigKey<>(Boolean.class, "mcp.enabled", ConfigKey.CATEGORY_ADVANCED, "false", + "Enables the MCP (Model Context Protocol) server of the management server, available at /client/mcp.", + true, ConfigKey.Scope.Global, null, "MCP server enabled", + null, ConfigKey.GROUP_MCP, ConfigKey.SUBGROUP_MCP_SERVER); + + ConfigKey McpAsyncJobWait = new ConfigKey<>(Integer.class, "mcp.async.job.wait", ConfigKey.CATEGORY_ADVANCED, "20", + "Maximum time, in seconds, an MCP tool call waits for an asynchronous job to finish before returning the pending job ID.", + true, ConfigKey.Scope.Global, null, "MCP async job wait", + null, ConfigKey.GROUP_MCP, ConfigKey.SUBGROUP_MCP_SERVER); + + /** + * Creates a token for the calling user. The returned response is the only place where the token itself is available. + */ + McpTokenResponse createToken(CreateMcpTokenCmd cmd); + + ListResponse listTokens(ListMcpTokensCmd cmd); + + boolean revokeToken(RevokeMcpTokenCmd cmd); + + McpToken findById(long id); + + /** + * @return the token entity matching the given token, or null if it does not exist, was revoked or has expired. + */ + McpToken authenticate(String token); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/mcp/McpTokenVO.java b/engine/schema/src/main/java/org/apache/cloudstack/mcp/McpTokenVO.java new file mode 100644 index 000000000000..21623621b0bf --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/mcp/McpTokenVO.java @@ -0,0 +1,142 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.mcp; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name = "mcp_token") +public class McpTokenVO implements McpToken { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private long id; + + @Column(name = "uuid", nullable = false) + private String uuid = UUID.randomUUID().toString(); + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "description", length = 1024) + private String description; + + @Column(name = "user_id", nullable = false) + private long userId; + + @Column(name = "account_id", nullable = false) + private long accountId; + + @Column(name = "domain_id", nullable = false) + private long domainId; + + @Column(name = "token_hash", nullable = false) + private String tokenHash; + + @Column(name = "end_date") + @Temporal(value = TemporalType.TIMESTAMP) + private Date endDate; + + @Column(name = "created", nullable = false) + @Temporal(value = TemporalType.TIMESTAMP) + private Date created = new Date(); + + @Column(name = "removed") + @Temporal(value = TemporalType.TIMESTAMP) + private Date removed; + + public McpTokenVO() { + } + + public McpTokenVO(String name, String description, long userId, long accountId, long domainId, String tokenHash, Date endDate) { + this.name = name; + this.description = description; + this.userId = userId; + this.accountId = accountId; + this.domainId = domainId; + this.tokenHash = tokenHash; + this.endDate = endDate; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public long getUserId() { + return userId; + } + + @Override + public long getAccountId() { + return accountId; + } + + @Override + public long getDomainId() { + return domainId; + } + + public String getTokenHash() { + return tokenHash; + } + + @Override + public Date getEndDate() { + return endDate; + } + + @Override + public Date getCreated() { + return created; + } + + public Date getRemoved() { + return removed; + } + + @Override + public Class getEntityType() { + return McpToken.class; + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java new file mode 100644 index 000000000000..b3aed029ef77 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.mcp.dao; + +import java.util.List; + +import org.apache.cloudstack.mcp.McpTokenVO; + +import com.cloud.utils.Pair; +import com.cloud.utils.db.GenericDao; + +public interface McpTokenDao extends GenericDao { + McpTokenVO findByTokenHash(String tokenHash); + + Pair, Integer> listByUserId(long userId, Long startIndex, Long pageSize); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java new file mode 100644 index 000000000000..b9c5577c9a41 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java @@ -0,0 +1,60 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.mcp.dao; + +import java.util.List; + +import org.apache.cloudstack.mcp.McpTokenVO; +import org.springframework.stereotype.Component; + +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Component +public class McpTokenDaoImpl extends GenericDaoBase implements McpTokenDao { + private static final String ID = "id"; + private static final String USER_ID = "userId"; + private static final String TOKEN_HASH = "tokenHash"; + + private final SearchBuilder tokenSearch; + + public McpTokenDaoImpl() { + super(); + + tokenSearch = createSearchBuilder(); + tokenSearch.and(TOKEN_HASH, tokenSearch.entity().getTokenHash(), SearchCriteria.Op.EQ); + tokenSearch.and(USER_ID, tokenSearch.entity().getUserId(), SearchCriteria.Op.EQ); + tokenSearch.done(); + } + + @Override + public McpTokenVO findByTokenHash(String tokenHash) { + SearchCriteria sc = tokenSearch.create(); + sc.setParameters(TOKEN_HASH, tokenHash); + return findOneBy(sc); + } + + @Override + public Pair, Integer> listByUserId(long userId, Long startIndex, Long pageSize) { + SearchCriteria sc = tokenSearch.create(); + sc.setParameters(USER_ID, userId); + return searchAndCount(sc, new Filter(McpTokenVO.class, ID, true, startIndex, pageSize)); + } +} diff --git a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml index b199284e3b5e..494be908a1e3 100644 --- a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml +++ b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml @@ -329,6 +329,7 @@ + diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql b/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql index 541caae23c11..27b7d6260f9f 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql @@ -271,3 +271,23 @@ CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.disk_offering', 'error_policy', 'VAR -- Rename persisted FlashArray provider name (plugin getName() changed from 'Flash Array' to 'FlashArray') UPDATE `cloud`.`storage_pool` SET `storage_provider_name` = 'FlashArray' WHERE `storage_provider_name` = 'Flash Array'; + +-- Access tokens for the MCP (Model Context Protocol) server. Only the SHA-256 hash of each token is stored. +CREATE TABLE IF NOT EXISTS `cloud`.`mcp_token` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT, + `uuid` varchar(40) NOT NULL, + `name` varchar(255) NOT NULL, + `description` varchar(1024) DEFAULT NULL, + `user_id` bigint unsigned NOT NULL COMMENT 'user that owns the token', + `account_id` bigint unsigned NOT NULL, + `domain_id` bigint unsigned NOT NULL, + `token_hash` char(64) NOT NULL COMMENT 'SHA-256 hash of the token, in hexadecimal', + `end_date` datetime DEFAULT NULL COMMENT 'expiration date, null if the token does not expire', + `created` datetime NOT NULL COMMENT 'date created', + `removed` datetime DEFAULT NULL COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `uc_mcp_token__uuid` UNIQUE (`uuid`), + CONSTRAINT `uc_mcp_token__token_hash` UNIQUE (`token_hash`), + CONSTRAINT `fk_mcp_token__user_id` FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON DELETE CASCADE, + INDEX `i_mcp_token__removed` (`removed`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java b/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java index fd007f12957b..2068c0562d6d 100644 --- a/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java +++ b/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java @@ -55,6 +55,7 @@ public class ConfigKey { public static final Ternary GROUP_SYSTEM_VMS = new Ternary<>("System VMs", "System VMs related configuration", 7L); public static final Ternary GROUP_INFRASTRUCTURE = new Ternary<>("Infrastructure", "Infrastructure configuration", 8L); public static final Ternary GROUP_USAGE_SERVER = new Ternary<>("Usage Server", "Usage Server related configuration", 9L); + public static final Ternary GROUP_MCP = new Ternary<>("MCP", "Model Context Protocol (MCP) server configuration", 10L); // Configuration Subgroups to be used to define subgroup for a config key // Subgroup name, description, precedence @@ -98,6 +99,7 @@ public class ConfigKey { public static final Pair SUBGROUP_BACKUP_AND_RECOVERY = new Pair<>("Backup & Recovery", 1L); public static final Pair SUBGROUP_CERTIFICATE_AUTHORITY = new Pair<>("Certificate Authority", 2L); public static final Pair SUBGROUP_QUOTA = new Pair<>("Quota", 3L); + public static final Pair SUBGROUP_MCP_SERVER = new Pair<>("MCP Server", 1L); public static final Pair SUBGROUP_CLOUDIAN = new Pair<>("Cloudian", 4L); public static final Pair SUBGROUP_DRS = new Pair<>("DRS", 4L); diff --git a/server/src/main/java/org/apache/cloudstack/mcp/McpTokenManagerImpl.java b/server/src/main/java/org/apache/cloudstack/mcp/McpTokenManagerImpl.java new file mode 100644 index 000000000000..995930eaa33e --- /dev/null +++ b/server/src/main/java/org/apache/cloudstack/mcp/McpTokenManagerImpl.java @@ -0,0 +1,186 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.mcp; + +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.inject.Inject; + +import org.apache.cloudstack.api.command.user.mcp.CreateMcpTokenCmd; +import org.apache.cloudstack.api.command.user.mcp.ListMcpTokensCmd; +import org.apache.cloudstack.api.command.user.mcp.RevokeMcpTokenCmd; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.McpTokenResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.Configurable; +import org.apache.cloudstack.mcp.dao.McpTokenDao; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; + +import com.cloud.event.ActionEvent; +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.user.Account; +import com.cloud.user.AccountService; +import com.cloud.user.User; +import com.cloud.user.dao.UserDao; +import com.cloud.utils.Pair; +import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.component.PluggableService; + +public class McpTokenManagerImpl extends ManagerBase implements McpTokenService, PluggableService, Configurable { + private static final int TOKEN_BYTES = 32; + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + @Inject + private McpTokenDao mcpTokenDao; + @Inject + private UserDao userDao; + @Inject + private AccountService accountService; + + @Override + @ActionEvent(eventType = EventTypes.EVENT_MCP_TOKEN_CREATE, eventDescription = "creating MCP token") + public McpTokenResponse createToken(CreateMcpTokenCmd cmd) { + User user = CallContext.current().getCallingUser(); + if (user.getId() == User.UID_SYSTEM) { + throw new PermissionDeniedException("MCP tokens cannot be created for the system user."); + } + + Date endDate = cmd.getEndDate(); + if (endDate != null && !endDate.after(new Date())) { + throw new InvalidParameterValueException("The MCP token cannot be created already expired, please inform an end date in the future."); + } + + Account account = CallContext.current().getCallingAccount(); + byte[] randomBytes = new byte[TOKEN_BYTES]; + SECURE_RANDOM.nextBytes(randomBytes); + String token = TOKEN_PREFIX + Base64.encodeBase64URLSafeString(randomBytes); + + McpTokenVO mcpToken = mcpTokenDao.persist(new McpTokenVO(cmd.getName(), cmd.getDescription(), user.getId(), account.getId(), + account.getDomainId(), DigestUtils.sha256Hex(token), endDate)); + + McpTokenResponse response = createResponse(mcpToken); + response.setToken(token); + return response; + } + + @Override + public ListResponse listTokens(ListMcpTokensCmd cmd) { + List tokens; + Integer count; + + if (cmd.getId() != null) { + tokens = List.of(findAccessibleToken(cmd.getId())); + count = 1; + } else { + long userId = CallContext.current().getCallingUserId(); + if (cmd.getUserId() != null) { + accountService.validateCallingUserHasAccessToDesiredUser(cmd.getUserId()); + userId = cmd.getUserId(); + } + Pair, Integer> result = mcpTokenDao.listByUserId(userId, cmd.getStartIndex(), cmd.getPageSizeVal()); + tokens = result.first(); + count = result.second(); + } + + List responses = new ArrayList<>(); + for (McpTokenVO token : tokens) { + responses.add(createResponse(token)); + } + ListResponse listResponse = new ListResponse<>(); + listResponse.setResponses(responses, count); + return listResponse; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_MCP_TOKEN_REVOKE, eventDescription = "revoking MCP token") + public boolean revokeToken(RevokeMcpTokenCmd cmd) { + return mcpTokenDao.remove(findAccessibleToken(cmd.getId()).getId()); + } + + @Override + public McpToken findById(long id) { + return mcpTokenDao.findById(id); + } + + @Override + public McpToken authenticate(String token) { + if (StringUtils.isBlank(token) || !token.startsWith(TOKEN_PREFIX)) { + return null; + } + McpTokenVO mcpToken = mcpTokenDao.findByTokenHash(DigestUtils.sha256Hex(token)); + if (mcpToken == null) { + return null; + } + if (mcpToken.getEndDate() != null && !mcpToken.getEndDate().after(new Date())) { + logger.debug("MCP token [{}] has expired on [{}].", mcpToken.getUuid(), mcpToken.getEndDate()); + return null; + } + return mcpToken; + } + + private McpTokenVO findAccessibleToken(long id) { + McpTokenVO token = mcpTokenDao.findById(id); + if (token == null) { + throw new InvalidParameterValueException("Unable to find the MCP token with the informed ID."); + } + accountService.validateCallingUserHasAccessToDesiredUser(token.getUserId()); + return token; + } + + private McpTokenResponse createResponse(McpTokenVO token) { + McpTokenResponse response = new McpTokenResponse(); + response.setId(token.getUuid()); + response.setName(token.getName()); + response.setDescription(token.getDescription()); + response.setEndDate(token.getEndDate()); + response.setCreated(token.getCreated()); + User user = userDao.findByIdIncludingRemoved(token.getUserId()); + if (user != null) { + response.setUserId(user.getUuid()); + response.setUsername(user.getUsername()); + } + response.setObjectName("mcptoken"); + return response; + } + + @Override + public List> getCommands() { + final List> cmdList = new ArrayList<>(); + cmdList.add(CreateMcpTokenCmd.class); + cmdList.add(ListMcpTokensCmd.class); + cmdList.add(RevokeMcpTokenCmd.class); + return cmdList; + } + + @Override + public String getConfigComponentName() { + return McpTokenService.class.getSimpleName(); + } + + @Override + public ConfigKey[] getConfigKeys() { + return new ConfigKey[] {McpEnabled, McpAsyncJobWait}; + } +} diff --git a/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml b/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml index 61b5b541bc75..820725826231 100644 --- a/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml +++ b/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml @@ -45,6 +45,8 @@ + + diff --git a/server/src/test/java/org/apache/cloudstack/mcp/McpTokenManagerImplTest.java b/server/src/test/java/org/apache/cloudstack/mcp/McpTokenManagerImplTest.java new file mode 100644 index 000000000000..16f85e231d55 --- /dev/null +++ b/server/src/test/java/org/apache/cloudstack/mcp/McpTokenManagerImplTest.java @@ -0,0 +1,191 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.mcp; + +import java.util.Date; + +import org.apache.cloudstack.api.command.user.mcp.CreateMcpTokenCmd; +import org.apache.cloudstack.api.command.user.mcp.RevokeMcpTokenCmd; +import org.apache.cloudstack.api.response.McpTokenResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.mcp.dao.McpTokenDao; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.user.Account; +import com.cloud.user.AccountService; +import com.cloud.user.User; +import com.cloud.user.dao.UserDao; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class McpTokenManagerImplTest { + private static final long USER_ID = 42L; + private static final long ACCOUNT_ID = 7L; + private static final long DOMAIN_ID = 3L; + private static final long DAY_IN_MILLIS = 24L * 60 * 60 * 1000; + + @Mock + private McpTokenDao mcpTokenDao; + @Mock + private UserDao userDao; + @Mock + private AccountService accountService; + @Mock + private User user; + @Mock + private Account account; + @Mock + private CreateMcpTokenCmd createCmd; + @Mock + private RevokeMcpTokenCmd revokeCmd; + + @InjectMocks + private McpTokenManagerImpl manager; + + @Before + public void setUp() { + Mockito.when(user.getId()).thenReturn(USER_ID); + Mockito.when(account.getId()).thenReturn(ACCOUNT_ID); + Mockito.when(account.getDomainId()).thenReturn(DOMAIN_ID); + CallContext.register(user, account); + + Mockito.when(createCmd.getName()).thenReturn("my-token"); + Mockito.when(mcpTokenDao.persist(Mockito.any(McpTokenVO.class))).thenAnswer(invocation -> invocation.getArgument(0)); + } + + @After + public void tearDown() { + CallContext.unregister(); + } + + private McpTokenVO tokenExpiringAt(Date endDate) { + return new McpTokenVO("my-token", null, USER_ID, ACCOUNT_ID, DOMAIN_ID, "hash", endDate); + } + + @Test + public void createTokenPersistsOnlyTheHashOfTheToken() { + McpTokenResponse response = manager.createToken(createCmd); + + String token = response.getToken(); + Assert.assertTrue(token.startsWith(McpTokenService.TOKEN_PREFIX)); + + ArgumentCaptor captor = ArgumentCaptor.forClass(McpTokenVO.class); + Mockito.verify(mcpTokenDao).persist(captor.capture()); + McpTokenVO persisted = captor.getValue(); + Assert.assertEquals(DigestUtils.sha256Hex(token), persisted.getTokenHash()); + Assert.assertNotEquals(token, persisted.getTokenHash()); + Assert.assertEquals("my-token", persisted.getName()); + Assert.assertEquals(USER_ID, persisted.getUserId()); + Assert.assertEquals(ACCOUNT_ID, persisted.getAccountId()); + Assert.assertEquals(DOMAIN_ID, persisted.getDomainId()); + } + + @Test + public void createTokenGeneratesADifferentTokenOnEachCall() { + Assert.assertNotEquals(manager.createToken(createCmd).getToken(), manager.createToken(createCmd).getToken()); + } + + @Test(expected = InvalidParameterValueException.class) + public void createTokenRejectsAnEndDateInThePast() { + Mockito.when(createCmd.getEndDate()).thenReturn(new Date(System.currentTimeMillis() - DAY_IN_MILLIS)); + manager.createToken(createCmd); + } + + @Test(expected = PermissionDeniedException.class) + public void createTokenRejectsTheSystemUser() { + Mockito.when(user.getId()).thenReturn(User.UID_SYSTEM); + manager.createToken(createCmd); + } + + @Test + public void authenticateReturnsTheTokenMatchingTheHash() { + String token = McpTokenService.TOKEN_PREFIX + "abc"; + McpTokenVO stored = tokenExpiringAt(new Date(System.currentTimeMillis() + DAY_IN_MILLIS)); + Mockito.when(mcpTokenDao.findByTokenHash(DigestUtils.sha256Hex(token))).thenReturn(stored); + + Assert.assertSame(stored, manager.authenticate(token)); + } + + @Test + public void authenticateAcceptsATokenWithoutEndDate() { + String token = McpTokenService.TOKEN_PREFIX + "abc"; + McpTokenVO stored = tokenExpiringAt(null); + Mockito.when(mcpTokenDao.findByTokenHash(DigestUtils.sha256Hex(token))).thenReturn(stored); + + Assert.assertSame(stored, manager.authenticate(token)); + } + + @Test + public void authenticateRejectsAnExpiredToken() { + String token = McpTokenService.TOKEN_PREFIX + "abc"; + Mockito.when(mcpTokenDao.findByTokenHash(DigestUtils.sha256Hex(token))) + .thenReturn(tokenExpiringAt(new Date(System.currentTimeMillis() - DAY_IN_MILLIS))); + + Assert.assertNull(manager.authenticate(token)); + } + + @Test + public void authenticateRejectsAnUnknownOrRevokedToken() { + Assert.assertNull(manager.authenticate(McpTokenService.TOKEN_PREFIX + "unknown")); + } + + @Test + public void authenticateRejectsValuesThatAreNotMcpTokensWithoutQueryingTheDatabase() { + Assert.assertNull(manager.authenticate(null)); + Assert.assertNull(manager.authenticate("")); + Assert.assertNull(manager.authenticate("some-api-key")); + Mockito.verifyNoInteractions(mcpTokenDao); + } + + @Test + public void revokeTokenRemovesTheToken() { + McpTokenVO stored = tokenExpiringAt(null); + Mockito.when(revokeCmd.getId()).thenReturn(5L); + Mockito.when(mcpTokenDao.findById(5L)).thenReturn(stored); + Mockito.when(mcpTokenDao.remove(stored.getId())).thenReturn(true); + + Assert.assertTrue(manager.revokeToken(revokeCmd)); + Mockito.verify(accountService).validateCallingUserHasAccessToDesiredUser(USER_ID); + } + + @Test + public void revokeTokenOfAnInaccessibleUserIsDenied() { + Mockito.when(revokeCmd.getId()).thenReturn(5L); + Mockito.when(mcpTokenDao.findById(5L)).thenReturn(tokenExpiringAt(null)); + Mockito.doThrow(new PermissionDeniedException("denied")).when(accountService).validateCallingUserHasAccessToDesiredUser(USER_ID); + + Assert.assertThrows(PermissionDeniedException.class, () -> manager.revokeToken(revokeCmd)); + Mockito.verify(mcpTokenDao, Mockito.never()).remove(Mockito.anyLong()); + } + + @Test(expected = InvalidParameterValueException.class) + public void revokeTokenThatDoesNotExistFails() { + Mockito.when(revokeCmd.getId()).thenReturn(5L); + manager.revokeToken(revokeCmd); + } +} diff --git a/tools/apidoc/gen_toc.py b/tools/apidoc/gen_toc.py index 30b97bedabd1..cabbb1d96de0 100644 --- a/tools/apidoc/gen_toc.py +++ b/tools/apidoc/gen_toc.py @@ -258,6 +258,7 @@ 'SharedFileSystem': 'Shared FileSystem', 'Webhook': 'Webhook', 'Webhooks': 'Webhook', + 'McpToken': 'MCP', 'purgeExpungedResources': 'Resource', 'forgotPassword': 'Authentication', 'resetPassword': 'Authentication', From 999ededabcb87617a8d7222d045e2ce914820018 Mon Sep 17 00:00:00 2001 From: Francisco Ewerton de Araujo Silva Date: Sun, 22 Nov 2026 14:05:00 -0300 Subject: [PATCH 2/5] feat(mcp): serve the MCP protocol at /client/mcp Add a servlet that implements the Streamable HTTP transport of the Model Context Protocol without streaming and without sessions, for the protocol revisions 2025-06-18 and 2025-11-25. Requests are authenticated with an MCP token and run as the user that owns it. Instead of one tool per API, four tools search, describe and execute any API available to the user and query asynchronous jobs. APIs go through ApiServerService, so the role permissions, the allowed source CIDRs, the API rate limit and the project roles apply as in /client/api. The server is off by default (mcp.enabled). --- .../cloudstack/api/ApiServerService.java | 3 + client/src/main/webapp/WEB-INF/web.xml | 11 + .../main/java/com/cloud/api/ApiServer.java | 3 +- .../main/java/com/cloud/api/ApiServlet.java | 8 +- .../java/com/cloud/api/McpParamEncoder.java | 102 +++ .../main/java/com/cloud/api/McpServlet.java | 619 ++++++++++++++++++ .../com/cloud/api/McpParamEncoderTest.java | 82 +++ .../java/com/cloud/api/McpServletTest.java | 516 +++++++++++++++ 8 files changed, 1339 insertions(+), 5 deletions(-) create mode 100644 server/src/main/java/com/cloud/api/McpParamEncoder.java create mode 100644 server/src/main/java/com/cloud/api/McpServlet.java create mode 100644 server/src/test/java/com/cloud/api/McpParamEncoderTest.java create mode 100644 server/src/test/java/com/cloud/api/McpServletTest.java diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java b/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java index 1ee41ac86c22..0184371ee441 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java @@ -26,6 +26,7 @@ import com.cloud.domain.Domain; import com.cloud.exception.CloudAuthenticationException; import com.cloud.user.Account; +import com.cloud.user.User; import com.cloud.user.UserAccount; public interface ApiServerService { @@ -40,6 +41,8 @@ public ResponseObject loginUser(HttpSession session, String username, String pas public boolean verifyUser(Long userId); + boolean verifyApiKeyAccessAllowed(User user, Account account); + public String getSerializedApiError(int errorCode, String errorText, Map apiCommandParams, String responseType); public String getSerializedApiError(ServerApiException ex, Map apiCommandParams, String responseType); diff --git a/client/src/main/webapp/WEB-INF/web.xml b/client/src/main/webapp/WEB-INF/web.xml index 43bee7e59d88..245ca70ea599 100644 --- a/client/src/main/webapp/WEB-INF/web.xml +++ b/client/src/main/webapp/WEB-INF/web.xml @@ -54,6 +54,12 @@ 6 + + mcpServlet + com.cloud.api.McpServlet + 7 + + apiServlet /api/* @@ -64,6 +70,11 @@ /console + + mcpServlet + /mcp + + java.lang.Exception /error.html diff --git a/server/src/main/java/com/cloud/api/ApiServer.java b/server/src/main/java/com/cloud/api/ApiServer.java index 083f4629740f..0203f6098c12 100644 --- a/server/src/main/java/com/cloud/api/ApiServer.java +++ b/server/src/main/java/com/cloud/api/ApiServer.java @@ -962,7 +962,8 @@ private void buildAuditTrail(final StringBuilder auditTrailSb, final String comm } } - protected boolean verifyApiKeyAccessAllowed(User user, Account account) { + @Override + public boolean verifyApiKeyAccessAllowed(User user, Account account) { Boolean apiKeyAccessEnabled = user.getApiKeyAccess(); if (apiKeyAccessEnabled != null) { if (Boolean.TRUE.equals(apiKeyAccessEnabled)) { diff --git a/server/src/main/java/com/cloud/api/ApiServlet.java b/server/src/main/java/com/cloud/api/ApiServlet.java index f5ca18449fe1..d11c304d3e73 100644 --- a/server/src/main/java/com/cloud/api/ApiServlet.java +++ b/server/src/main/java/com/cloud/api/ApiServlet.java @@ -390,7 +390,7 @@ void processRequestInContext(final HttpServletRequest req, final HttpServletResp } else { CallContext.register(accountMgr.getSystemUser(), accountMgr.getSystemAccount()); } - setProjectContext(params); + setProjectContext(params, projectDao); setGuiThemeParameterIfApiCallIsUnauthenticated(userId, command, req, params); if (LOGGER.isTraceEnabled()) { @@ -403,7 +403,7 @@ void processRequestInContext(final HttpServletRequest req, final HttpServletResp // Add the HTTP method (GET/POST/PUT/DELETE) as well into the params map. params.put("httpmethod", new String[]{req.getMethod()}); - setProjectContext(params); + setProjectContext(params, projectDao); setClientAddressForConsoleEndpointAccess(command, params, req); final String response = apiServer.handleRequest(params, responseType, auditTrailSb); HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType, ApiServer.JSONContentType.value()); @@ -674,7 +674,7 @@ public static void invalidateHttpSession(HttpSession session, String msg) { } } - private void setProjectContext(Map requestParameters) { + static void setProjectContext(Map requestParameters, ProjectDao projectDao) { final String[] command = (String[])requestParameters.get(ApiConstants.COMMAND); if (command == null) { LOGGER.info("missing command, ignoring request..."); @@ -701,7 +701,7 @@ private void setProjectContext(Map requestParameters) { } } - private boolean isSpecificAPI(String commandName) { + private static boolean isSpecificAPI(String commandName) { List commands = Arrays.asList("suspendProject", "updateProject", "activateProject", "deleteProject"); if (commands.contains(commandName)) { return true; diff --git a/server/src/main/java/com/cloud/api/McpParamEncoder.java b/server/src/main/java/com/cloud/api/McpParamEncoder.java new file mode 100644 index 000000000000..86b5cb2ee39f --- /dev/null +++ b/server/src/main/java/com/cloud/api/McpParamEncoder.java @@ -0,0 +1,102 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +/** + * Converts the JSON arguments of an MCP tool call into CloudStack API parameters, using the same encoding as the query string of the API: + * lists are comma separated values and maps are name[index].field=value entries. + */ +public final class McpParamEncoder { + private static final Set RESERVED_PARAMETERS = Set.of("command", "response", "apikey", "signature", "signatureversion", "expires", + "sessionkey", "httpmethod"); + + private McpParamEncoder() { + } + + /** + * @throws IllegalArgumentException if a parameter is reserved or has a structure that the API cannot represent. + */ + public static Map encode(JsonObject parameters) { + Map encoded = new LinkedHashMap<>(); + for (Map.Entry parameter : parameters.entrySet()) { + String name = parameter.getKey(); + JsonElement value = parameter.getValue(); + if (RESERVED_PARAMETERS.contains(name.toLowerCase())) { + throw new IllegalArgumentException(String.format("Parameter [%s] is reserved and cannot be informed.", name)); + } + + if (value.isJsonNull()) { + continue; + } + if (value.isJsonPrimitive()) { + encoded.put(name, value.getAsString()); + } else if (value.isJsonObject()) { + encodeMapEntry(encoded, name, 0, value); + } else { + encodeArray(encoded, name, value.getAsJsonArray()); + } + } + return encoded; + } + + private static void encodeArray(Map encoded, String name, JsonArray array) { + if (array.size() == 0) { + return; + } + if (array.get(0).isJsonObject()) { + for (int index = 0; index < array.size(); index++) { + encodeMapEntry(encoded, name, index, array.get(index)); + } + return; + } + + List values = new ArrayList<>(); + for (JsonElement element : array) { + values.add(getPrimitive(name, element)); + } + encoded.put(name, String.join(",", values)); + } + + private static void encodeMapEntry(Map encoded, String name, int index, JsonElement entry) { + if (!entry.isJsonObject()) { + throw new IllegalArgumentException(String.format("Parameter [%s] mixes objects and plain values, which is not supported.", name)); + } + for (Map.Entry field : entry.getAsJsonObject().entrySet()) { + if (!field.getValue().isJsonNull()) { + encoded.put(String.format("%s[%d].%s", name, index, field.getKey()), getPrimitive(name, field.getValue())); + } + } + } + + private static String getPrimitive(String name, JsonElement value) { + if (!value.isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Parameter [%s] is nested deeper than the API supports: use a plain value, " + + "a list of plain values, an object of plain values or a list of such objects.", name)); + } + return value.getAsString(); + } +} diff --git a/server/src/main/java/com/cloud/api/McpServlet.java b/server/src/main/java/com/cloud/api/McpServlet.java new file mode 100644 index 000000000000..281a049cd980 --- /dev/null +++ b/server/src/main/java/com/cloud/api/McpServlet.java @@ -0,0 +1,619 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.ApiServerService; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.managed.context.ManagedContext; +import org.apache.cloudstack.mcp.McpToken; +import org.apache.cloudstack.mcp.McpTokenService; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; + +import com.cloud.projects.dao.ProjectDao; +import com.cloud.server.ManagementService; +import com.cloud.user.Account; +import com.cloud.user.AccountService; +import com.cloud.user.User; +import com.cloud.utils.HttpUtils; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; + +/** + * MCP (Model Context Protocol) server of the management server, using the Streamable HTTP transport without streaming and without sessions: + * each POST carries one JSON-RPC message and is answered with one JSON body. Requests are authenticated with an MCP token + * (see {@link McpTokenService}) and every API is executed through {@link ApiServerService}, as the calling user. + *

+ * Instead of one tool per API, the server exposes a few tools to search, describe and execute any API the user has access to. + */ +public class McpServlet extends HttpServlet { + protected static Logger LOGGER = LogManager.getLogger(McpServlet.class); + private static final Logger ACCESSLOGGER = LogManager.getLogger("apiserver." + McpServlet.class.getName()); + + // Protocol revisions based on the initialize handshake, newest first + static final List SUPPORTED_PROTOCOL_VERSIONS = List.of("2025-11-25", "2025-06-18"); + private static final String PROTOCOL_VERSION_HEADER = "MCP-Protocol-Version"; + // Revisions without handshake inform the version on each request, in the metadata of its parameters + private static final String PROTOCOL_VERSION_META = "io.modelcontextprotocol/protocolVersion"; + + static final int PARSE_ERROR = -32700; + static final int INVALID_REQUEST = -32600; + static final int METHOD_NOT_FOUND = -32601; + static final int INVALID_PARAMS = -32602; + static final int INTERNAL_ERROR = -32603; + static final int UNSUPPORTED_PROTOCOL_VERSION = -32022; + + static final String TOOL_SEARCH_APIS = "cloudstack_search_apis"; + static final String TOOL_DESCRIBE_API = "cloudstack_describe_api"; + static final String TOOL_EXECUTE_API = "cloudstack_execute_api"; + static final String TOOL_QUERY_ASYNC_JOB = "cloudstack_query_async_job"; + + private static final int MAX_SEARCH_RESULTS = 50; + private static final int JOB_STATUS_PENDING = 0; + private static final int JOB_STATUS_FAILED = 2; + + private static final String INSTRUCTIONS = "This server gives access to the Apache CloudStack API with the permissions of the user that owns the token. " + + "Find the API for a task with " + TOOL_SEARCH_APIS + ", check its parameters with " + TOOL_DESCRIBE_API + " and run it with " + TOOL_EXECUTE_API + ". " + + "IDs are UUIDs obtained from the list APIs. List APIs can return many entries: filter them with parameters such as keyword, name or id, " + + "and paginate with page and pagesize."; + + @Inject + ApiServerService apiServer; + @Inject + AccountService accountService; + @Inject + McpTokenService mcpTokenService; + @Inject + ManagedContext managedContext; + @Inject + ManagementService managementService; + @Inject + ProjectDao projectDao; + + long jobPollIntervalInMillis = 1000; + + @Override + public void init(final ServletConfig config) throws ServletException { + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + } + + boolean isEnabled() { + return McpTokenService.McpEnabled.value(); + } + + int getAsyncJobWait() { + return McpTokenService.McpAsyncJobWait.value(); + } + + /** + * Only POST is implemented: the other methods, used by the transport for streams and sessions, get the 405 of {@link HttpServlet}. + */ + @Override + protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { + if (!isEnabled()) { + resp.setStatus(HttpServletResponse.SC_NOT_FOUND); + return; + } + super.service(req, resp); + } + + @Override + protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) { + managedContext.runWithContext(() -> processRequest(req, resp)); + } + + void processRequest(final HttpServletRequest req, final HttpServletResponse resp) { + try { + if (!isOriginAllowed(req)) { + resp.setStatus(HttpServletResponse.SC_FORBIDDEN); + return; + } + + McpToken token = mcpTokenService.authenticate(getBearerToken(req)); + User user = token != null && apiServer.verifyUser(token.getUserId()) ? accountService.getActiveUser(token.getUserId()) : null; + Account account = user != null ? accountService.getAccount(user.getAccountId()) : null; + if (account == null || !apiServer.verifyApiKeyAccessAllowed(user, account)) { + resp.setHeader("WWW-Authenticate", "Bearer"); + resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return; + } + + InetAddress remoteAddress = ApiServlet.getClientAddress(req); + CallContext.register(user, account); + try { + processMessage(req, resp, user.getId(), remoteAddress); + } finally { + CallContext.unregister(); + } + } catch (IOException | RuntimeException e) { + LOGGER.error("Unexpected error while processing an MCP request", e); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + + /** + * Protection against DNS rebinding required by the transport: a browser page of another origin must not reach this endpoint. + */ + private boolean isOriginAllowed(HttpServletRequest req) { + String origin = req.getHeader("Origin"); + if (origin == null) { + return true; + } + try { + return req.getServerName().equalsIgnoreCase(new URI(origin).getHost()); + } catch (URISyntaxException e) { + return false; + } + } + + private String getBearerToken(HttpServletRequest req) { + String authorization = req.getHeader("Authorization"); + if (!StringUtils.startsWithIgnoreCase(authorization, "Bearer ")) { + return null; + } + return authorization.substring("Bearer ".length()).trim(); + } + + private void processMessage(HttpServletRequest req, HttpServletResponse resp, long userId, InetAddress remoteAddress) throws IOException { + JsonElement body; + try { + req.setCharacterEncoding("UTF-8"); + body = JsonParser.parseReader(req.getReader()); + } catch (JsonParseException e) { + writeResponse(resp, HttpServletResponse.SC_BAD_REQUEST, createError(null, PARSE_ERROR, "Parse error", null)); + return; + } + + JsonObject message = body.isJsonObject() ? body.getAsJsonObject() : new JsonObject(); + JsonElement id = message.get("id"); + String method = getString(message, "method"); + if (method == null) { + if (message.has("result") || message.has("error")) { + resp.setStatus(HttpServletResponse.SC_ACCEPTED); + } else { + writeResponse(resp, HttpServletResponse.SC_BAD_REQUEST, createError(id, INVALID_REQUEST, "Invalid Request", null)); + } + return; + } + + JsonObject params = message.get("params") instanceof JsonObject ? message.getAsJsonObject("params") : new JsonObject(); + String protocolVersion = getRequestProtocolVersion(req, params); + if (protocolVersion != null && !SUPPORTED_PROTOCOL_VERSIONS.contains(protocolVersion)) { + JsonObject data = new JsonObject(); + JsonArray supported = new JsonArray(); + SUPPORTED_PROTOCOL_VERSIONS.forEach(supported::add); + data.add("supported", supported); + data.addProperty("requested", protocolVersion); + writeResponse(resp, HttpServletResponse.SC_BAD_REQUEST, createError(id, UNSUPPORTED_PROTOCOL_VERSION, "Unsupported protocol version", data)); + return; + } + + if (id == null || id.isJsonNull()) { + resp.setStatus(HttpServletResponse.SC_ACCEPTED); + return; + } + + JsonObject response; + try { + response = createResult(id, processMethod(method, params, userId, remoteAddress)); + } catch (McpException e) { + response = createError(id, e.code, e.getMessage(), null); + } catch (RuntimeException e) { + LOGGER.error("Unexpected error while processing the MCP method [{}]", method, e); + response = createError(id, INTERNAL_ERROR, "Internal error", null); + } + writeResponse(resp, HttpServletResponse.SC_OK, response); + } + + private String getRequestProtocolVersion(HttpServletRequest req, JsonObject params) { + if (params.get("_meta") instanceof JsonObject) { + String version = getString(params.getAsJsonObject("_meta"), PROTOCOL_VERSION_META); + if (version != null) { + return version; + } + } + return req.getHeader(PROTOCOL_VERSION_HEADER); + } + + private JsonObject processMethod(String method, JsonObject params, long userId, InetAddress remoteAddress) throws McpException { + switch (method) { + case "initialize": + return initialize(params); + case "ping": + return new JsonObject(); + case "tools/list": + JsonObject tools = new JsonObject(); + tools.add("tools", createTools()); + return tools; + case "tools/call": + return callTool(params, userId, remoteAddress); + default: + throw new McpException(METHOD_NOT_FOUND, "Method not found: " + method); + } + } + + private JsonObject initialize(JsonObject params) { + String requestedVersion = getString(params, "protocolVersion"); + + JsonObject capabilities = new JsonObject(); + capabilities.add("tools", new JsonObject()); + JsonObject serverInfo = new JsonObject(); + serverInfo.addProperty("name", "cloudstack"); + serverInfo.addProperty("title", "Apache CloudStack"); + serverInfo.addProperty("version", managementService.getVersion()); + + JsonObject result = new JsonObject(); + result.addProperty("protocolVersion", SUPPORTED_PROTOCOL_VERSIONS.contains(requestedVersion) ? requestedVersion : SUPPORTED_PROTOCOL_VERSIONS.get(0)); + result.add("capabilities", capabilities); + result.add("serverInfo", serverInfo); + result.addProperty("instructions", INSTRUCTIONS); + return result; + } + + private JsonArray createTools() { + JsonArray tools = new JsonArray(); + tools.add(createTool(TOOL_SEARCH_APIS, "Search APIs", true, + "Searches the CloudStack APIs available to the user by name and description. Returns up to " + MAX_SEARCH_RESULTS + + " API names with their descriptions. API names follow the pattern verbResource, such as listVirtualMachines or createNetwork.", + Map.of("keyword", createProperty("string", "Words that must all be present in the name or in the description of the API, e.g. \"list virtualmachine\".")), + "keyword")); + tools.add(createTool(TOOL_DESCRIBE_API, "Describe API", true, + "Returns the description and the parameters of a CloudStack API: name, type, whether it is required and what it means. " + + "Use it before executing an API for the first time.", + Map.of("name", createProperty("string", "Exact name of the API, e.g. deployVirtualMachine.")), + "name")); + tools.add(createTool(TOOL_EXECUTE_API, "Execute API", false, + "Executes a CloudStack API as the user and returns its JSON response. This can create, change and destroy resources. " + + "For asynchronous APIs, waits for the job to finish for a limited time: if the job is still running, returns its jobid, " + + "to be used with " + TOOL_QUERY_ASYNC_JOB + ".", + Map.of("command", createProperty("string", "Exact name of the API, e.g. listVirtualMachines."), + "params", createProperty("object", "Parameters of the API, as described by " + TOOL_DESCRIBE_API + ". " + + "Parameters of type list take a JSON array of values. Parameters of type map take a JSON object, " + + "or an array of objects when the map has several entries, " + + "e.g. {\"details\": {\"cpuNumber\": 2}} or {\"iptonetworklist\": [{\"networkid\": \"...\", \"ip\": \"...\"}]}.")), + "command")); + tools.add(createTool(TOOL_QUERY_ASYNC_JOB, "Query asynchronous job", true, + "Waits for a limited time for an asynchronous job to finish and returns its status and result. " + + "The jobstatus is 0 while the job is running, 1 when it succeeded and 2 when it failed.", + Map.of("jobid", createProperty("string", "ID of the job, as returned by " + TOOL_EXECUTE_API + ".")), + "jobid")); + return tools; + } + + private JsonObject createProperty(String type, String description) { + JsonObject property = new JsonObject(); + property.addProperty("type", type); + property.addProperty("description", description); + return property; + } + + private JsonObject createTool(String name, String title, boolean readOnly, String description, Map properties, String required) { + JsonObject schemaProperties = new JsonObject(); + properties.forEach(schemaProperties::add); + JsonArray schemaRequired = new JsonArray(); + schemaRequired.add(required); + JsonObject inputSchema = new JsonObject(); + inputSchema.addProperty("type", "object"); + inputSchema.add("properties", schemaProperties); + inputSchema.add("required", schemaRequired); + + JsonObject annotations = new JsonObject(); + annotations.addProperty("readOnlyHint", readOnly); + if (!readOnly) { + annotations.addProperty("destructiveHint", true); + } + annotations.addProperty("openWorldHint", false); + + JsonObject tool = new JsonObject(); + tool.addProperty("name", name); + tool.addProperty("title", title); + tool.addProperty("description", description); + tool.add("inputSchema", inputSchema); + tool.add("annotations", annotations); + return tool; + } + + /** + * Failures of the tool itself, such as invalid arguments or an error returned by the API, are reported in the tool result, + * where the model can see them and correct the call. Only an unknown tool is a protocol error. + */ + private JsonObject callTool(JsonObject params, long userId, InetAddress remoteAddress) throws McpException { + String name = getString(params, "name"); + JsonObject arguments = params.get("arguments") instanceof JsonObject ? params.getAsJsonObject("arguments") : new JsonObject(); + try { + switch (StringUtils.defaultString(name)) { + case TOOL_SEARCH_APIS: + return createToolResult(searchApis(getRequiredArgument(arguments, "keyword"), userId, remoteAddress), false); + case TOOL_DESCRIBE_API: + return createToolResult(describeApi(getRequiredArgument(arguments, "name"), userId, remoteAddress), false); + case TOOL_EXECUTE_API: + return executeApi(arguments, userId, remoteAddress); + case TOOL_QUERY_ASYNC_JOB: + return createJobResult(waitForJob(getRequiredArgument(arguments, "jobid"), userId, remoteAddress, true)); + default: + throw new McpException(INVALID_PARAMS, "Unknown tool: " + name); + } + } catch (ServerApiException e) { + JsonObject error = new JsonObject(); + error.addProperty("errorcode", e.getErrorCode().getHttpCode()); + error.addProperty("errortext", e.getDescription()); + return createToolResult(error.toString(), true); + } catch (IllegalArgumentException e) { + return createToolResult(e.getMessage(), true); + } + } + + private String getRequiredArgument(JsonObject arguments, String name) { + String value = getString(arguments, name); + if (StringUtils.isBlank(value)) { + throw new IllegalArgumentException(String.format("The argument [%s] is required and must be a string.", name)); + } + return value; + } + + private String searchApis(String keyword, long userId, InetAddress remoteAddress) { + String[] terms = keyword.toLowerCase().trim().split("\\s+"); + List matches = new ArrayList<>(); + for (JsonElement element : listApis(null, userId, remoteAddress)) { + JsonObject api = element.getAsJsonObject(); + String name = getString(api, "name"); + String description = StringUtils.defaultString(getString(api, "description")); + String searchable = (name + " " + description).toLowerCase(); + if (Arrays.stream(terms).allMatch(searchable::contains)) { + boolean isAsync = api.has("isasync") && api.get("isasync").getAsBoolean(); + matches.add(String.format("%s%s: %s", name, isAsync ? " [async]" : "", description)); + } + } + + if (matches.isEmpty()) { + return String.format("No API found for [%s]. Try fewer or different words.", keyword); + } + int total = matches.size(); + List shown = matches.subList(0, Math.min(total, MAX_SEARCH_RESULTS)); + String header = total > MAX_SEARCH_RESULTS ? String.format("%d APIs found, showing the first %d. Refine the search to see the others.", total, MAX_SEARCH_RESULTS) + : String.format("%d APIs found.", total); + return header + "\n" + String.join("\n", shown); + } + + private String describeApi(String name, long userId, InetAddress remoteAddress) { + JsonArray apis = listApis(name, userId, remoteAddress); + if (apis.size() == 0) { + throw new IllegalArgumentException(String.format("The API [%s] does not exist or is not available to the user.", name)); + } + + // The description of the response of the API is left out: it is large and the response describes itself + JsonObject api = apis.get(0).getAsJsonObject(); + JsonObject description = new JsonObject(); + for (String field : List.of("name", "description", "isasync", "since")) { + if (api.has(field)) { + description.add(field, api.get(field)); + } + } + JsonArray parameters = new JsonArray(); + if (api.get("params") instanceof JsonArray) { + for (JsonElement element : api.getAsJsonArray("params")) { + JsonObject param = element.getAsJsonObject(); + JsonObject parameter = new JsonObject(); + for (String field : List.of("name", "type", "required", "description", "length", "related")) { + if (param.has(field)) { + parameter.add(field, param.get(field)); + } + } + parameters.add(parameter); + } + } + description.add("params", parameters); + return description.toString(); + } + + private JsonArray listApis(String name, long userId, InetAddress remoteAddress) { + Map params = new HashMap<>(); + params.put(ApiConstants.COMMAND, "listApis"); + if (name != null) { + params.put(ApiConstants.NAME, name); + } + JsonObject response = getResponseObject(callApi(params, userId, remoteAddress, true)); + return response.get("api") instanceof JsonArray ? response.getAsJsonArray("api") : new JsonArray(); + } + + private JsonObject executeApi(JsonObject arguments, long userId, InetAddress remoteAddress) { + String command = getRequiredArgument(arguments, "command"); + JsonElement apiParams = arguments.get("params"); + if (apiParams != null && !apiParams.isJsonNull() && !apiParams.isJsonObject()) { + throw new IllegalArgumentException("The argument [params] must be an object."); + } + + Map params = McpParamEncoder.encode(apiParams instanceof JsonObject ? apiParams.getAsJsonObject() : new JsonObject()); + params.put(ApiConstants.COMMAND, command); + String response = callApi(params, userId, remoteAddress, true); + + Class cmdClass = apiServer.getCmdClass(command); + if (cmdClass != null && BaseAsyncCmd.class.isAssignableFrom(cmdClass)) { + String jobId = getString(getResponseObject(response), ApiConstants.JOB_ID); + if (jobId != null) { + return createJobResult(waitForJob(jobId, userId, remoteAddress, false)); + } + } + return createToolResult(response, false); + } + + /** + * Polls the job until it finishes or the configured wait time is over, so the request does not outlive the timeouts of the HTTP + * connection. Only the first query is subject to the API access checks and to the API rate limit. + * + * @return the response of queryAsyncJobResult + */ + private String waitForJob(String jobId, long userId, InetAddress remoteAddress, boolean verifyFirstQuery) { + Map params = new HashMap<>(); + params.put(ApiConstants.COMMAND, "queryAsyncJobResult"); + params.put(ApiConstants.JOB_ID, jobId); + + long deadline = System.currentTimeMillis() + getAsyncJobWait() * 1000L; + String response = callApi(params, userId, remoteAddress, verifyFirstQuery); + while (getJobStatus(response) == JOB_STATUS_PENDING && System.currentTimeMillis() < deadline) { + try { + Thread.sleep(jobPollIntervalInMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + response = callApi(params, userId, remoteAddress, false); + } + return response; + } + + private int getJobStatus(String queryAsyncJobResultResponse) { + return getResponseObject(queryAsyncJobResultResponse).get(ApiConstants.JOB_STATUS).getAsInt(); + } + + private JsonObject createJobResult(String queryAsyncJobResultResponse) { + int status = getJobStatus(queryAsyncJobResultResponse); + JsonObject result = createToolResult(queryAsyncJobResultResponse, status == JOB_STATUS_FAILED); + if (status == JOB_STATUS_PENDING) { + result.getAsJsonArray("content").add(createTextContent("The job is still running. Call " + TOOL_QUERY_ASYNC_JOB + " with its jobid to wait for the result.")); + } + return result; + } + + /** + * Executes an API as the calling user, with the same checks of a request to the API endpoint authenticated by a session. + * + * @return the response of the API, serialized as JSON + */ + private String callApi(Map apiParams, long userId, InetAddress remoteAddress, boolean verify) { + String command = apiParams.get(ApiConstants.COMMAND); + Map params = new HashMap<>(); + apiParams.forEach((name, value) -> params.put(name, new String[] {value})); + params.put(ApiConstants.HTTPMETHOD, new String[] {"POST"}); + + ApiServlet.setProjectContext(params, projectDao); + if (verify && !apiServer.verifyRequest(params, userId, remoteAddress)) { + throw new ServerApiException(ApiErrorCode.UNAUTHORIZED, String.format("The command [%s] is not allowed from the address of the request.", command)); + } + + StringBuilder auditTrail = new StringBuilder(); + try { + String response = apiServer.handleRequest(params, HttpUtils.RESPONSE_TYPE_JSON, auditTrail); + if (response == null) { + throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, String.format("The command [%s] is not available through MCP.", command)); + } + return response; + } catch (ServerApiException e) { + auditTrail.append(" ").append(e.getErrorCode()).append(" ").append(e.getDescription()); + throw e; + } finally { + if (verify) { + // Parameter values are not logged, as they may hold sensitive data + ACCESSLOGGER.info("(userId={} accountId={}) {} -- MCP command={} params={}{}", userId, CallContext.current().getCallingAccountId(), + remoteAddress.getHostAddress(), command, apiParams.keySet(), auditTrail); + } + } + } + + /** + * @return the object that wraps the content of an API response, e.g. the value of "listzonesresponse" + */ + private JsonObject getResponseObject(String apiResponse) { + return JsonParser.parseString(apiResponse).getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject(); + } + + private String getString(JsonObject object, String name) { + JsonElement value = object.get(name); + return value != null && value.isJsonPrimitive() ? value.getAsString() : null; + } + + private JsonObject createTextContent(String text) { + JsonObject content = new JsonObject(); + content.addProperty("type", "text"); + content.addProperty("text", text); + return content; + } + + private JsonObject createToolResult(String text, boolean isError) { + JsonArray content = new JsonArray(); + content.add(createTextContent(text)); + JsonObject result = new JsonObject(); + result.add("content", content); + result.addProperty("isError", isError); + return result; + } + + private JsonObject createResult(JsonElement id, JsonObject result) { + JsonObject response = new JsonObject(); + response.addProperty("jsonrpc", "2.0"); + response.add("id", id); + response.add("result", result); + return response; + } + + private JsonObject createError(JsonElement id, int code, String message, JsonObject data) { + JsonObject error = new JsonObject(); + error.addProperty("code", code); + error.addProperty("message", message); + if (data != null) { + error.add("data", data); + } + JsonObject response = new JsonObject(); + response.addProperty("jsonrpc", "2.0"); + response.add("id", id == null ? JsonNull.INSTANCE : id); + response.add("error", error); + return response; + } + + private void writeResponse(HttpServletResponse resp, int status, JsonObject response) throws IOException { + resp.setStatus(status); + resp.setContentType("application/json"); + resp.setCharacterEncoding("UTF-8"); + resp.getWriter().print(response.toString()); + } + + private static class McpException extends Exception { + private final int code; + + McpException(int code, String message) { + super(message); + this.code = code; + } + } +} diff --git a/server/src/test/java/com/cloud/api/McpParamEncoderTest.java b/server/src/test/java/com/cloud/api/McpParamEncoderTest.java new file mode 100644 index 000000000000..e7cb68f1c2f2 --- /dev/null +++ b/server/src/test/java/com/cloud/api/McpParamEncoderTest.java @@ -0,0 +1,82 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api; + +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +import com.google.gson.JsonParser; + +public class McpParamEncoderTest { + + private Map encode(String json) { + return McpParamEncoder.encode(JsonParser.parseString(json).getAsJsonObject()); + } + + @Test + public void encodesPlainValuesAsStrings() { + Map encoded = encode("{\"name\": \"vm-1\", \"pagesize\": 20, \"listall\": true, \"cpuspeed\": 1.5}"); + + Assert.assertEquals(Map.of("name", "vm-1", "pagesize", "20", "listall", "true", "cpuspeed", "1.5"), encoded); + } + + @Test + public void ignoresNullValues() { + Assert.assertEquals(Map.of("name", "vm-1"), encode("{\"name\": \"vm-1\", \"keyword\": null, \"details\": {\"a\": null}}")); + } + + @Test + public void encodesListsAsCommaSeparatedValues() { + Assert.assertEquals(Map.of("ids", "a,b,c", "ports", "80,443"), encode("{\"ids\": [\"a\", \"b\", \"c\"], \"ports\": [80, 443], \"empty\": []}")); + } + + @Test + public void encodesAnObjectAsTheFirstEntryOfAMap() { + Assert.assertEquals(Map.of("details[0].cpuNumber", "2", "details[0].memory", "1024"), + encode("{\"details\": {\"cpuNumber\": 2, \"memory\": 1024}}")); + } + + @Test + public void encodesAListOfObjectsAsIndexedMapEntries() { + Assert.assertEquals(Map.of("rules[0].rule", "list*", "rules[0].permission", "allow", "rules[1].rule", "*", "rules[1].permission", "deny"), + encode("{\"rules\": [{\"rule\": \"list*\", \"permission\": \"allow\"}, {\"rule\": \"*\", \"permission\": \"deny\"}]}")); + } + + @Test(expected = IllegalArgumentException.class) + public void rejectsObjectsNestedInsideAMap() { + encode("{\"details\": {\"a\": {\"b\": 1}}}"); + } + + @Test(expected = IllegalArgumentException.class) + public void rejectsListsNestedInsideAList() { + encode("{\"ids\": [[\"a\"]]}"); + } + + @Test(expected = IllegalArgumentException.class) + public void rejectsListsMixingObjectsAndPlainValues() { + encode("{\"rules\": [{\"rule\": \"*\"}, \"allow\"]}"); + } + + @Test + public void rejectsReservedParametersInAnyCase() { + for (String reserved : new String[] {"command", "response", "apikey", "signature", "signatureversion", "expires", "sessionkey", "httpmethod", "ApiKey"}) { + Assert.assertThrows(reserved, IllegalArgumentException.class, () -> encode("{\"" + reserved + "\": \"x\"}")); + } + } +} diff --git a/server/src/test/java/com/cloud/api/McpServletTest.java b/server/src/test/java/com/cloud/api/McpServletTest.java new file mode 100644 index 000000000000..10547f60acc6 --- /dev/null +++ b/server/src/test/java/com/cloud/api/McpServletTest.java @@ -0,0 +1,516 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api; + +import java.io.BufferedReader; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.ApiServerService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesCmd; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.mcp.McpToken; +import org.apache.cloudstack.mcp.McpTokenService; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.projects.Project; +import com.cloud.projects.ProjectVO; +import com.cloud.projects.dao.ProjectDao; +import com.cloud.server.ManagementService; +import com.cloud.user.Account; +import com.cloud.user.AccountService; +import com.cloud.user.User; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class McpServletTest { + private static final String TOKEN = "csmcp_token"; + private static final long USER_ID = 42L; + private static final long ACCOUNT_ID = 7L; + + @Mock + private ApiServerService apiServer; + @Mock + private AccountService accountService; + @Mock + private McpTokenService mcpTokenService; + @Mock + private ManagementService managementService; + @Mock + private ProjectDao projectDao; + @Mock + private HttpServletRequest request; + @Mock + private HttpServletResponse response; + @Mock + private McpToken token; + @Mock + private User user; + @Mock + private Account account; + + private McpServlet servlet; + private StringWriter responseWriter; + private final List> executedRequests = new ArrayList<>(); + + @Before + public void setUp() throws Exception { + servlet = Mockito.spy(new McpServlet()); + servlet.apiServer = apiServer; + servlet.accountService = accountService; + servlet.mcpTokenService = mcpTokenService; + servlet.managementService = managementService; + servlet.projectDao = projectDao; + servlet.jobPollIntervalInMillis = 1; + Mockito.doReturn(true).when(servlet).isEnabled(); + Mockito.doReturn(0).when(servlet).getAsyncJobWait(); + + responseWriter = new StringWriter(); + Mockito.when(response.getWriter()).thenReturn(new PrintWriter(responseWriter)); + Mockito.when(request.getMethod()).thenReturn("POST"); + Mockito.when(request.getProtocol()).thenReturn("HTTP/1.1"); + Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1"); + Mockito.when(request.getServerName()).thenReturn("cloudstack.cloud.test"); + Mockito.when(request.getHeader("Authorization")).thenReturn("Bearer " + TOKEN); + + Mockito.when(mcpTokenService.authenticate(TOKEN)).thenReturn(token); + Mockito.when(token.getUserId()).thenReturn(USER_ID); + Mockito.when(user.getId()).thenReturn(USER_ID); + Mockito.when(user.getAccountId()).thenReturn(ACCOUNT_ID); + Mockito.when(account.getId()).thenReturn(ACCOUNT_ID); + Mockito.when(apiServer.verifyUser(USER_ID)).thenReturn(true); + Mockito.when(accountService.getActiveUser(USER_ID)).thenReturn(user); + Mockito.when(accountService.getAccount(ACCOUNT_ID)).thenReturn(account); + Mockito.when(apiServer.verifyApiKeyAccessAllowed(user, account)).thenReturn(true); + Mockito.when(apiServer.verifyRequest(Mockito.anyMap(), Mockito.eq(USER_ID), Mockito.any(InetAddress.class))).thenReturn(true); + Mockito.when(managementService.getVersion()).thenReturn("24.0.0"); + } + + private void setBody(String body) throws Exception { + Mockito.when(request.getReader()).thenReturn(new BufferedReader(new StringReader(body))); + } + + private JsonObject post(String body) throws Exception { + setBody(body); + servlet.processRequest(request, response); + String written = responseWriter.toString(); + return written.isEmpty() ? null : JsonParser.parseString(written).getAsJsonObject(); + } + + private JsonObject callTool(String name, String arguments) throws Exception { + return post(String.format("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"%s\",\"arguments\":%s}}", name, arguments)) + .getAsJsonObject("result"); + } + + private String getText(JsonObject toolResult) { + return toolResult.getAsJsonArray("content").get(0).getAsJsonObject().get("text").getAsString(); + } + + /** + * Answers each executed API with the next of the given responses, repeating the last one. + */ + private void mockApiResponses(String... responses) { + Mockito.when(apiServer.handleRequest(Mockito.anyMap(), Mockito.eq("json"), Mockito.any(StringBuilder.class))).thenAnswer(invocation -> { + executedRequests.add(invocation.getArgument(0)); + return responses[Math.min(executedRequests.size(), responses.length) - 1]; + }); + } + + private String getParam(Map params, String name) { + return params.get(name) == null ? null : (String)params.get(name)[0]; + } + + private void verifyStatus(int status) { + Mockito.verify(response).setStatus(status); + } + + @Test + public void disabledServerAnswersNotFoundToAnyMethod() throws Exception { + Mockito.doReturn(false).when(servlet).isEnabled(); + + servlet.service(request, response); + + verifyStatus(HttpServletResponse.SC_NOT_FOUND); + Mockito.verifyNoInteractions(mcpTokenService); + } + + @Test + public void getIsNotAllowed() throws Exception { + Mockito.when(request.getMethod()).thenReturn("GET"); + + servlet.service(request, response); + + Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), Mockito.anyString()); + } + + @Test + public void requestWithoutTokenIsUnauthorized() throws Exception { + Mockito.when(request.getHeader("Authorization")).thenReturn(null); + + post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}"); + + verifyStatus(HttpServletResponse.SC_UNAUTHORIZED); + Mockito.verify(response).setHeader("WWW-Authenticate", "Bearer"); + Mockito.verify(mcpTokenService).authenticate(null); + } + + @Test + public void requestWithInvalidTokenIsUnauthorized() throws Exception { + Mockito.when(mcpTokenService.authenticate(TOKEN)).thenReturn(null); + + post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}"); + + verifyStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void requestOfDisabledUserIsUnauthorized() throws Exception { + Mockito.when(apiServer.verifyUser(USER_ID)).thenReturn(false); + + post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}"); + + verifyStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void requestOfUserWithoutApiKeyAccessIsUnauthorized() throws Exception { + Mockito.when(apiServer.verifyApiKeyAccessAllowed(user, account)).thenReturn(false); + + post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}"); + + verifyStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void requestFromAnotherOriginIsForbidden() throws Exception { + Mockito.when(request.getHeader("Origin")).thenReturn("https://evil.example.com"); + + post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}"); + + verifyStatus(HttpServletResponse.SC_FORBIDDEN); + Mockito.verifyNoInteractions(mcpTokenService); + } + + @Test + public void requestFromTheSameOriginIsAccepted() throws Exception { + Mockito.when(request.getHeader("Origin")).thenReturn("https://cloudstack.cloud.test"); + + post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}"); + + verifyStatus(HttpServletResponse.SC_OK); + } + + @Test + public void callContextIsAlwaysUnregistered() throws Exception { + post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}"); + + Assert.assertNull(CallContext.unregister()); + } + + @Test + public void initializeAnswersWithTheRequestedProtocolVersionWhenSupported() throws Exception { + JsonObject result = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}," + + "\"clientInfo\":{\"name\":\"test\",\"version\":\"1\"}}}").getAsJsonObject("result"); + + Assert.assertEquals("2025-06-18", result.get("protocolVersion").getAsString()); + Assert.assertTrue(result.getAsJsonObject("capabilities").has("tools")); + Assert.assertEquals("24.0.0", result.getAsJsonObject("serverInfo").get("version").getAsString()); + verifyStatus(HttpServletResponse.SC_OK); + Mockito.verify(response).setContentType("application/json"); + } + + @Test + public void initializeAnswersWithTheNewestSupportedVersionWhenTheRequestedIsNot() throws Exception { + JsonObject result = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"1999-01-01\"}}").getAsJsonObject("result"); + + Assert.assertEquals(McpServlet.SUPPORTED_PROTOCOL_VERSIONS.get(0), result.get("protocolVersion").getAsString()); + } + + @Test + public void pingAnswersWithAnEmptyResult() throws Exception { + JsonObject answer = post("{\"jsonrpc\":\"2.0\",\"id\":\"abc\",\"method\":\"ping\"}"); + + Assert.assertEquals("abc", answer.get("id").getAsString()); + Assert.assertEquals(0, answer.getAsJsonObject("result").size()); + } + + @Test + public void toolsListReturnsTheFourTools() throws Exception { + JsonObject result = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}").getAsJsonObject("result"); + + List names = new ArrayList<>(); + result.getAsJsonArray("tools").forEach(tool -> { + names.add(tool.getAsJsonObject().get("name").getAsString()); + Assert.assertEquals("object", tool.getAsJsonObject().getAsJsonObject("inputSchema").get("type").getAsString()); + }); + Assert.assertEquals(List.of(McpServlet.TOOL_SEARCH_APIS, McpServlet.TOOL_DESCRIBE_API, McpServlet.TOOL_EXECUTE_API, McpServlet.TOOL_QUERY_ASYNC_JOB), names); + } + + @Test + public void notificationIsAcceptedWithoutBody() throws Exception { + Assert.assertNull(post("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}")); + + verifyStatus(HttpServletResponse.SC_ACCEPTED); + } + + @Test + public void invalidJsonIsAParseError() throws Exception { + JsonObject answer = post("{not json"); + + Assert.assertEquals(McpServlet.PARSE_ERROR, answer.getAsJsonObject("error").get("code").getAsInt()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + @Test + public void batchIsAnInvalidRequest() throws Exception { + JsonObject answer = post("[{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}]"); + + Assert.assertEquals(McpServlet.INVALID_REQUEST, answer.getAsJsonObject("error").get("code").getAsInt()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + @Test + public void unknownMethodIsNotFound() throws Exception { + JsonObject answer = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"resources/list\"}"); + + Assert.assertEquals(McpServlet.METHOD_NOT_FOUND, answer.getAsJsonObject("error").get("code").getAsInt()); + } + + @Test + public void unknownToolIsAnInvalidParamsError() throws Exception { + JsonObject answer = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"unknown\",\"arguments\":{}}}"); + + Assert.assertEquals(McpServlet.INVALID_PARAMS, answer.getAsJsonObject("error").get("code").getAsInt()); + } + + @Test + public void unsupportedProtocolVersionInHeaderIsRejectedListingTheSupportedOnes() throws Exception { + Mockito.when(request.getHeader("MCP-Protocol-Version")).thenReturn("1999-01-01"); + + JsonObject error = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}").getAsJsonObject("error"); + + Assert.assertEquals(McpServlet.UNSUPPORTED_PROTOCOL_VERSION, error.get("code").getAsInt()); + Assert.assertEquals(McpServlet.SUPPORTED_PROTOCOL_VERSIONS.size(), error.getAsJsonObject("data").getAsJsonArray("supported").size()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + @Test + public void unsupportedProtocolVersionInRequestMetadataIsRejected() throws Exception { + JsonObject error = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{\"_meta\":" + + "{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"}}}").getAsJsonObject("error"); + + Assert.assertEquals(McpServlet.UNSUPPORTED_PROTOCOL_VERSION, error.get("code").getAsInt()); + Assert.assertEquals("2026-07-28", error.getAsJsonObject("data").get("requested").getAsString()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + @Test + public void executeApiVerifiesAndExecutesTheCommandWithTheEncodedParameters() throws Exception { + Mockito.doReturn(ListZonesCmd.class).when(apiServer).getCmdClass("listZones"); + mockApiResponses("{\"listzonesresponse\":{\"count\":1,\"zone\":[{\"name\":\"z1\"}]}}"); + + JsonObject result = callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"listZones\",\"params\":{\"available\":true,\"ids\":[\"a\",\"b\"]}}"); + + Assert.assertFalse(result.get("isError").getAsBoolean()); + Assert.assertTrue(getText(result).contains("\"z1\"")); + + ArgumentCaptor> verified = ArgumentCaptor.forClass(Map.class); + Mockito.verify(apiServer).verifyRequest(verified.capture(), Mockito.eq(USER_ID), Mockito.any(InetAddress.class)); + Assert.assertEquals("listZones", getParam(verified.getValue(), "command")); + + Assert.assertEquals(1, executedRequests.size()); + Map executed = executedRequests.get(0); + Assert.assertEquals("listZones", getParam(executed, "command")); + Assert.assertEquals("true", getParam(executed, "available")); + Assert.assertEquals("a,b", getParam(executed, "ids")); + Assert.assertEquals("POST", getParam(executed, "httpmethod")); + } + + @Test + public void executeApiSetsTheProjectOfTheRequestInTheCallContext() throws Exception { + ProjectVO project = Mockito.mock(ProjectVO.class); + Mockito.when(projectDao.findByUuid("project-uuid")).thenReturn(project); + List projectsDuringVerification = new ArrayList<>(); + Mockito.when(apiServer.verifyRequest(Mockito.anyMap(), Mockito.eq(USER_ID), Mockito.any(InetAddress.class))).thenAnswer(invocation -> { + projectsDuringVerification.add(CallContext.current().getProject()); + return true; + }); + mockApiResponses("{\"listvirtualmachinesresponse\":{}}"); + + callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"listVirtualMachines\",\"params\":{\"projectid\":\"project-uuid\"}}"); + + Assert.assertEquals(List.of(project), projectsDuringVerification); + } + + @Test + public void executeApiReportsApiErrorsInTheToolResult() throws Exception { + Mockito.when(apiServer.handleRequest(Mockito.anyMap(), Mockito.eq("json"), Mockito.any(StringBuilder.class))) + .thenThrow(new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to find zone")); + + JsonObject answer = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"" + McpServlet.TOOL_EXECUTE_API + + "\",\"arguments\":{\"command\":\"listZones\"}}}"); + + Assert.assertFalse(answer.has("error")); + JsonObject result = answer.getAsJsonObject("result"); + Assert.assertTrue(result.get("isError").getAsBoolean()); + Assert.assertTrue(getText(result).contains("Unable to find zone")); + verifyStatus(HttpServletResponse.SC_OK); + } + + @Test + public void executeApiReportsDeniedCommandsInTheToolResultWithoutExecutingThem() throws Exception { + Mockito.when(apiServer.verifyRequest(Mockito.anyMap(), Mockito.eq(USER_ID), Mockito.any(InetAddress.class))) + .thenThrow(new ServerApiException(ApiErrorCode.UNAUTHORIZED, "not available for user")); + + JsonObject result = callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"listHosts\"}"); + + Assert.assertTrue(result.get("isError").getAsBoolean()); + Mockito.verify(apiServer, Mockito.never()).handleRequest(Mockito.anyMap(), Mockito.anyString(), Mockito.any(StringBuilder.class)); + } + + @Test + public void executeApiReportsRequestsFromDisallowedAddressesInTheToolResult() throws Exception { + Mockito.when(apiServer.verifyRequest(Mockito.anyMap(), Mockito.eq(USER_ID), Mockito.any(InetAddress.class))).thenReturn(false); + + JsonObject result = callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"listZones\"}"); + + Assert.assertTrue(result.get("isError").getAsBoolean()); + Mockito.verify(apiServer, Mockito.never()).handleRequest(Mockito.anyMap(), Mockito.anyString(), Mockito.any(StringBuilder.class)); + } + + @Test + public void executeApiReportsInvalidArgumentsInTheToolResult() throws Exception { + Assert.assertTrue(callTool(McpServlet.TOOL_EXECUTE_API, "{}").get("isError").getAsBoolean()); + + responseWriter.getBuffer().setLength(0); + Assert.assertTrue(callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"listZones\",\"params\":{\"apikey\":\"x\"}}").get("isError").getAsBoolean()); + + Mockito.verify(apiServer, Mockito.never()).handleRequest(Mockito.anyMap(), Mockito.anyString(), Mockito.any(StringBuilder.class)); + } + + @Test + public void executeApiReportsCommandsNotHandledByTheApiServerInTheToolResult() throws Exception { + mockApiResponses((String)null); + + Assert.assertTrue(callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"login\"}").get("isError").getAsBoolean()); + } + + @Test + public void executeApiWaitsForTheJobOfAnAsynchronousCommand() throws Exception { + Mockito.doReturn(5).when(servlet).getAsyncJobWait(); + Mockito.doReturn(DeployVMCmd.class).when(apiServer).getCmdClass("deployVirtualMachine"); + mockApiResponses("{\"deployvirtualmachineresponse\":{\"id\":\"vm-uuid\",\"jobid\":\"job-uuid\"}}", + "{\"queryasyncjobresultresponse\":{\"jobid\":\"job-uuid\",\"jobstatus\":0}}", + "{\"queryasyncjobresultresponse\":{\"jobid\":\"job-uuid\",\"jobstatus\":1,\"jobresult\":{\"virtualmachine\":{\"name\":\"vm-1\"}}}}"); + + JsonObject result = callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"deployVirtualMachine\",\"params\":{\"details\":{\"cpuNumber\":2}}}"); + + Assert.assertFalse(result.get("isError").getAsBoolean()); + Assert.assertTrue(getText(result).contains("vm-1")); + Assert.assertEquals(1, result.getAsJsonArray("content").size()); + + Assert.assertEquals(3, executedRequests.size()); + Assert.assertEquals("2", getParam(executedRequests.get(0), "details[0].cpuNumber")); + Assert.assertEquals("queryAsyncJobResult", getParam(executedRequests.get(1), "command")); + Assert.assertEquals("job-uuid", getParam(executedRequests.get(1), "jobid")); + // Only the command itself goes through the access checks and the rate limit, not the polling + Mockito.verify(apiServer, Mockito.times(1)).verifyRequest(Mockito.anyMap(), Mockito.eq(USER_ID), Mockito.any(InetAddress.class)); + } + + @Test + public void executeApiReturnsThePendingJobWhenItDoesNotFinishInTime() throws Exception { + Mockito.doReturn(DeployVMCmd.class).when(apiServer).getCmdClass("deployVirtualMachine"); + mockApiResponses("{\"deployvirtualmachineresponse\":{\"id\":\"vm-uuid\",\"jobid\":\"job-uuid\"}}", + "{\"queryasyncjobresultresponse\":{\"jobid\":\"job-uuid\",\"jobstatus\":0}}"); + + JsonObject result = callTool(McpServlet.TOOL_EXECUTE_API, "{\"command\":\"deployVirtualMachine\"}"); + + Assert.assertFalse(result.get("isError").getAsBoolean()); + Assert.assertTrue(getText(result).contains("job-uuid")); + Assert.assertEquals(2, result.getAsJsonArray("content").size()); + Assert.assertEquals(2, executedRequests.size()); + } + + @Test + public void queryAsyncJobReportsAFailedJobAsError() throws Exception { + mockApiResponses("{\"queryasyncjobresultresponse\":{\"jobid\":\"job-uuid\",\"jobstatus\":2,\"jobresult\":{\"errortext\":\"No capacity\"}}}"); + + JsonObject result = callTool(McpServlet.TOOL_QUERY_ASYNC_JOB, "{\"jobid\":\"job-uuid\"}"); + + Assert.assertTrue(result.get("isError").getAsBoolean()); + Assert.assertTrue(getText(result).contains("No capacity")); + Mockito.verify(apiServer).verifyRequest(Mockito.anyMap(), Mockito.eq(USER_ID), Mockito.any(InetAddress.class)); + } + + @Test + public void searchApisReturnsTheApisMatchingAllTheWords() throws Exception { + mockApiResponses("{\"listapisresponse\":{\"count\":3,\"api\":[" + + "{\"name\":\"listVirtualMachines\",\"description\":\"List the virtual machines owned by the account.\",\"isasync\":false}," + + "{\"name\":\"deployVirtualMachine\",\"description\":\"Creates and automatically starts a virtual machine.\",\"isasync\":true}," + + "{\"name\":\"listZones\",\"description\":\"Lists zones\",\"isasync\":false}]}}"); + + JsonObject result = callTool(McpServlet.TOOL_SEARCH_APIS, "{\"keyword\":\"Virtual DEPLOY\"}"); + + String text = getText(result); + Assert.assertTrue(text.contains("deployVirtualMachine [async]: Creates")); + Assert.assertFalse(text.contains("listVirtualMachines")); + Assert.assertFalse(text.contains("listZones")); + Assert.assertEquals("listApis", getParam(executedRequests.get(0), "command")); + } + + @Test + public void describeApiReturnsTheParametersWithoutTheResponseDescription() throws Exception { + mockApiResponses("{\"listapisresponse\":{\"count\":1,\"api\":[{\"name\":\"listZones\",\"description\":\"Lists zones\",\"isasync\":false," + + "\"params\":[{\"name\":\"id\",\"type\":\"uuid\",\"required\":false,\"description\":\"the ID of the zone\",\"since\":\"4.0\"}]," + + "\"response\":[{\"name\":\"name\",\"description\":\"Zone name\",\"type\":\"string\"}]}]}}"); + + JsonObject description = JsonParser.parseString(getText(callTool(McpServlet.TOOL_DESCRIBE_API, "{\"name\":\"listZones\"}"))).getAsJsonObject(); + + Assert.assertEquals("listZones", description.get("name").getAsString()); + Assert.assertFalse(description.has("response")); + JsonObject param = description.getAsJsonArray("params").get(0).getAsJsonObject(); + Assert.assertEquals("uuid", param.get("type").getAsString()); + Assert.assertFalse(param.has("since")); + Assert.assertEquals("listZones", getParam(executedRequests.get(0), "name")); + } + + @Test + public void describeApiOfAnUnknownApiIsReportedInTheToolResult() throws Exception { + mockApiResponses("{\"listapisresponse\":{}}"); + + Assert.assertTrue(callTool(McpServlet.TOOL_DESCRIBE_API, "{\"name\":\"doesNotExist\"}").get("isError").getAsBoolean()); + } +} From 536dedbe14daaaa5f8399d455fa40e5711e6fea0 Mon Sep 17 00:00:00 2001 From: Francisco Ewerton de Araujo Silva Date: Sun, 22 Nov 2026 14:05:03 -0300 Subject: [PATCH 3/5] feat(ui): manage MCP tokens in the user view Add an MCP Tokens tab to the user view to list and revoke the tokens of the user and, for the logged in user, to create one. The token is shown only once, right after it is created. --- ui/public/locales/en.json | 7 + ui/public/locales/pt_BR.json | 7 + ui/src/components/view/McpTokensTab.vue | 191 ++++++++++++++++++++++++ ui/src/config/section/user.js | 6 + ui/src/views/iam/GenerateMcpToken.vue | 153 +++++++++++++++++++ 5 files changed, 364 insertions(+) create mode 100644 ui/src/components/view/McpTokensTab.vue create mode 100644 ui/src/views/iam/GenerateMcpToken.vue diff --git a/ui/public/locales/en.json b/ui/public/locales/en.json index a3d3a2285ac4..aabe15bffa40 100644 --- a/ui/public/locales/en.json +++ b/ui/public/locales/en.json @@ -1,4 +1,8 @@ { +"label.action.create.mcp.token": "Create MCP token", +"label.action.revoke.mcp.token": "Revoke MCP token", +"label.mcptokens": "MCP Tokens", +"message.confirm.revoke.mcp.token": "Please confirm that you want to revoke this MCP token. Clients using it will lose access.", "message.delete.account.not.disabled": "Please disable the account before attempting to delete it.", "alert.service.domainrouter": "Domain Router", "error.dedicate.bgp.peer.failed":"Failed to dedicate BGP peer", @@ -1784,6 +1788,8 @@ "label.migrate.systemvm.to": "Migrate System VM to", "label.migrate.volume": "Migrate Volume", "label.migrate.volume.to.kms": "Migrate Volume Encryption to KMS", +"message.mcp.token.created.body": "Copy the token now and keep it in a safe place. For security reasons it is not stored and cannot be shown again.", +"message.mcp.token.created.title": "MCP token created", "message.memory.usage.info.hypervisor.additionals": "The data shown may not reflect the actual memory usage if the Instance does not have the additional hypervisor tools installed", "message.memory.usage.info.negative.value": "If the Instance's memory usage cannot be obtained from the hypervisor, the lines for free memory in the raw data graph and memory usage in the percentage graph will be disabled", "message.migrate.volume.tooltip": "Volume can be migrated to any suitable storage pool. Admin has to choose the appropriate disk offering to replace, that supports the new storage pool", @@ -3199,6 +3205,7 @@ "message.create.instance.from.backup.different.zone": "Creating Instance from Backup on a different Zone. Please ensure that the backup repository is accessible in the selected Zone.", "message.csv.empty": "Empty CSV File", "message.csv.missing.headers": "Columns are missing from headers in CSV", +"message.success.revoke.mcp.token": "Successfully revoked the MCP token", "message.template.ostype.different.from.backup": "Selected Template has a different OS type than the Backup. Please proceed with caution.", "message.iso.ostype.different.from.backup": "Selected ISO has a different OS type than the Backup. Please proceed with caution.", "message.action.delete.asnrange": "Please confirm the AS range that you want to delete", diff --git a/ui/public/locales/pt_BR.json b/ui/public/locales/pt_BR.json index 09259496da5d..f28b10e6a6e0 100644 --- a/ui/public/locales/pt_BR.json +++ b/ui/public/locales/pt_BR.json @@ -68,6 +68,7 @@ "label.action.change.password": "Trocar de senha", "label.action.change.primary.storage.scope": "Alterar escopo do armazenamento prim\u00e1rio", "label.action.clear.webhook.deliveries": "Limpar entregas do webhook", +"label.action.create.mcp.token": "Criar token MCP", "label.action.delete.webhook.deliveries": "Excluir entregas do webhook", "label.action.configure.stickiness": "Ader\u00eancia", "label.action.copy.iso": "Copiar ISO", @@ -97,6 +98,8 @@ "label.action.delete.network.static.route": "Remover rota est\u00e1tica de Rede Tungsten Fabric", "label.action.delete.node": "Remover nodo", "label.action.delete.oauth.provider": "Excluir provedor OAuth", +"label.action.revoke.mcp.token": "Revogar token MCP", +"label.mcptokens": "Tokens MCP", "message.action.delete.object.storage": "Por favor, confirme que voc\u00ea deseja excluir este Object Storage", "label.action.delete.physical.network": "Remover rede f\u00edsica", "label.action.delete.pod": "Remover pod", @@ -2844,6 +2847,9 @@ "message.add.ip.v6.firewall.rule.failed": "Falha ao adicionar regra de firewall IPv6", "message.add.ip.v6.firewall.rule.processing": "Adicionando regra de firewall IPv6...", "message.add.ip.v6.firewall.rule.success": "Regra de firewall IPv6 adicionada", +"message.confirm.revoke.mcp.token": "Por favor, confirme que voc\u00ea deseja revogar este token MCP. Os clientes que o utilizam perder\u00e3o o acesso.", +"message.mcp.token.created.body": "Copie o token agora e guarde-o em um local seguro. Por seguran\u00e7a ele n\u00e3o \u00e9 armazenado e n\u00e3o poder\u00e1 ser exibido novamente.", +"message.mcp.token.created.title": "Token MCP criado", "message.redeliver.webhook.delivery": "Reentregar esta entrega de Webhook", "message.remove.ip.v6.firewall.rule.failed": "Falha ao remover regra de firewall IPv6", "message.remove.ip.v6.firewall.rule.processing": "Removendo regra de firewall IPv6...", @@ -3666,6 +3672,7 @@ "message.success.remove.tungsten.routing.policy": "Pol\u00edtica de Roteamento Tungsten-Fabric removida da Rede com sucesso", "message.success.reset.network.permissions": "Permiss\u00f5es de Rede redefinidas com sucesso", "message.success.resize.volume": "Volume redimensionado com sucesso", +"message.success.revoke.mcp.token": "Token MCP revogado com sucesso", "message.success.scale.kubernetes": "Cluster Kubernetes escalonado com sucesso", "message.success.unmanage.instance": "Inst\u00e2ncia n\u00e3o gerenciada com sucesso", "message.success.unmanage.volume": "Volume n\u00e3o gerenciado com sucesso", diff --git a/ui/src/components/view/McpTokensTab.vue b/ui/src/components/view/McpTokensTab.vue new file mode 100644 index 000000000000..e5fbd7b64730 --- /dev/null +++ b/ui/src/components/view/McpTokensTab.vue @@ -0,0 +1,191 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + + + + diff --git a/ui/src/config/section/user.js b/ui/src/config/section/user.js index 9fb2ac8a25ca..7d5af25f5221 100644 --- a/ui/src/config/section/user.js +++ b/ui/src/config/section/user.js @@ -70,6 +70,12 @@ export default { resourceType: 'User', component: shallowRef(defineAsyncComponent(() => import('@/components/view/ApiKeyPairsTab.vue'))), show: () => { return 'listUserKeys' in store.getters.apis } + }, + { + name: 'mcptokens', + resourceType: 'User', + component: shallowRef(defineAsyncComponent(() => import('@/components/view/McpTokensTab.vue'))), + show: () => { return 'listMcpTokens' in store.getters.apis } } ], actions: [ diff --git a/ui/src/views/iam/GenerateMcpToken.vue b/ui/src/views/iam/GenerateMcpToken.vue new file mode 100644 index 000000000000..421318a143ce --- /dev/null +++ b/ui/src/views/iam/GenerateMcpToken.vue @@ -0,0 +1,153 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + + + + From 4d8f1454d4258bbe4cea309ae505f96cbf96be92 Mon Sep 17 00:00:00 2001 From: Francisco Ewerton de Araujo Silva Date: Sun, 22 Nov 2026 17:15:50 -0300 Subject: [PATCH 4/5] feat(mcp): support the protocol revision without handshake Accept the 2026-07-28 revision, which drops the initialize handshake: answer server/discover, validate the MCP-Protocol-Version, Mcp-Method and Mcp-Name headers against the request body, and return resultType and cache hints. The 2025-11-25 and 2025-06-18 revisions keep working through initialize. --- .../main/java/com/cloud/api/McpServlet.java | 145 ++++++++++++++---- .../java/com/cloud/api/McpServletTest.java | 120 ++++++++++++++- 2 files changed, 235 insertions(+), 30 deletions(-) diff --git a/server/src/main/java/com/cloud/api/McpServlet.java b/server/src/main/java/com/cloud/api/McpServlet.java index 281a049cd980..58ef767d58dd 100644 --- a/server/src/main/java/com/cloud/api/McpServlet.java +++ b/server/src/main/java/com/cloud/api/McpServlet.java @@ -20,8 +20,10 @@ import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -62,7 +64,8 @@ /** * MCP (Model Context Protocol) server of the management server, using the Streamable HTTP transport without streaming and without sessions: - * each POST carries one JSON-RPC message and is answered with one JSON body. Requests are authenticated with an MCP token + * each POST carries one JSON-RPC message and is answered with one JSON body. Both the protocol revisions that start with the initialize + * handshake and the revision without handshake are served, the latter being recognized by the protocol version in the request metadata. Requests are authenticated with an MCP token * (see {@link McpTokenService}) and every API is executed through {@link ApiServerService}, as the calling user. *

* Instead of one tool per API, the server exposes a few tools to search, describe and execute any API the user has access to. @@ -72,16 +75,26 @@ public class McpServlet extends HttpServlet { private static final Logger ACCESSLOGGER = LogManager.getLogger("apiserver." + McpServlet.class.getName()); // Protocol revisions based on the initialize handshake, newest first - static final List SUPPORTED_PROTOCOL_VERSIONS = List.of("2025-11-25", "2025-06-18"); + static final List HANDSHAKE_PROTOCOL_VERSIONS = List.of("2025-11-25", "2025-06-18"); + // Protocol revision without handshake: each request informs the version, in the metadata of its parameters, and is served on its own + static final String STATELESS_PROTOCOL_VERSION = "2026-07-28"; + static final List SUPPORTED_PROTOCOL_VERSIONS = List.of(STATELESS_PROTOCOL_VERSION, "2025-11-25", "2025-06-18"); + private static final String PROTOCOL_VERSION_HEADER = "MCP-Protocol-Version"; - // Revisions without handshake inform the version on each request, in the metadata of its parameters + private static final String METHOD_HEADER = "Mcp-Method"; + private static final String NAME_HEADER = "Mcp-Name"; private static final String PROTOCOL_VERSION_META = "io.modelcontextprotocol/protocolVersion"; + private static final String CLIENT_CAPABILITIES_META = "io.modelcontextprotocol/clientCapabilities"; + private static final String SERVER_INFO_META = "io.modelcontextprotocol/serverInfo"; + // The tools and the server description only change when the management server is upgraded + private static final long CACHE_TTL_IN_MILLIS = 3600000; static final int PARSE_ERROR = -32700; static final int INVALID_REQUEST = -32600; static final int METHOD_NOT_FOUND = -32601; static final int INVALID_PARAMS = -32602; static final int INTERNAL_ERROR = -32603; + static final int HEADER_MISMATCH = -32020; static final int UNSUPPORTED_PROTOCOL_VERSION = -32022; static final String TOOL_SEARCH_APIS = "cloudstack_search_apis"; @@ -218,8 +231,11 @@ private void processMessage(HttpServletRequest req, HttpServletResponse resp, lo } JsonObject params = message.get("params") instanceof JsonObject ? message.getAsJsonObject("params") : new JsonObject(); - String protocolVersion = getRequestProtocolVersion(req, params); - if (protocolVersion != null && !SUPPORTED_PROTOCOL_VERSIONS.contains(protocolVersion)) { + JsonObject meta = params.get("_meta") instanceof JsonObject ? params.getAsJsonObject("_meta") : new JsonObject(); + String metaProtocolVersion = getString(meta, PROTOCOL_VERSION_META); + boolean isStateless = metaProtocolVersion != null; + String protocolVersion = isStateless ? metaProtocolVersion : req.getHeader(PROTOCOL_VERSION_HEADER); + if (isStateless ? !STATELESS_PROTOCOL_VERSION.equals(protocolVersion) : protocolVersion != null && !SUPPORTED_PROTOCOL_VERSIONS.contains(protocolVersion)) { JsonObject data = new JsonObject(); JsonArray supported = new JsonArray(); SUPPORTED_PROTOCOL_VERSIONS.forEach(supported::add); @@ -234,28 +250,28 @@ private void processMessage(HttpServletRequest req, HttpServletResponse resp, lo return; } + int status = HttpServletResponse.SC_OK; JsonObject response; try { - response = createResult(id, processMethod(method, params, userId, remoteAddress)); + if (isStateless) { + validateStatelessRequest(req, method, params, meta); + response = createResult(id, processStatelessMethod(method, params, userId, remoteAddress)); + } else { + response = createResult(id, processMethod(method, params, userId, remoteAddress)); + } } catch (McpException e) { + status = e.status; response = createError(id, e.code, e.getMessage(), null); } catch (RuntimeException e) { LOGGER.error("Unexpected error while processing the MCP method [{}]", method, e); response = createError(id, INTERNAL_ERROR, "Internal error", null); } - writeResponse(resp, HttpServletResponse.SC_OK, response); - } - - private String getRequestProtocolVersion(HttpServletRequest req, JsonObject params) { - if (params.get("_meta") instanceof JsonObject) { - String version = getString(params.getAsJsonObject("_meta"), PROTOCOL_VERSION_META); - if (version != null) { - return version; - } - } - return req.getHeader(PROTOCOL_VERSION_HEADER); + writeResponse(resp, status, response); } + /** + * Methods of the protocol revisions based on the initialize handshake. + */ private JsonObject processMethod(String method, JsonObject params, long userId, InetAddress remoteAddress) throws McpException { switch (method) { case "initialize": @@ -269,26 +285,99 @@ private JsonObject processMethod(String method, JsonObject params, long userId, case "tools/call": return callTool(params, userId, remoteAddress); default: - throw new McpException(METHOD_NOT_FOUND, "Method not found: " + method); + throw new McpException(HttpServletResponse.SC_OK, METHOD_NOT_FOUND, "Method not found: " + method); } } private JsonObject initialize(JsonObject params) { String requestedVersion = getString(params, "protocolVersion"); + JsonObject result = new JsonObject(); + result.addProperty("protocolVersion", HANDSHAKE_PROTOCOL_VERSIONS.contains(requestedVersion) ? requestedVersion : HANDSHAKE_PROTOCOL_VERSIONS.get(0)); + result.add("capabilities", createCapabilities()); + result.add("serverInfo", createServerInfo()); + result.addProperty("instructions", INSTRUCTIONS); + return result; + } + + /** + * In the protocol revision without handshake, the routing headers of the request must be present and match its body. + */ + private void validateStatelessRequest(HttpServletRequest req, String method, JsonObject params, JsonObject meta) throws McpException { + validateHeader(req, PROTOCOL_VERSION_HEADER, STATELESS_PROTOCOL_VERSION); + validateHeader(req, METHOD_HEADER, method); + if ("tools/call".equals(method)) { + validateHeader(req, NAME_HEADER, getString(params, "name")); + } + if (!(meta.get(CLIENT_CAPABILITIES_META) instanceof JsonObject)) { + throw new McpException(HttpServletResponse.SC_BAD_REQUEST, INVALID_PARAMS, "Missing required metadata: " + CLIENT_CAPABILITIES_META); + } + } + + private void validateHeader(HttpServletRequest req, String header, String bodyValue) throws McpException { + String value = req.getHeader(header); + // Values that are not plain ASCII are sent encoded in Base64 + if (value != null && value.startsWith("=?base64?") && value.endsWith("?=")) { + value = new String(Base64.getDecoder().decode(value.substring("=?base64?".length(), value.length() - "?=".length())), StandardCharsets.UTF_8); + } + if (value == null || !value.equals(bodyValue)) { + throw new McpException(HttpServletResponse.SC_BAD_REQUEST, HEADER_MISMATCH, + String.format("Header mismatch: %s header value '%s' does not match body value '%s'", header, value, bodyValue)); + } + } + + /** + * Methods of the protocol revision without handshake. + */ + private JsonObject processStatelessMethod(String method, JsonObject params, long userId, InetAddress remoteAddress) throws McpException { + JsonObject result; + switch (method) { + case "server/discover": + JsonArray supportedVersions = new JsonArray(); + SUPPORTED_PROTOCOL_VERSIONS.forEach(supportedVersions::add); + result = new JsonObject(); + result.add("supportedVersions", supportedVersions); + result.add("capabilities", createCapabilities()); + result.addProperty("instructions", INSTRUCTIONS); + addCacheHints(result); + break; + case "tools/list": + result = new JsonObject(); + result.add("tools", createTools()); + addCacheHints(result); + break; + case "tools/call": + result = callTool(params, userId, remoteAddress); + break; + default: + throw new McpException(HttpServletResponse.SC_NOT_FOUND, METHOD_NOT_FOUND, "Method not found: " + method); + } + + JsonObject meta = new JsonObject(); + meta.add(SERVER_INFO_META, createServerInfo()); + result.add("_meta", meta); + result.addProperty("resultType", "complete"); + return result; + } + + private void addCacheHints(JsonObject result) { + result.addProperty("ttlMs", CACHE_TTL_IN_MILLIS); + // The same for every user + result.addProperty("cacheScope", "public"); + } + + private JsonObject createCapabilities() { JsonObject capabilities = new JsonObject(); capabilities.add("tools", new JsonObject()); + return capabilities; + } + + private JsonObject createServerInfo() { JsonObject serverInfo = new JsonObject(); serverInfo.addProperty("name", "cloudstack"); serverInfo.addProperty("title", "Apache CloudStack"); serverInfo.addProperty("version", managementService.getVersion()); - - JsonObject result = new JsonObject(); - result.addProperty("protocolVersion", SUPPORTED_PROTOCOL_VERSIONS.contains(requestedVersion) ? requestedVersion : SUPPORTED_PROTOCOL_VERSIONS.get(0)); - result.add("capabilities", capabilities); - result.add("serverInfo", serverInfo); - result.addProperty("instructions", INSTRUCTIONS); - return result; + return serverInfo; } private JsonArray createTools() { @@ -372,7 +461,7 @@ private JsonObject callTool(JsonObject params, long userId, InetAddress remoteAd case TOOL_QUERY_ASYNC_JOB: return createJobResult(waitForJob(getRequiredArgument(arguments, "jobid"), userId, remoteAddress, true)); default: - throw new McpException(INVALID_PARAMS, "Unknown tool: " + name); + throw new McpException(HttpServletResponse.SC_OK, INVALID_PARAMS, "Unknown tool: " + name); } } catch (ServerApiException e) { JsonObject error = new JsonObject(); @@ -609,10 +698,12 @@ private void writeResponse(HttpServletResponse resp, int status, JsonObject resp } private static class McpException extends Exception { + private final int status; private final int code; - McpException(int code, String message) { + McpException(int status, int code, String message) { super(message); + this.status = status; this.code = code; } } diff --git a/server/src/test/java/com/cloud/api/McpServletTest.java b/server/src/test/java/com/cloud/api/McpServletTest.java index 10547f60acc6..387bf4df6f34 100644 --- a/server/src/test/java/com/cloud/api/McpServletTest.java +++ b/server/src/test/java/com/cloud/api/McpServletTest.java @@ -88,6 +88,8 @@ public class McpServletTest { @Before public void setUp() throws Exception { + // Other tests may leave a context registered in this thread + CallContext.unregister(); servlet = Mockito.spy(new McpServlet()); servlet.apiServer = apiServer; servlet.accountService = accountService; @@ -256,7 +258,7 @@ public void initializeAnswersWithTheRequestedProtocolVersionWhenSupported() thro public void initializeAnswersWithTheNewestSupportedVersionWhenTheRequestedIsNot() throws Exception { JsonObject result = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"1999-01-01\"}}").getAsJsonObject("result"); - Assert.assertEquals(McpServlet.SUPPORTED_PROTOCOL_VERSIONS.get(0), result.get("protocolVersion").getAsString()); + Assert.assertEquals(McpServlet.HANDSHAKE_PROTOCOL_VERSIONS.get(0), result.get("protocolVersion").getAsString()); } @Test @@ -330,10 +332,10 @@ public void unsupportedProtocolVersionInHeaderIsRejectedListingTheSupportedOnes( @Test public void unsupportedProtocolVersionInRequestMetadataIsRejected() throws Exception { JsonObject error = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{\"_meta\":" + - "{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"}}}").getAsJsonObject("error"); + "{\"io.modelcontextprotocol/protocolVersion\":\"2099-01-01\"}}}").getAsJsonObject("error"); Assert.assertEquals(McpServlet.UNSUPPORTED_PROTOCOL_VERSION, error.get("code").getAsInt()); - Assert.assertEquals("2026-07-28", error.getAsJsonObject("data").get("requested").getAsString()); + Assert.assertEquals("2099-01-01", error.getAsJsonObject("data").get("requested").getAsString()); verifyStatus(HttpServletResponse.SC_BAD_REQUEST); } @@ -513,4 +515,116 @@ public void describeApiOfAnUnknownApiIsReportedInTheToolResult() throws Exceptio Assert.assertTrue(callTool(McpServlet.TOOL_DESCRIBE_API, "{\"name\":\"doesNotExist\"}").get("isError").getAsBoolean()); } + + private static final String STATELESS_META = "\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"," + + "\"io.modelcontextprotocol/clientInfo\":{\"name\":\"test\",\"version\":\"1\"},\"io.modelcontextprotocol/clientCapabilities\":{}}"; + + /** + * Sends a request of the protocol revision without handshake, with the headers that match its body. + */ + private JsonObject postStateless(String method, String extraParams) throws Exception { + Mockito.when(request.getHeader("MCP-Protocol-Version")).thenReturn("2026-07-28"); + Mockito.when(request.getHeader("Mcp-Method")).thenReturn(method); + return post(String.format("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"%s\",\"params\":{%s%s}}", method, extraParams, STATELESS_META)); + } + + @Test + public void statelessDiscoverReturnsTheSupportedVersionsAndCapabilities() throws Exception { + JsonObject result = postStateless("server/discover", "").getAsJsonObject("result"); + + Assert.assertEquals("complete", result.get("resultType").getAsString()); + Assert.assertEquals(McpServlet.SUPPORTED_PROTOCOL_VERSIONS.size(), result.getAsJsonArray("supportedVersions").size()); + Assert.assertTrue(result.getAsJsonObject("capabilities").has("tools")); + Assert.assertTrue(result.has("instructions")); + Assert.assertTrue(result.get("ttlMs").getAsLong() > 0); + Assert.assertEquals("public", result.get("cacheScope").getAsString()); + Assert.assertEquals("24.0.0", result.getAsJsonObject("_meta").getAsJsonObject("io.modelcontextprotocol/serverInfo").get("version").getAsString()); + verifyStatus(HttpServletResponse.SC_OK); + } + + @Test + public void statelessToolsListReturnsTheToolsWithCacheHints() throws Exception { + JsonObject result = postStateless("tools/list", "").getAsJsonObject("result"); + + Assert.assertEquals(4, result.getAsJsonArray("tools").size()); + Assert.assertEquals("complete", result.get("resultType").getAsString()); + Assert.assertTrue(result.has("ttlMs")); + Assert.assertTrue(result.has("cacheScope")); + } + + @Test + public void statelessToolsCallExecutesTheTool() throws Exception { + Mockito.when(request.getHeader("Mcp-Name")).thenReturn(McpServlet.TOOL_EXECUTE_API); + mockApiResponses("{\"listzonesresponse\":{\"count\":0}}"); + + JsonObject result = postStateless("tools/call", "\"name\":\"" + McpServlet.TOOL_EXECUTE_API + "\",\"arguments\":{\"command\":\"listZones\"},") + .getAsJsonObject("result"); + + Assert.assertEquals("complete", result.get("resultType").getAsString()); + Assert.assertFalse(result.get("isError").getAsBoolean()); + Assert.assertEquals("listZones", getParam(executedRequests.get(0), "command")); + } + + @Test + public void statelessToolsCallAcceptsTheNameHeaderEncodedInBase64() throws Exception { + Mockito.when(request.getHeader("Mcp-Name")).thenReturn("=?base64?" + + java.util.Base64.getEncoder().encodeToString(McpServlet.TOOL_SEARCH_APIS.getBytes()) + "?="); + mockApiResponses("{\"listapisresponse\":{}}"); + + JsonObject answer = postStateless("tools/call", "\"name\":\"" + McpServlet.TOOL_SEARCH_APIS + "\",\"arguments\":{\"keyword\":\"zone\"},"); + + Assert.assertTrue(answer.has("result")); + } + + @Test + public void statelessRequestWithoutTheMethodHeaderIsAHeaderMismatch() throws Exception { + Mockito.when(request.getHeader("MCP-Protocol-Version")).thenReturn("2026-07-28"); + + JsonObject answer = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{" + STATELESS_META + "}}"); + + Assert.assertEquals(McpServlet.HEADER_MISMATCH, answer.getAsJsonObject("error").get("code").getAsInt()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + @Test + public void statelessRequestWithAnotherVersionInTheHeaderIsAHeaderMismatch() throws Exception { + Mockito.when(request.getHeader("MCP-Protocol-Version")).thenReturn("2025-11-25"); + Mockito.when(request.getHeader("Mcp-Method")).thenReturn("tools/list"); + + JsonObject answer = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{" + STATELESS_META + "}}"); + + Assert.assertEquals(McpServlet.HEADER_MISMATCH, answer.getAsJsonObject("error").get("code").getAsInt()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + @Test + public void statelessToolsCallWithAnotherToolInTheNameHeaderIsAHeaderMismatchAndIsNotExecuted() throws Exception { + Mockito.when(request.getHeader("Mcp-Name")).thenReturn(McpServlet.TOOL_SEARCH_APIS); + + JsonObject answer = postStateless("tools/call", "\"name\":\"" + McpServlet.TOOL_EXECUTE_API + "\",\"arguments\":{\"command\":\"listZones\"},"); + + Assert.assertEquals(McpServlet.HEADER_MISMATCH, answer.getAsJsonObject("error").get("code").getAsInt()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + Mockito.verify(apiServer, Mockito.never()).handleRequest(Mockito.anyMap(), Mockito.anyString(), Mockito.any(StringBuilder.class)); + } + + @Test + public void statelessRequestWithoutClientCapabilitiesIsInvalid() throws Exception { + Mockito.when(request.getHeader("MCP-Protocol-Version")).thenReturn("2026-07-28"); + Mockito.when(request.getHeader("Mcp-Method")).thenReturn("tools/list"); + + JsonObject answer = post("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{\"_meta\":" + + "{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"}}}"); + + Assert.assertEquals(McpServlet.INVALID_PARAMS, answer.getAsJsonObject("error").get("code").getAsInt()); + verifyStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + @Test + public void statelessUnknownMethodIsNotFound() throws Exception { + JsonObject answer = postStateless("resources/list", ""); + + Assert.assertEquals(McpServlet.METHOD_NOT_FOUND, answer.getAsJsonObject("error").get("code").getAsInt()); + verifyStatus(HttpServletResponse.SC_NOT_FOUND); + } } From 939e4c448e63e7b78f3fed623834ceae37081974 Mon Sep 17 00:00:00 2001 From: Francisco Ewerton de Araujo Silva Date: Sun, 22 Nov 2026 17:15:58 -0300 Subject: [PATCH 5/5] fix(mcp): remove the MCP tokens of a removed user Users are soft deleted, so the foreign key cascade never fires and the tokens stayed behind. Remove them when a user or its account is deleted, and when a user is moved to another account, since the token keeps the account and domain it was created in. --- .../java/org/apache/cloudstack/mcp/dao/McpTokenDao.java | 2 ++ .../org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java | 7 +++++++ .../src/main/java/com/cloud/user/AccountManagerImpl.java | 6 ++++++ .../test/java/com/cloud/user/AccountManagerImplTest.java | 5 +++++ 4 files changed, 20 insertions(+) diff --git a/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java index b3aed029ef77..fc573b9bd697 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDao.java @@ -27,4 +27,6 @@ public interface McpTokenDao extends GenericDao { McpTokenVO findByTokenHash(String tokenHash); Pair, Integer> listByUserId(long userId, Long startIndex, Long pageSize); + + int removeByUserId(long userId); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java index b9c5577c9a41..ae03dc9ee523 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/mcp/dao/McpTokenDaoImpl.java @@ -57,4 +57,11 @@ public Pair, Integer> listByUserId(long userId, Long startIndex sc.setParameters(USER_ID, userId); return searchAndCount(sc, new Filter(McpTokenVO.class, ID, true, startIndex, pageSize)); } + + @Override + public int removeByUserId(long userId) { + SearchCriteria sc = tokenSearch.create(); + sc.setParameters(USER_ID, userId); + return remove(sc); + } } diff --git a/server/src/main/java/com/cloud/user/AccountManagerImpl.java b/server/src/main/java/com/cloud/user/AccountManagerImpl.java index e72700b8f828..fba224da95d6 100644 --- a/server/src/main/java/com/cloud/user/AccountManagerImpl.java +++ b/server/src/main/java/com/cloud/user/AccountManagerImpl.java @@ -113,6 +113,7 @@ import org.apache.cloudstack.framework.messagebus.PublishScope; import org.apache.cloudstack.kms.KMSManager; import org.apache.cloudstack.managed.context.ManagedContextRunnable; +import org.apache.cloudstack.mcp.dao.McpTokenDao; import org.apache.cloudstack.query.QueryService; import org.apache.cloudstack.network.RoutedIpv4Manager; import org.apache.cloudstack.network.dao.NetworkPermissionDao; @@ -265,6 +266,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Inject private ApiKeyPairDao apiKeyPairDao; @Inject + private McpTokenDao mcpTokenDao; + @Inject private ApiKeyPairService apiKeyPairService; @Inject private ApiKeyPairPermissionsDao apiKeyPairPermissionsDao; @@ -982,6 +985,7 @@ protected boolean cleanupAccount(AccountVO account, long callerUserId, Account c List users = _userDao.listByAccount(accountId); for (UserVO user : users) { removeUserApiKeys(user.getId()); + mcpTokenDao.removeByUserId(user.getId()); if (!_userDao.remove(user.getId())) { logger.error("Unable to delete user: " + user + " as a part of account " + account + " cleanup"); accountCleanupNeeded = true; @@ -2597,6 +2601,7 @@ protected boolean deleteAndCleanupUser(User user) { long userId = user.getId(); removeUserApiKeys(userId); + mcpTokenDao.removeByUserId(userId); _projectMgr.cleanupProjectsForUser(null, user); return _userDao.remove(userId); @@ -2641,6 +2646,7 @@ private boolean moveUser(UserVO user, long newAccountId) throws ResourceAllocati newUser.setAccountId(newAccountId); UserVO persisted = _userDao.persist(newUser); _projectMgr.moveProjectAssociationsToUser(user, persisted); + mcpTokenDao.removeByUserId(user.getId()); boolean success = _userDao.remove(user.getId()); return success && persisted.getUuid().equals(user.getExternalEntity()); }); diff --git a/server/src/test/java/com/cloud/user/AccountManagerImplTest.java b/server/src/test/java/com/cloud/user/AccountManagerImplTest.java index a2cc9495405e..5543ce9c6ef2 100644 --- a/server/src/test/java/com/cloud/user/AccountManagerImplTest.java +++ b/server/src/test/java/com/cloud/user/AccountManagerImplTest.java @@ -62,6 +62,7 @@ import org.apache.cloudstack.auth.UserTwoFactorAuthenticator; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.mcp.dao.McpTokenDao; import org.apache.cloudstack.resourcedetail.UserDetailVO; import org.apache.cloudstack.webhook.WebhookHelper; import org.junit.Assert; @@ -169,6 +170,9 @@ public class AccountManagerImplTest extends AccountManagentImplTestBase { @Mock ApiKeyPairDao apiKeyPairDaoMock; + @Mock + McpTokenDao mcpTokenDaoMock; + @Mock RegisterUserKeysCmd registerCmdMock; @@ -2247,6 +2251,7 @@ public void deleteAndCleanupUserTestUserCleanup() { accountManagerImpl.deleteAndCleanupUser(userVoMock); Mockito.verify(accountManagerImpl).removeUserApiKeys(userId); + Mockito.verify(mcpTokenDaoMock).removeByUserId(userId); Mockito.verify(_projectMgr).cleanupProjectsForUser(null, userVoMock); }