feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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 for the policies CLI subcommands."""
from googlecloudsdk.calliope import base
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class MCP(base.Group):
"""List, enable and disable MCP endpoints."""

View File

@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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 for the MCP policies CLI subcommands."""
from googlecloudsdk.calliope import base
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class ContentSecurity(base.Group):
"""Get/add/remove MCP content security."""

View File

@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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.
"""services mcp content-security add command."""
from googlecloudsdk.api_lib.services import services_util
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
from googlecloudsdk.core import properties
_PROJECT_RESOURCE = 'projects/%s'
_CONTENT_SECURITY_POLICY_DEFAULT = '/contentSecurityPolicies/%s'
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Add(base.Command):
"""Add MCP content security provider of a project.
Add MCP content security provider of a project.
## EXAMPLES
Add MCP content security provider of a project:
$ {command} my-mcp-content-security-provider
Add MCP content security provider of a project `my-project`:
$ {command} my-mcp-content-security-provider --project=my-project
"""
@staticmethod
def Args(parser):
common_flags.mcp_content_security_provider_flag(
suffix='to add'
).AddToParser(parser)
def Run(self, args):
"""Run command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The content security providers for a project.
"""
if args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE % args.project
else:
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE % project
op = serviceusage.AddContentSecurityProvider(
args.mcp_content_security_provider,
resource_name + _CONTENT_SECURITY_POLICY_DEFAULT % 'default',
)
if op is None:
return None
op = services_util.WaitOperation(op.name, serviceusage.GetOperationV2Beta)
services_util.PrintOperation(op)

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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.
"""services mcp content-security get command."""
import collections
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
_PROJECT_RESOURCE = 'projects/%s'
_CONTENT_SECURITY_POLICY_DEFAULT = '/contentSecurityPolicies/default'
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Get(base.Command):
"""Get MCP content security providers for a project.
Get MCP content security providers for a project.
## EXAMPLES
Get MCP content security providers for a project:
$ {command}
Get MCP content security providers for a project `my-project`:
$ {command} --project=my-project
"""
@staticmethod
def Args(parser):
parser.display_info.AddFormat("""
table(
contentSecurityProvider
)
""")
def Run(self, args):
"""Run command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The content security providers for a project.
"""
if args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE % args.project
else:
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE % project
mcp_content_security = serviceusage.GetContentSecurityPolicy(
resource_name + _CONTENT_SECURITY_POLICY_DEFAULT,
).mcpContentSecurity
content_security_providers = []
results = collections.namedtuple(
'ContentSecurityProvider', ['contentSecurityProvider']
)
for (
content_security_provider
) in mcp_content_security.contentSecurityProviders:
content_security_providers.append(results(content_security_provider.name))
return content_security_providers

View File

@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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.
"""services mcp content-security remove command."""
from googlecloudsdk.api_lib.services import services_util
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
from googlecloudsdk.core import properties
_PROJECT_RESOURCE = 'projects/%s'
_CONTENT_SECURITY_POLICY_DEFAULT = '/contentSecurityPolicies/%s'
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Remove(base.Command):
"""Remove MCP content security provider of a project.
Remove MCP content security provider of a project.
## EXAMPLES
Remove MCP content security provider of a project:
$ {command} my-mcp-content-security-provider
Remove MCP content security provider of a project `my-project`:
$ {command} my-mcp-content-security-provider --project=my-project
"""
@staticmethod
def Args(parser):
common_flags.mcp_content_security_provider_flag(
suffix='to remove'
).AddToParser(parser)
def Run(self, args):
"""Run command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The content security providers for a project.
"""
if args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE % args.project
else:
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE % project
op = serviceusage.RemoveContentSecurityProvider(
args.mcp_content_security_provider,
resource_name + _CONTENT_SECURITY_POLICY_DEFAULT % 'default',
)
if op is None:
return None
op = services_util.WaitOperation(op.name, serviceusage.GetOperationV2Beta)
services_util.PrintOperation(op)

View File

