alibaba-cloud-ops-mcp-server 0.7.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ from . import server
2
+ import asyncio
3
+ import logging
4
+
5
+ logging.getLogger().setLevel(logging.INFO)
6
+
7
+ def main():
8
+ """Main entry point for the package."""
9
+ asyncio.run(server.main())
10
+
11
+ __all__ = ['main', 'server']
@@ -0,0 +1,164 @@
1
+ # -------------------------------------------------------------------------------
2
+ # Copyright (c) 2019 Aliyun.com All right reserved. This software is the
3
+ # confidential and proprietary information of Aliyun.com ("Confidential
4
+ # Information"). You shall not disclose such Confidential Information and shall
5
+ # use it only in accordance with the terms of the license agreement you entered
6
+ # into with Aliyun.com .
7
+ # -------------------------------------------------------------------------------
8
+ import requests
9
+
10
+ API_META_KEYS = (VERSION, RESPONSES, SCHEMA, PROPERTIES, HTTP_SUCCESS_CODE, DEFAULT_VERSION, CODE, REF, APIS,
11
+ SERVICE_KEY, NAME, IN, PARAMETERS, STYLE, BODY) \
12
+ = ('version', 'responses', 'schema', 'properties', '200', 'defaultVersion', 'code', '$ref', 'apis', 'service',
13
+ 'name', 'in', 'parameters', 'style', 'body')
14
+
15
+
16
+
17
+ class ApiMetaClient:
18
+ PATH = 'path'
19
+ METHODS = 'methods'
20
+ BASE_URL = 'https://api.aliyun.com/meta/v1'
21
+ POP_API_NAME = (GET_PRODUCT_LIST, GET_API_OVERVIEW, GET_API_INFO, GET_APIDOCS) = \
22
+ ('GetProductList', 'GetApiOverview', 'GetApiInfo', 'GetAPIDocs')
23
+
24
+ config = {
25
+ 'GetProductList': {'path': 'products.json'},
26
+ 'GetApiOverview': {'path': 'products/{service}/versions/{version}/overview.json'},
27
+ 'GetApiInfo': {'path': 'products/{service}/versions/{version}/apis/{api}/api.json'},
28
+ 'GetAPIDocs': {'path': 'products/{service}/versions/{version}/api-docs.json'},
29
+ }
30
+
31
+ @classmethod
32
+ def get_response_from_pop_api(cls, pop_api_name, service=None, api=None, version=None):
33
+ try:
34
+ api_config = cls.config.get(pop_api_name)
35
+ try:
36
+ formatted_path = api_config[cls.PATH].format(service=service, api=api, version=version)
37
+ except KeyError as e:
38
+ raise Exception(f'Failed to format path, path: {api_config[cls.PATH]}, error: {e}')
39
+
40
+ url = f'{cls.BASE_URL}/{formatted_path}'
41
+ response = requests.get(url)
42
+ return response.json()
43
+ except Exception as e:
44
+ raise Exception(f'Failed to get response from pop api, url: {url}, error: {e}')
45
+
46
+ @classmethod
47
+ def get_service_version(cls, service):
48
+ data = cls.get_response_from_pop_api(cls.GET_PRODUCT_LIST)
49
+ version = next((item.get(DEFAULT_VERSION) for item in data if item.get(CODE).lower() == service), None)
50
+ return version
51
+
52
+ @classmethod
53
+ def get_service_style(cls, service):
54
+ data = cls.get_response_from_pop_api(cls.GET_PRODUCT_LIST)
55
+ style = next((item.get(STYLE) for item in data if item.get(CODE).lower() == service), 'RPC')
56
+ return style
57
+
58
+ @classmethod
59
+ def get_standard_service_and_api(cls, service, api=None, version=None):
60
+ data = cls.get_response_from_pop_api(cls.GET_PRODUCT_LIST)
61
+ service_standard = (next((item.get(CODE) for item in data if item.get(CODE).lower() == service), None))
62
+ api_standard = None
63
+ if api:
64
+ apis = cls.get_response_from_pop_api(cls.GET_API_OVERVIEW, service=service_standard,
65
+ version=version).get(APIS, {})
66
+ for api_name in apis:
67
+ if api_name.lower() == api.lower():
68
+ api_standard = api_name
69
+ return service_standard, api_standard
70
+
71
+ @classmethod
72
+ def get_api_meta(cls, service, api):
73
+ service = service.lower()
74
+ # API_META不包含ROA类型的API,需要通过POP平台的API GetProductList获取Service对应的Version
75
+ # 获取POP平台API META参考文档:https://api.aliyun.com/openmeta/guide
76
+ version = cls.get_service_version(service)
77
+ service_standard, api_standard = cls.get_standard_service_and_api(service, api, version)
78
+ data = cls.get_response_from_pop_api(cls.GET_API_INFO, service_standard, api_standard, version)
79
+ return data, version
80
+
81
+ @classmethod
82
+ def get_response_from_api_meta(cls, service, api):
83
+ api_meta, version = cls.get_api_meta(service, api)
84
+ property_values = api_meta.get(RESPONSES, {}).get(HTTP_SUCCESS_CODE, {}).get(SCHEMA, {}).get(PROPERTIES, {})
85
+ return property_values, version
86
+
87
+ @classmethod
88
+ def get_ref_api_meta(cls, data, service, version):
89
+ service_standard, _ = cls.get_standard_service_and_api(service=service, version=version)
90
+ current_data = cls.get_response_from_pop_api(cls.GET_API_OVERVIEW, service=service_standard, version=version)
91
+ ref_path = data.get(REF)
92
+ path = ref_path.lstrip('#/').split('/')
93
+ for _key in path:
94
+ if _key in current_data:
95
+ current_data = current_data[_key]
96
+ else:
97
+ raise KeyError(f"Path {_key} not found in the JSON data.")
98
+
99
+ return current_data
100
+
101
+ @classmethod
102
+ def get_api_parameters(cls, service, api, params_in=''):
103
+ """
104
+ params_in: 过滤参数位置,取值:'host', 'query', 'body', 'header',若为空,则返回所有参数
105
+ """
106
+ api_meta, _ = cls.get_api_meta(service, api)
107
+ parameters = api_meta.get(PARAMETERS)
108
+ param_names = []
109
+ additional_props = []
110
+ # 避免循环引用
111
+ visited_refs = set()
112
+
113
+ def get_ref(data, _):
114
+ props = []
115
+ if not isinstance(data, dict):
116
+ return props
117
+ if REF in data:
118
+ ref_path = data.get(REF)
119
+ if ref_path in visited_refs:
120
+ return props
121
+ visited_refs.add(ref_path)
122
+ referenced_schema = cls.get_ref_api_meta(data, service, _)
123
+ props.extend(get_ref(referenced_schema, _))
124
+ return props
125
+ if PROPERTIES in data:
126
+ for prop_name, prop_details in data.get(PROPERTIES, {}).items():
127
+ props.append(prop_name)
128
+ if isinstance(prop_details, dict) and REF in prop_details:
129
+ props.extend(get_ref(prop_details, _))
130
+ return props
131
+
132
+ for param in parameters:
133
+ if params_in and param.get(IN) != params_in:
134
+ continue
135
+ param_name = param.get(NAME)
136
+ if param_name:
137
+ param_names.append(param_name)
138
+ schema = param.get(SCHEMA, {})
139
+ extracted_props = get_ref(schema, _)
140
+ additional_props.extend(extracted_props)
141
+ combined_params = param_names + additional_props
142
+ return combined_params
143
+
144
+ @classmethod
145
+ def get_apis_in_service(cls, service, version):
146
+ data = cls.get_response_from_pop_api(cls.GET_API_OVERVIEW, service=service, version=version)
147
+ apis = list(data[APIS].keys())
148
+ return apis
149
+
150
+ @classmethod
151
+ def get_api_field(cls, field_type, service, api, default=None):
152
+ try:
153
+ data, _ = cls.get_api_meta(service, api)
154
+ return data.get(field_type, default)
155
+ except Exception as e:
156
+ return default
157
+
158
+ @classmethod
159
+ def get_api_body_style(cls, service, api):
160
+ parameters = cls.get_api_field(PARAMETERS, service, api)
161
+ body_style = None
162
+ if parameters:
163
+ body_style = next((param.get(STYLE) for param in parameters if param.get(IN) == BODY), None)
164
+ return body_style
@@ -0,0 +1,120 @@
1
+ from pydantic import Field
2
+ from typing import List
3
+ import os
4
+ import json
5
+
6
+ from alibabacloud_cms20190101.client import Client as cms20190101Client
7
+ from alibabacloud_tea_openapi import models as open_api_models
8
+ from alibabacloud_cms20190101 import models as cms_20190101_models
9
+ from alibabacloud_tea_util import models as util_models
10
+ from alibabacloud_tea_util.client import Client as UtilClient
11
+
12
+
13
+ END_STATUSES = ['Success', 'Failed', 'Cancelled']
14
+
15
+
16
+ tools = []
17
+
18
+ def create_client(region_id: str) -> cms20190101Client:
19
+ config = open_api_models.Config(
20
+ access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
21
+ access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
22
+ user_agent='alibaba-cloud-ops-mcp-server',
23
+ )
24
+ config.endpoint = f'metrics.{region_id}.aliyuncs.com'
25
+ return cms20190101Client(config)
26
+
27
+
28
+ def _get_cms_metric_data(region_id: str, instance_ids: List[str], metric_name: str):
29
+ client = create_client(region_id)
30
+ dimesion = []
31
+ for instance_id in instance_ids:
32
+ dimesion.append({
33
+ 'instanceId': instance_id
34
+ })
35
+ describe_metric_last_request = cms_20190101_models.DescribeMetricLastRequest(
36
+ namespace='acs_ecs_dashboard',
37
+ metric_name=metric_name,
38
+ dimensions=json.dumps(dimesion),
39
+ )
40
+ describe_metric_last_resp = client.describe_metric_last(describe_metric_last_request)
41
+ return describe_metric_last_resp.body.datapoints
42
+
43
+ @tools.append
44
+ def GetCpuUsageData(
45
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
46
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
47
+ ):
48
+ """获取ECS实例的CPU使用率数据"""
49
+ return _get_cms_metric_data(RegionId, InstanceIds, 'cpu_total')
50
+
51
+
52
+ @tools.append
53
+ def GetCpuLoadavgData(
54
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
55
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
56
+ ):
57
+ """获取CPU一分钟平均负载指标数据"""
58
+ return _get_cms_metric_data(RegionId, InstanceIds, 'load_1m')
59
+
60
+
61
+ @tools.append
62
+ def GetCpuloadavg5mData(
63
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
64
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
65
+ ):
66
+ """获取CPU五分钟平均负载指标数据"""
67
+ return _get_cms_metric_data(RegionId, InstanceIds, 'load_5m')
68
+
69
+
70
+ @tools.append
71
+ def GetCpuloadavg15mData(
72
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
73
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
74
+ ):
75
+ """获取CPU十五分钟平均负载指标数据"""
76
+ return _get_cms_metric_data(RegionId, InstanceIds, 'load_15m')
77
+
78
+ @tools.append
79
+ def GetMemUsedData(
80
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
81
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
82
+ ):
83
+ """获取内存使用量指标数据"""
84
+ return _get_cms_metric_data(RegionId, InstanceIds, 'memory_usedspace')
85
+
86
+
87
+ @tools.append
88
+ def GetMemUsageData(
89
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
90
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
91
+ ):
92
+ """获取内存利用率指标数据"""
93
+ return _get_cms_metric_data(RegionId, InstanceIds, 'memory_usedutilization')
94
+
95
+
96
+ @tools.append
97
+ def GetDiskUsageData(
98
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
99
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
100
+ ):
101
+ """获取磁盘利用率指标数据"""
102
+ return _get_cms_metric_data(RegionId, InstanceIds, 'diskusage_utilization')
103
+
104
+
105
+ @tools.append
106
+ def GetDiskTotalData(
107
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
108
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
109
+ ):
110
+ """获取磁盘分区总容量指标数据"""
111
+ return _get_cms_metric_data(RegionId, InstanceIds, 'diskusage_total')
112
+
113
+
114
+ @tools.append
115
+ def GetDiskUsedData(
116
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
117
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
118
+ ):
119
+ """获取磁盘分区使用量指标数据"""
120
+ return _get_cms_metric_data(RegionId, InstanceIds, 'diskusage_used')
@@ -0,0 +1,36 @@
1
+ """
2
+ ========================================
3
+ Tools config
4
+ ========================================
5
+ """
6
+
7
+ config = {
8
+ 'ecs': [
9
+ 'DescribeInstances',
10
+ 'DescribeRegions',
11
+ 'DescribeZones',
12
+ 'DescribeAccountAttributes',
13
+ 'DescribeAvailableResource',
14
+ 'DescribeImages',
15
+ 'DescribeSecurityGroups',
16
+ 'DeleteInstances'
17
+ ],
18
+ 'Vpc': [
19
+ 'DescribeVpcs',
20
+ 'DescribeVSwitches'
21
+ ]
22
+ }
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
@@ -0,0 +1,196 @@
1
+ from pydantic import Field
2
+ from typing import List
3
+ import os
4
+ import json
5
+ import time
6
+
7
+ from alibabacloud_oos20190601.client import Client as oos20190601Client
8
+ from alibabacloud_tea_openapi import models as open_api_models
9
+ from alibabacloud_oos20190601 import models as oos_20190601_models
10
+ from alibabacloud_tea_util import models as util_models
11
+ from alibabacloud_tea_util.client import Client as UtilClient
12
+
13
+
14
+ END_STATUSES = ['Success', 'Failed', 'Cancelled']
15
+
16
+
17
+ tools = []
18
+
19
+ def create_client(region_id: str) -> oos20190601Client:
20
+ config = open_api_models.Config(
21
+ access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
22
+ access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
23
+ user_agent='alibaba-cloud-ops-mcp-server',
24
+ )
25
+ config.endpoint = f'oos.{region_id}.aliyuncs.com'
26
+ return oos20190601Client(config)
27
+
28
+
29
+ def _start_execution_sync(region_id: str, template_name: str, parameters: dict):
30
+ client = create_client(region_id=region_id)
31
+ start_execution_request = oos_20190601_models.StartExecutionRequest(
32
+ region_id=region_id,
33
+ template_name=template_name,
34
+ parameters=json.dumps(parameters)
35
+ )
36
+ start_execution_resp = client.start_execution(start_execution_request)
37
+ execution_id = start_execution_resp.body.execution.execution_id
38
+
39
+ while True:
40
+ list_executions_request = oos_20190601_models.ListExecutionsRequest(
41
+ region_id=region_id,
42
+ execution_id=execution_id
43
+ )
44
+ list_executions_resp = client.list_executions(list_executions_request)
45
+ status = list_executions_resp.body.executions[0].status
46
+ if status in END_STATUSES:
47
+ return list_executions_resp.body
48
+ time.sleep(1)
49
+ @tools.append
50
+ def RunCommand(
51
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
52
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
53
+ CommandType: str = Field(description='ECS实例上执行的命令类型,可选值:RunShellScript,RunPythonScript,RunPerlScript,RunBatScript,RunPowerShellScript', default='RunShellScript'),
54
+ Command: str = Field(description='ECS实例上执行的命令内容'),
55
+ ):
56
+ """批量在多台ECS实例上运行云助手命令,适用于需要同时管理多台ECS实例的场景,如应用程序管理和资源标记操作等。"""
57
+
58
+ parameters = {
59
+ 'regionId': RegionId,
60
+ 'resourceType': 'ALIYUN::ECS::Instance',
61
+ 'targets': {
62
+ 'ResourceIds': InstanceIds,
63
+ 'RegionId': RegionId,
64
+ 'Type': 'ResourceIds',
65
+ 'Parameters': {
66
+ 'RegionId': RegionId,
67
+ 'Status': 'Running'
68
+ }
69
+ },
70
+ "commandType": CommandType,
71
+ "commandContent": Command
72
+ }
73
+ return _start_execution_sync(region_id=RegionId, template_name='ACS-ECS-BulkyRunCommand', parameters=parameters)
74
+
75
+
76
+ @tools.append
77
+ def StartInstances(
78
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
79
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
80
+ ):
81
+ """批量启动ECS实例,适用于需要同时管理和启动多台ECS实例的场景,例如应用部署和高可用性场景。"""
82
+
83
+ parameters = {
84
+ 'regionId': RegionId,
85
+ 'resourceType': 'ALIYUN::ECS::Instance',
86
+ 'targets': {
87
+ 'ResourceIds': InstanceIds,
88
+ 'RegionId': RegionId,
89
+ 'Type': 'ResourceIds'
90
+ }
91
+ }
92
+ return _start_execution_sync(region_id=RegionId, template_name='ACS-ECS-BulkyStartInstances', parameters=parameters)
93
+
94
+
95
+ @tools.append
96
+ def StopInstances(
97
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
98
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
99
+ ForeceStop: bool = Field(description='是否强制关机', default=False),
100
+ ):
101
+ """批量停止ECS实例,适用于需要同时管理和停止多台ECS实例的场景。"""
102
+
103
+ parameters = {
104
+ 'regionId': RegionId,
105
+ 'resourceType': 'ALIYUN::ECS::Instance',
106
+ 'targets': {
107
+ 'ResourceIds': InstanceIds,
108
+ 'RegionId': RegionId,
109
+ 'Type': 'ResourceIds'
110
+ },
111
+ 'forceStop': ForeceStop
112
+ }
113
+ return _start_execution_sync(region_id=RegionId, template_name='ACS-ECS-BulkyStopInstances', parameters=parameters)
114
+
115
+
116
+ @tools.append
117
+ def RebootInstances(
118
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
119
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
120
+ ForeceStop: bool = Field(description='是否强制关机', default=False),
121
+ ):
122
+ """批量重启ECS实例,适用于需要同时管理和重启多台ECS实例的场景。"""
123
+
124
+ parameters = {
125
+ 'regionId': RegionId,
126
+ 'resourceType': 'ALIYUN::ECS::Instance',
127
+ 'targets': {
128
+ 'ResourceIds': InstanceIds,
129
+ 'RegionId': RegionId,
130
+ 'Type': 'ResourceIds'
131
+ },
132
+ 'forceStop': ForeceStop
133
+ }
134
+ return _start_execution_sync(region_id=RegionId, template_name='ACS-ECS-BulkyRebootInstances', parameters=parameters)
135
+
136
+
137
+ @tools.append
138
+ def RunInstances(
139
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
140
+ ImageId: str = Field(description='镜像ID'),
141
+ InstanceType: str = Field(description='实例规格'),
142
+ SecurityGroupId: str = Field(description='安全组ID'),
143
+ VSwitchId: str = Field(description='交换机ID'),
144
+ Amount: int = Field(description='创建数量', default=1),
145
+ InstanceName: str = Field(description='实例名称', default=''),
146
+ ):
147
+ """批量创建ECS实例,适用于需要同时创建多台ECS实例的场景,例如应用部署和高可用性场景。"""
148
+
149
+ parameters = {
150
+ 'imageId': ImageId,
151
+ 'instanceType': InstanceType,
152
+ 'securityGroupId': SecurityGroupId,
153
+ 'vSwitchId': VSwitchId,
154
+ 'amount': Amount,
155
+ 'instanceName': InstanceName
156
+ }
157
+ return _start_execution_sync(region_id=RegionId, template_name='ACS-ECS-RunInstances', parameters=parameters)
158
+
159
+
160
+ @tools.append
161
+ def ResetPassword(
162
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
163
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
164
+ Password: str = Field(description='ECS实例的密码,8-30个字符且只能包含以下限制条件中的字符:小写字母,大写字母,数字,只可包含特殊字符()~!@#$%^&*-_+=(40:<>,?/'),
165
+ ):
166
+ """批量修改ECS实例的密码,请注意,本操作将会重启ECS实例"""
167
+ parameters = {
168
+ 'regionId': RegionId,
169
+ 'resourceType': 'ALIYUN::ECS::Instance',
170
+ 'targets': {
171
+ 'ResourceIds': InstanceIds,
172
+ 'RegionId': RegionId,
173
+ 'Type': 'ResourceIds'
174
+ },
175
+ 'password': Password
176
+ }
177
+ return _start_execution_sync(region_id=RegionId, template_name='ACS-ECS-BulkyResetPassword', parameters=parameters)
178
+
179
+ @tools.append
180
+ def ReplaceSystemDisk(
181
+ RegionId: str = Field(description='AlibabaCloud region ID', default='cn-hangzhou'),
182
+ InstanceIds: List[str] = Field(description='AlibabaCloud ECS instance ID List'),
183
+ ImageId: str = Field(description='镜像ID')
184
+ ):
185
+ """批量替换ECS实例的系统盘,更换操作系统"""
186
+ parameters = {
187
+ 'regionId': RegionId,
188
+ 'resourceType': 'ALIYUN::ECS::Instance',
189
+ 'targets': {
190
+ 'ResourceIds': InstanceIds,
191
+ 'RegionId': RegionId,
192
+ 'Type': 'ResourceIds'
193
+ },
194
+ 'imageId': ImageId
195
+ }
196
+ return _start_execution_sync(region_id=RegionId, template_name='ACS-ECS-BulkyReplaceSystemDisk', parameters=parameters)
@@ -0,0 +1,197 @@
1
+ # server.py
2
+ import os
3
+ from mcp.server.fastmcp import FastMCP, Context
4
+ from pydantic import Field
5
+ import click
6
+ import logging
7
+
8
+ import inspect
9
+ import types
10
+ from dataclasses import make_dataclass, field
11
+ from alibabacloud_tea_openapi import models as open_api_models
12
+ from alibabacloud_tea_util import models as util_models
13
+ from alibabacloud_tea_openapi.client import Client as OpenApiClient
14
+ from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
15
+ from alibaba_cloud_ops_mcp_server.api_meta_client import ApiMetaClient
16
+ from alibaba_cloud_ops_mcp_server.config import config
17
+
18
+ from alibaba_cloud_ops_mcp_server import oos_tools
19
+ from alibaba_cloud_ops_mcp_server import cms_tools
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ type_map = {
25
+ 'string': str,
26
+ 'integer': int,
27
+ 'boolean': bool,
28
+ 'array': list,
29
+ 'object': dict,
30
+ 'number': float
31
+ }
32
+
33
+
34
+ def create_client(service: str, region_id: str) -> OpenApiClient:
35
+ config = open_api_models.Config(
36
+ access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
37
+ access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
38
+ user_agent='alibaba-cloud-ops-mcp-server',
39
+ )
40
+ if isinstance(service, str):
41
+ service = service.lower()
42
+ config.endpoint = f'{service}.{region_id}.aliyuncs.com'
43
+ return OpenApiClient(config)
44
+
45
+
46
+ def tools_api_call(service: str, api: str, parameters: dict, ctx: Context):
47
+ service = service.lower()
48
+ api_meta, _ = ApiMetaClient.get_api_meta(service, api)
49
+ version = ApiMetaClient.get_service_version(service)
50
+ method = 'POST' if api_meta.get('methods', [])[0] == 'post' else 'GET'
51
+ path = api_meta.get('path', '/')
52
+ style = ApiMetaClient.get_service_style(service)
53
+ req = open_api_models.OpenApiRequest(
54
+ query=OpenApiUtilClient.query(parameters)
55
+ )
56
+ params = open_api_models.Params(
57
+ action=api,
58
+ version=version,
59
+ protocol='HTTPS',
60
+ pathname=path,
61
+ method=method,
62
+ auth_type='AK',
63
+ style=style,
64
+ req_body_type='formData',
65
+ body_type='json'
66
+ )
67
+ client = create_client(service, parameters.get('RegionId', 'cn-hangzhou'))
68
+ runtime = util_models.RuntimeOptions()
69
+ return client.call_api(params, req, runtime)
70
+
71
+
72
+ def create_parameter_schema(fields: dict):
73
+ return make_dataclass("ParameterSchema", [(name, type_, value) for name, (type_, value) in fields.items()])
74
+
75
+
76
+ def create_function_schemas(service, api, api_meta):
77
+ schemas = {}
78
+ schemas[api] = {}
79
+ parameters = api_meta['parameters']
80
+ for parameter in parameters:
81
+ name = parameter.get('name')
82
+ # TODO 目前忽略了带'.'的参数
83
+ if '.' in name:
84
+ continue
85
+ schema = parameter.get('schema', '')
86
+ description = schema.get('description', '')
87
+ example = schema.get('example', '')
88
+ type_ = schema.get('type', '')
89
+ description = f'{description} 请注意,提供参数要严格按照参数的类型和参数示例的提示,如果提到参数为String,且为一个 JSON 数组字符串,应在数组内使用单引号包裹对应的参数以避免转义问题,并在最外侧用双引号包裹以确保其是字符串,否则可能会导致参数解析错误。参数类型: {type_},参数示例:{example}'
90
+ required = schema.get('required', False)
91
+ python_type = type_map.get(type_, str)
92
+ field_info = (
93
+ python_type,
94
+ field(
95
+ default=None,
96
+ metadata={'description': description, 'required': required}
97
+ )
98
+ )
99
+ schemas[api][name] = field_info
100
+ if 'RegionId' not in schemas[api]:
101
+ schemas[api]['RegionId'] = (
102
+ str,
103
+ field(
104
+ default=None,
105
+ metadata={'description': '地域ID', 'required': False}
106
+ )
107
+ )
108
+ return schemas
109
+
110
+
111
+ def create_tool_function_with_signature(service: str, function_name: str, fields: dict, description: str):
112
+ """
113
+ Dynamically creates a lambda function with a custom signature based on the provided fields.
114
+ """
115
+ parameters = []
116
+ annotations = {}
117
+ defaults = {}
118
+
119
+ for name, (type_, field_info) in fields.items():
120
+ field_description = field_info.metadata.get('description', '')
121
+ is_required = field_info.metadata.get('required', False)
122
+ default_value = field_info.default if not is_required else ...
123
+
124
+ field_default = Field(default=default_value, description=field_description)
125
+ parameters.append(inspect.Parameter(
126
+ name=name,
127
+ kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
128
+ default=field_default,
129
+ annotation=type_
130
+ ))
131
+ annotations[name] = type_
132
+ defaults[name] = field_default
133
+
134
+ signature = inspect.Signature(parameters)
135
+
136
+ def func_code(*args, **kwargs):
137
+ bound_args = signature.bind(*args, **kwargs)
138
+ bound_args.apply_defaults()
139
+
140
+ return tools_api_call(
141
+ service=service,
142
+ api=function_name,
143
+ parameters=bound_args.arguments,
144
+ ctx=None
145
+ )
146
+
147
+ func = types.FunctionType(
148
+ func_code.__code__,
149
+ globals(),
150
+ function_name,
151
+ None,
152
+ func_code.__closure__
153
+ )
154
+ func.__signature__ = signature
155
+ func.__annotations__ = annotations
156
+ func.__defaults__ = tuple(defaults.values())
157
+ func.__doc__ = description
158
+
159
+ return func
160
+
161
+
162
+ def create_and_decorate_tool(mcp: FastMCP, service: str, api: str):
163
+ """Create a tool function for a Lambda function."""
164
+ api_meta, _ = ApiMetaClient.get_api_meta(service, api)
165
+ fields = create_function_schemas(service, api, api_meta).get(api, {})
166
+ description = api_meta.get('summary', '')
167
+ dynamic_lambda = create_tool_function_with_signature(service, api, fields, description)
168
+ decorated_function = mcp.tool(name=api)(dynamic_lambda)
169
+
170
+ return decorated_function
171
+
172
+
173
+ @click.command()
174
+ @click.option(
175
+ "--transport",
176
+ type=click.Choice(["stdio", "sse"]),
177
+ default="stdio",
178
+ help="Transport type",
179
+ )
180
+ def main(transport: str):
181
+ # Create an MCP server
182
+ mcp = FastMCP("alibaba-cloud-ops-mcp-server")
183
+ for tool in oos_tools.tools:
184
+ mcp.add_tool(tool)
185
+ for tool in cms_tools.tools:
186
+ mcp.add_tool(tool)
187
+ for service_code, apis in config.items():
188
+ for api_name in apis:
189
+ create_and_decorate_tool(mcp, service_code, api_name)
190
+
191
+ # Initialize and run the server
192
+ logger.debug(f'mcp server is running on {transport} mode.')
193
+ mcp.run(transport=transport)
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: alibaba-cloud-ops-mcp-server
3
+ Version: 0.7.2
4
+ Summary: A MCP server for Alibaba Cloud
5
+ Author-email: Zheng Dayu <dayu.zdy@alibaba-inc.com>
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: alibabacloud-cms20190101>=3.1.4
9
+ Requires-Dist: alibabacloud-ecs20140526>=6.1.0
10
+ Requires-Dist: alibabacloud-oos20190601>=3.4.1
11
+ Requires-Dist: click>=8.1.8
12
+ Requires-Dist: mcp[cli]>=1.6.0
13
+ Description-Content-Type: text/markdown
14
+
15
+ # alibaba-cloud-ops-mcp-server
16
+
17
+ ## Prepare
18
+
19
+ Install [uv](https://github.com/astral-sh/uv)
20
+
21
+ ```bash
22
+ # On macOS and Linux.
23
+ curl -LsSf https://astral.sh/uv/install.sh | sh
24
+ ```
25
+
26
+ ## Start
27
+
28
+ Start from local development environment
29
+
30
+ ```bash
31
+ ALIBABA_CLOUD_ACCESS_KEY_ID=<Your AccessKeyId> ALIBABA_CLOUD_ACCESS_KEY_SECRET=<Your AccessKeySecret> uv run src/alibaba_cloud_ops_mcp_server/server.py --transport sse
32
+ ```
33
+
34
+ Start from package
35
+
36
+ ```bash
37
+ ALIBABA_CLOUD_ACCESS_KEY_ID=<Your AccessKeyId> ALIBABA_CLOUD_ACCESS_KEY_SECRET=<Your AccessKeySecret> uvx alibaba-cloud-ops-mcp-server@latest --transport sse
38
+ ```
39
+
40
+ ## Debug
41
+
42
+ Use [VS Code](https://code.visualstudio.com/) + [Cline](https://cline.bot/) to config MCP Server.
43
+
44
+ ## Tools
45
+
46
+ | **Product** | **Tool** | **Function** | **Implematation** | **Status** |
47
+ | --- | --- | --- | --- | --- |
48
+ | ECS | RunCommand | Run Command | OOS | Done |
49
+ | | StartInstances | Start Instances | OOS | Done |
50
+ | | StopInstances | Stop Instances | OOS | Done |
51
+ | | RebootInstances | Reboot Instances | OOS | Done |
52
+ | | DescribeInstances | View Instances | API | Done |
53
+ | | DescribeRegions | View Regions | API | Done |
54
+ | | DescribeZones | View Zones | API | Done |
55
+ | | DescribeAvailableResource | View Resource Inventory | API | Done |
56
+ | | DescribeImages | View Images | API | Done |
57
+ | | DescribeSecurityGroups | View Security Groups | API | Done |
58
+ | | RunInstances | Create Instances | OOS | Done |
59
+ | | DeleteInstances | Delete Instances | API | Done |
60
+ | | ResetPassword | Modify Password | OOS | Done |
61
+ | | ReplaceSystemDisk | Replace Operating System | OOS | Done |
62
+ | VPC | DescribeVpcs | View VPCs | API | Done |
63
+ | | DescribeVSwitches | View VSwitches | API | Done |
64
+ | CloudMonitor | GetCpuUsageData | Get CPU Usage Data for ECS Instances | API | Done |
65
+ | | GetCpuLoadavgData | Get CPU One-Minute Average Load Metric Data | API | Done |
66
+ | | GetCpuloadavg5mData | Get CPU Five-Minute Average Load Metric Data | API | Done |
67
+ | | GetCpuloadavg15mData | Get CPU Fifteen-Minute Average Load Metric Data | API | Done |
68
+ | | GetMemUsedData | Get Memory Usage Metric Data | API | Done |
69
+ | | GetMemUsageData | Get Memory Utilization Metric Data | API | Done |
70
+ | | GetDiskUsageData | Get Disk Utilization Metric Data | API | Done |
71
+ | | GetDiskTotalData | Get Total Disk Partition Capacity Metric Data | API | Done |
72
+ | | GetDiskUsedData | Get Disk Partition Usage Metric Data | API | Done |
@@ -0,0 +1,11 @@
1
+ alibaba_cloud_ops_mcp_server/__init__.py,sha256=BaluUNyRz8Qw-X7Y0ywDezwbkqiSvWlSYn2452XeGcA,213
2
+ alibaba_cloud_ops_mcp_server/api_meta_client.py,sha256=pxJztmkmcqqI3djECziAIMc3ZxsS8crqSc6AbneOX2I,7315
3
+ alibaba_cloud_ops_mcp_server/cms_tools.py,sha256=5IhPtkHSwqLsy7D3lGznovQ94e-XBy6HBE7qLDMoYaQ,4464
4
+ alibaba_cloud_ops_mcp_server/config.py,sha256=MJRa5MLJgftSBitrbzTX8fPAV3-7_7FVxNqPvQyJiac,463
5
+ alibaba_cloud_ops_mcp_server/oos_tools.py,sha256=zXniXIPjTKYYMaP2oS9KtuSAWeLixeGhjqIMNgR4Hqg,7864
6
+ alibaba_cloud_ops_mcp_server/server.py,sha256=MCXk-nVDEuSuTO9E3duRa_r77ALz0KoJzQI94eHCZVw,6612
7
+ alibaba_cloud_ops_mcp_server-0.7.2.dist-info/METADATA,sha256=DlUj7F9mfEAuvtMF4S4n2XgEzjtpGSe28iPwXaNHaJw,2847
8
+ alibaba_cloud_ops_mcp_server-0.7.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ alibaba_cloud_ops_mcp_server-0.7.2.dist-info/entry_points.txt,sha256=ESGAWXKEp184forhs7VzTD4P1AUdZz6vCW6hRUKITGw,83
10
+ alibaba_cloud_ops_mcp_server-0.7.2.dist-info/licenses/LICENSE,sha256=gQgVkp2ttRCjodiPpXZZR-d7JnrYIYNiHk1YDUYgpa4,11331
11
+ alibaba_cloud_ops_mcp_server-0.7.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ alibaba-cloud-ops-mcp-server = alibaba_cloud_ops_mcp_server:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.