@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""services mcp disable command."""
from googlecloudsdk.api_lib.services import services_util
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
_OP_BASE_CMD = 'gcloud beta services operations '
_OP_WAIT_CMD = _OP_BASE_CMD + 'wait {0}'
_SERVICE = 'services/%s'
_PROJECT_RESOURCE = 'projects/{}'
_FOLDER_RESOURCE = 'folders/{}'
_ORGANIZATION_RESOURCE = 'organizations/{}'
_CONSUMER_POLICY_DEFAULT = '/consumerPolicies/{}'
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Disable(base.SilentCommand):
"""Disable a service for MCP on a project, folder or organization.
Disable a service for MCP on a project, folder or organization
## EXAMPLES
To disable a service for MCP called `my-service` on the current project, run:
$ {command} my-service
To disable a service for MCP called `my-service` on the project
`my-project`, run:
$ {command} my-service --project=my-project
To disable a service for MCP called `my-service` on the folder
`my-folder, run:
$ {command} my-service --folder=my-folder
To disable a service for MCP called `my-service` on the organization
`my-organization`, run:
$ {command} my-service --organization=my-organization
To run the same command asynchronously (non-blocking), run:
$ {command} my-service --async
"""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
common_flags.service_flag(suffix='to disable MCP').AddToParser(parser)
common_flags.add_resource_args(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run 'services mcp disable'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
Updated MCP Policy.
"""
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE.format(project)
if args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE.format(args.project)
project = args.project
if args.IsSpecified('folder'):
resource_name = _FOLDER_RESOURCE.format(args.folder)
folder = args.folder
else:
folder = None
if args.IsSpecified('organization'):
resource_name = _ORGANIZATION_RESOURCE.format(args.organization)
organization = args.organization
else:
organization = None
op = serviceusage.RemoveMcpEnableRule(
project,
args.service,
folder=folder,
organization=organization,
)
if op is None:
return None
if args.async_:
cmd = _OP_WAIT_CMD.format(op.name)
log.status.Print(
'Asynchronous operation is in progress... '
'Use the following command to wait for its '
f'completion:\n {cmd}'
)
return
op = services_util.WaitOperation(op.name, serviceusage.GetOperationV2Beta)
if op.error:
services_util.PrintOperation(op)
else:
log.status.Print(
f'The MCP endpoint for service {args.service} has been disabled for'
f' the resource {resource_name}.'
)

View File

@@ -0,0 +1,180 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""services mcp enable command."""
from googlecloudsdk.api_lib.services import services_util
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
_OP_BASE_CMD = 'gcloud beta services operations '
_OP_WAIT_CMD = _OP_BASE_CMD + 'wait {0}'
_SERVICE = 'services/%s'
_PROJECT_RESOURCE = 'projects/{}'
_FOLDER_RESOURCE = 'folders/{}'
_ORGANIZATION_RESOURCE = 'organizations/{}'
_CONSUMER_POLICY_DEFAULT = '/consumerPolicies/{}'
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Enable(base.SilentCommand):
"""Enable a service for MCP on a project, folder or organization.
Enable a service for MCP on a project, folder or organization
## EXAMPLES
To enable a service for MCP called `my-service` on the current project, run:
$ {command} my-service
To enable a service for MCP called `my-service` on the project
`my-project`, run:
$ {command} my-service --project=my-project
To enable a service for MCP called `my-service` on the folder
`my-folder, run:
$ {command} my-service --folder=my-folder
To enable a service for MCP called `my-service` on the organization
`my-organization`, run:
$ {command} my-service --organization=my-organization
To run the same command asynchronously (non-blocking), run:
$ {command} my-service --async
"""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
common_flags.service_flag(suffix='to enable MCP').AddToParser(parser)
common_flags.add_resource_args(parser)
common_flags.skip_mcp_endpoint_check_flag(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run 'services mcp enable'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
Updated MCP Policy.
"""
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE.format(project)
if args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE.format(args.project)
project = args.project
if args.IsSpecified('folder'):
resource_name = _FOLDER_RESOURCE.format(args.folder)
folder = args.folder
else:
folder = None
if args.IsSpecified('organization'):
resource_name = _ORGANIZATION_RESOURCE.format(args.organization)
organization = args.organization
else:
organization = None
# check if sevice has Mcp Config
service_metadata = serviceusage.GetServiceV2Beta(
f'{resource_name}/services/{args.service}'
)
if not args.skip_mcp_endpoint_check and (
not service_metadata.service.mcpServer
or not service_metadata.service.mcpServer.urls
):
log.error(
f'The service {args.service} does not have MCP endpoint.'
)
return
if not service_metadata.state.enableRules:
enable_msg = serviceusage.GetMcpEnabledError(resource_name)
do_enable = console_io.PromptContinue(
enable_msg,
default=False,
throw_if_unattended=True,
)
if do_enable:
enable_service_op, _ = serviceusage.AddEnableRule(
[args.service],
project,
folder=folder,
organization=organization,
)
# The operation should not be None when enable rules are empty,
# but in case it is, we check it here to avoid error.
if enable_service_op:
enable_service_op = services_util.WaitOperation(
enable_service_op.name, serviceusage.GetOperationV2Beta
)
if enable_service_op.error:
log.error(
f'Failed to enable the service {args.service} for the resource'
f' {resource_name}: {enable_service_op.error}'
)
return
else:
return
op = serviceusage.AddMcpEnableRule(
args.service,
project,
folder=folder,
organization=organization,
)
if op is None:
return None
if args.async_:
cmd = _OP_WAIT_CMD.format(op.name)
log.status.Print(
'Asynchronous operation is in progress... '
'Use the following command to wait for its '
f'completion:\n {cmd}'
)
return
op = services_util.WaitOperation(op.name, serviceusage.GetOperationV2Beta)
if op.error:
services_util.PrintOperation(op)
else:
log.status.Print(
f'The MCP endpoint for service {args.service} has been enabled for'
f' the resource {resource_name}.'
)

View File

@@ -0,0 +1,127 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""services mcp list command."""
import sys
from googlecloudsdk.api_lib.services import services_util
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class List(base.ListCommand):
"""List MCP services for a project, folder or organization.
This command lists the MCP services that are enabled or available (with MCP
endpoints) to be MCP enabled
by a project, folder or organization.
## EXAMPLES
To list the services the current project has enabled for MCP, run:
$ {command} --enabled
To list the services the current project can enable for MCP, run:
$ {command} --available
"""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
mode_group = parser.add_mutually_exclusive_group(required=False)
mode_group.add_argument(
'--enabled',
action='store_true',
help=(
'(DEFAULT) Return the MCP services which the project, folder or'
' organization has enabled.'
),
)
mode_group.add_argument(
'--available',
action='store_true',
help=(
'Return the services available to the '
'project, folder or organization to enable for MCP.'
),
)
common_flags.add_resource_args(parser)
base.PAGE_SIZE_FLAG.SetDefault(parser, 1000)
# Remove unneeded list-related flags from parser
base.URI_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat("""
table(
name:label=NAME:sort=1,
mcp_endpoint:label=MCP_ENDPOINT
)
""")
def Run(self, args):
"""Run 'services mcp list'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
The list of MCP services for the given project, folder or organization.
"""
# Default mode is --enabled, so if no flags were specified,
# turn on the args.enabled flag.
if not (args.enabled or args.available):
args.enabled = True
if args.IsSpecified('project'):
project = args.project
else:
project = services_util.GetValidatedProject(args.project)
if args.IsSpecified('folder'):
folder = args.folder
else:
folder = None
if args.IsSpecified('organization'):
organization = args.organization
else:
organization = None
if args.IsSpecified('limit'):
limit = args.limit
else:
limit = sys.maxsize
return serviceusage.ListMcpServicesV2Beta(
project,
args.enabled,
args.page_size,
limit=limit,
folder=folder,
organization=organization,
)

View File

@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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 for the MCP policies CLI subcommands."""
from googlecloudsdk.calliope import base
# TODO(b/321801975) make command public after suv2 launch.
@base.UniverseCompatible
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Policies(base.Group):
"""Get/update MCP policies and get the effective MCP policy."""

View File

@@ -0,0 +1,179 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""services mcp policies get command."""
import json
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import yaml
from googlecloudsdk.core.util import files
_PROJECT_RESOURCE = 'projects/{}'
_FOLDER_RESOURCE = 'folders/{}'
_ORGANIZATION_RESOURCE = 'organizations/{}'
_MCP_POLICY_DEFAULT = '/mcpPolicies/{}'
_INVALID_TIMESTAMP = (
# Invalid timestamp as the consumer policy is not created previously.
'1970-01-01T00:00:00Z'
)
# TODO(b/321801975) make command public after suv2 launch.
@base.UniverseCompatible
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Get(base.Command):
"""Get MCP policy for a project, folder or organization.
Get MCP policy for a project, folder or
organization.
## EXAMPLES
Get MCP policy for default policy on current project:
$ {command}
OR
$ {command} --policy-name=default
Get MCP policy for default policy on current project and save the
content in an output file:
$ {command} --output-file=/path/to/the/file.yaml
OR
$ {command} --output-file=/path/to/the/file.json
"""
@staticmethod
def Args(parser):
parser.add_argument(
'--policy-name',
help='Name of the MCP policy. Currently only "default" is supported.',
default='default',
)
common_flags.add_resource_args(parser)
parser.add_argument(
'--output-file',
help=(
'Path to the file to write policy contents to. Supported format:'
'.yaml or .json.'
),
)
def Run(self, args):
"""Run command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Resource name and its parent name.
"""
if args.IsSpecified('folder'):
resource_name = _FOLDER_RESOURCE.format(args.folder)
elif args.IsSpecified('organization'):
resource_name = _ORGANIZATION_RESOURCE.format(args.organization)
elif args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE.format(args.project)
else:
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE.format(project)
policy = serviceusage.GetMcpPolicy(
resource_name + _MCP_POLICY_DEFAULT.format(args.policy_name),
)
if args.IsSpecified('output_file'):
if not (
args.output_file.endswith('.json')
or args.output_file.endswith('.yaml')
):
log.error(
'Invalid output-file format. Please provide path to a yaml or json'
' file.'
)
else:
if args.output_file.endswith('.json'):
data = json.dumps(_ConvertToDict(policy), sort_keys=False)
else:
data = yaml.dump(_ConvertToDict(policy), round_trip=True)
files.WriteFileContents(args.output_file, data)
log.status.Print(
'Policy written to the output file %s ' % args.output_file
)
elif args.IsSpecified('format'):
return policy
else:
result = _ConvertToDict(policy)
for k, v in result.items():
if k not in ['mcpEnableRules'] and v:
log.status.Print(k + ': ' + v)
elif k == 'mcpEnableRules':
log.status.Print(k + ':')
for enable_rule in v:
_PrintRules(enable_rule)
return
def _ConvertToDict(policy):
"""ConvertToDict command.
Args:
policy: mcpPolicy to be convert to orderedDict.
Returns:
orderedDict.
"""
output = {
'name': policy.name,
'mcpEnableRules': [],
'updateTime': policy.updateTime,
'createTime': policy.createTime,
'etag': policy.etag,
}
for enable_rule in policy.mcpEnableRules:
if enable_rule.mcpServices:
output['mcpEnableRules'].append(
{'mcpservices': list(enable_rule.mcpServices)}
)
if not policy.mcpEnableRules:
del output['mcpEnableRules']
if policy.updateTime == _INVALID_TIMESTAMP:
del output['updateTime']
if policy.createTime == _INVALID_TIMESTAMP:
del output['createTime']
return output
def _PrintRules(rule):
keys = ['mcpServices']
for key in keys:
if key in rule.keys():
log.status.Print(' ' + key + ':')
for mcpservices in rule[key]:
for services in mcpservices:
log.status.Print(' - ' + services)

View File

@@ -0,0 +1,117 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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.
# TODO: b/300099033 - Capitalize and turn into a sentence.
"""services MCP policies get-effective-policy command."""
import collections
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
_PROJECT_RESOURCE = 'projects/{}'
_FOLDER_RESOURCE = 'folders/{}'
_ORGANIZATION_RESOURCE = 'organizations/{}'
# TODO: b/321801975 - Make command public after suv2 launch.
@base.UniverseCompatible
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class GetEffectivePolicy(base.Command):
"""Get effective MCP policy for a project, folder or organization.
Get effective MCP policy for a project, folder or organization.
## EXAMPLES
Get effective MCP policy for the current project:
$ {command}
Get effective MCP policy for project `my-project`:
$ {command} --project=my-project
"""
@staticmethod
def Args(parser):
parser.add_argument(
'--view',
help=(
'The view of the effective MCP policy. BASIC includes basic'
' metadata about the effective MCP policy. FULL includes every'
' information related to effective MCP policy.'
),
choices=['BASIC', 'FULL'],
default='BASIC',
)
common_flags.add_resource_args(parser)
parser.display_info.AddFormat("""
table(
EnabledMcpService:label=EnabledMcpService:sort=1,
EnabledMcpPolicies:label=EnabledMcpPolicies
)
""")
def Run(self, args):
"""Run command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Effective Policy.
"""
if args.IsSpecified('folder'):
resource_name = _FOLDER_RESOURCE.format(args.folder)
elif args.IsSpecified('organization'):
resource_name = _ORGANIZATION_RESOURCE.format(args.organization)
elif args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE.format(args.project)
else:
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE.format(project)
response = serviceusage.GetEffectiveMcpPolicy(
resource_name + '/effectiveMcpPolicy', args.view
)
if args.IsSpecified('format'):
return response
else:
log.status.Print('McpEnableRules:')
for enable_rule in response.mcpEnableRules:
log.status.Print(' McpServices:')
for mcp_service in enable_rule.mcpServices:
log.status.Print(' - %s' % mcp_service.service)
if args.view == 'FULL':
log.status.Print('\nMetadata of effective policy:')
result = []
resources = collections.namedtuple(
'serviceMcpSources', ['EnabledMcpService', 'EnabledMcpPolicies']
)
for metadata in response.mcpEnableRuleMetadata:
for values in metadata.serviceMcpSources.additionalProperties:
result.append(resources(values.key, values.value.policies))
return result

View File

@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google Inc. All Rights Reserved.
#
# Licensed 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.
"""services mcp policies test-enabled command."""
from googlecloudsdk.api_lib.services import serviceusage
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.services import common_flags
from googlecloudsdk.core import properties
_PROJECT_RESOURCE = 'projects/%s'
_FOLDER_RESOURCE = 'folders/%s'
_ORGANIZATION_RESOURCE = 'organizations/%s'
_SERVICE = 'services/%s'
# TODO(b/321801975) make command public after suv2 launch.
@base.UniverseCompatible
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class TestEnabled(base.Command):
"""Test a service against the result of merging MCP policies in the resource hierarchy.
Test a service against the result of merging MCP policies in the resource
hierarchy.
## EXAMPLES
Test for service my-service for current project:
$ {command} my-service
Test for service my-service for project `my-project`:
$ {command} my-service --project=my-project
"""
@staticmethod
def Args(parser):
common_flags.add_resource_args(parser)
parser.add_argument(
'service', help='Name of the service. example: foobar.googleapis.com'
)
def Run(self, args):
"""Run command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The enablement of the given service.
"""
resource = 'project'
if args.IsSpecified('folder'):
resource_name = _FOLDER_RESOURCE % args.folder
resource = 'folder'
elif args.IsSpecified('organization'):
resource_name = _ORGANIZATION_RESOURCE % args.organization
resource = 'organization'
elif args.IsSpecified('project'):
resource_name = _PROJECT_RESOURCE % args.project
else:
project = properties.VALUES.core.project.Get(required=True)
resource_name = _PROJECT_RESOURCE % project
response = serviceusage.TestMcpEnabled(
resource_name, _SERVICE % args.service
)
# If mcpEnableRules is empty that means service is not enabled.
if response.mcpEnableRules:
return (
f'MCP is ENABLED for Service {args.service} for the'
f' {resource} {resource_name}.'
)
else:
return (
f'MCP is NOT ENABLED for Service {args.service} for the'
f' {resource} {resource_name}.'
)