-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
341 lines (311 loc) · 12.9 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
from mcp.server.fastmcp import FastMCP
from tools import (
search_assets,
get_assets_by_dsl,
traverse_lineage,
update_assets,
UpdatableAttribute,
CertificateStatus,
UpdatableAsset,
)
from pyatlan.model.fields.atlan_fields import AtlanField
from typing import Optional, Dict, Any, List, Union, Type
from pyatlan.model.assets import Asset
from pyatlan.model.lineage import LineageDirection
mcp = FastMCP("Atlan MCP", dependencies=["pyatlan"])
@mcp.tool()
def search_assets_tool(
conditions: Optional[Union[Dict[str, Any], str]] = None,
negative_conditions: Optional[Dict[str, Any]] = None,
some_conditions: Optional[Dict[str, Any]] = None,
min_somes: int = 1,
include_attributes: Optional[List[Union[str, AtlanField]]] = None,
asset_type: Optional[Union[Type[Asset], str]] = None,
include_archived: bool = False,
limit: int = 10,
offset: int = 0,
sort_by: Optional[str] = None,
sort_order: str = "ASC",
connection_qualified_name: Optional[str] = None,
tags: Optional[List[str]] = None,
directly_tagged: bool = True,
domain_guids: Optional[List[str]] = None,
date_range: Optional[Dict[str, Dict[str, Any]]] = None,
):
"""
Advanced asset search using FluentSearch with flexible conditions.
Args:
conditions (Dict[str, Any], optional): Dictionary of attribute conditions to match.
Format: {"attribute_name": value} or {"attribute_name": {"operator": operator, "value": value}}
negative_conditions (Dict[str, Any], optional): Dictionary of attribute conditions to exclude.
Format: {"attribute_name": value} or {"attribute_name": {"operator": operator, "value": value}}
some_conditions (Dict[str, Any], optional): Conditions for where_some() queries that require min_somes of them to match.
Format: {"attribute_name": value} or {"attribute_name": {"operator": operator, "value": value}}
min_somes (int): Minimum number of some_conditions that must match. Defaults to 1.
include_attributes (List[Union[str, AtlanField]], optional): List of specific attributes to include in results.
Can be string attribute names or AtlanField objects.
asset_type (Union[Type[Asset], str], optional): Type of asset to search for.
Either a class (e.g., Table, Column) or a string type name (e.g., "Table", "Column")
include_archived (bool): Whether to include archived assets. Defaults to False.
limit (int, optional): Maximum number of results to return. Defaults to 10.
offset (int, optional): Offset for pagination. Defaults to 0.
sort_by (str, optional): Attribute to sort by. Defaults to None.
sort_order (str, optional): Sort order, "ASC" or "DESC". Defaults to "ASC".
connection_qualified_name (str, optional): Connection qualified name to filter by.
tags (List[str], optional): List of tags to filter by.
directly_tagged (bool): Whether to filter for directly tagged assets only. Defaults to True.
domain_guids (List[str], optional): List of domain GUIDs to filter by.
date_range (Dict[str, Dict[str, Any]], optional): Date range filters.
Format: {"attribute_name": {"gte": start_timestamp, "lte": end_timestamp}}
Returns:
List[Asset]: List of assets matching the search criteria
Raises:
Exception: If there's an error executing the search
Examples:
# Search for verified tables
tables = search_assets(
asset_type="Table",
conditions={"certificate_status": CertificateStatus.VERIFIED.value}
)
# Search for assets missing descriptions
missing_desc = search_assets(
negative_conditions={
"description": "has_any_value",
"user_description": "has_any_value"
},
include_attributes=["owner_users", "owner_groups"]
)
# Search for columns with specific certificate status
columns = search_assets(
asset_type="Column",
some_conditions={
"certificate_status": [CertificateStatus.DRAFT.value, CertificateStatus.VERIFIED.value]
},
tags=["PRD"],
conditions={"created_by": "username"},
date_range={"create_time": {"gte": 1641034800000, "lte": 1672570800000}}
)
# Search for assets with a specific search text
assets = search_assets(
conditions = {
"name": {
"operator": "match",
"value": "search_text"
},
"description": {
"operator": "match",
"value": "search_text"
}
}
)
"""
return search_assets(
conditions,
negative_conditions,
some_conditions,
min_somes,
include_attributes,
asset_type,
include_archived,
limit,
offset,
sort_by,
sort_order,
connection_qualified_name,
tags,
directly_tagged,
domain_guids,
date_range,
)
@mcp.tool()
def get_assets_by_dsl_tool(dsl_query: Union[str, Dict[str, Any]]):
"""
Execute the search with the given query
dsl_query : Union[str, Dict[str, Any]] (required):
The DSL query used to search the index.
Example:
dsl_query = '''{
"query": {
"function_score": {
"boost_mode": "sum",
"functions": [
{"filter": {"match": {"starredBy": "john.doe"}}, "weight": 10},
{"filter": {"match": {"certificateStatus": "VERIFIED"}}, "weight": 15},
{"filter": {"match": {"certificateStatus": "DRAFT"}}, "weight": 10},
{"filter": {"bool": {"must_not": [{"exists": {"field": "certificateStatus"}}]}}, "weight": 8},
{"filter": {"bool": {"must_not": [{"terms": {"__typeName.keyword": ["Process", "DbtProcess"]}}]}}, "weight": 20}
],
"query": {
"bool": {
"filter": [
{
"bool": {
"minimum_should_match": 1,
"must": [
{"bool": {"should": [{"terms": {"certificateStatus": ["VERIFIED"]}}]}},
{"term": {"__state": "ACTIVE"}}
],
"must_not": [
{"term": {"isPartial": "true"}},
{"terms": {"__typeName.keyword": ["Procedure", "DbtColumnProcess", "BIProcess", "MatillionComponent", "SnowflakeTag", "DbtTag", "BigqueryTag", "AIApplication", "AIModel"]}},
{"terms": {"__typeName.keyword": ["MCIncident", "AnomaloCheck"]}}
],
"should": [
{"terms": {"__typeName.keyword": ["Query", "Collection", "AtlasGlossary", "AtlasGlossaryCategory", "AtlasGlossaryTerm", "Connection", "File"]}},
]
}
}
]
},
"score_mode": "sum"
},
"score_mode": "sum"
}
},
"post_filter": {
"bool": {
"filter": [
{
"bool": {
"must": [{"terms": {"__typeName.keyword": ["Table", "Column"]}}],
"must_not": [{"exists": {"field": "termType"}}]
}
}
]
},
"sort": [
{"_score": {"order": "desc"}},
{"popularityScore": {"order": "desc"}},
{"starredCount": {"order": "desc"}},
{"name.keyword": {"order": "asc"}}
],
"track_total_hits": true,
"size": 10,
"include_meta": false
}'''
response = get_assets_by_dsl(dsl_query)
"""
return get_assets_by_dsl(dsl_query)
@mcp.tool()
def traverse_lineage_tool(
guid: str,
direction: str,
depth: int = 1000000,
size: int = 10,
immediate_neighbors: bool = True,
):
"""
Traverse asset lineage in specified direction.
Args:
guid (str): GUID of the starting asset
direction (str): Direction to traverse ("UPSTREAM" or "DOWNSTREAM")
depth (int, optional): Maximum depth to traverse. Defaults to 1000000.
size (int, optional): Maximum number of results to return. Defaults to 10.
immediate_neighbors (bool, optional): Only return immediate neighbors. Defaults to True.
Returns:
Dict[str, Any]: Dictionary containing:
- assets: List of assets in the lineage
- references: List of dictionaries containing:
- source_guid: GUID of the source asset
- target_guid: GUID of the target asset
- direction: Direction of the reference (upstream/downstream)
Example:
# Get lineage with specific depth and size
lineage = traverse_lineage_tool(
guid="asset-guid-here",
direction="DOWNSTREAM",
depth=1000000,
size=10
)
# Access assets and their references
for asset in lineage["assets"]:
print(f"Asset: {asset.guid}")
for ref in lineage["references"]:
print(f"Reference: {ref['source_guid']} -> {ref['target_guid']}")
"""
try:
direction_enum = LineageDirection[direction.upper()]
except KeyError:
raise ValueError(
f"Invalid direction: {direction}. Must be either 'UPSTREAM' or 'DOWNSTREAM'"
)
return traverse_lineage(
guid=guid,
direction=direction_enum,
depth=depth,
size=size,
immediate_neighbors=immediate_neighbors,
)
@mcp.tool()
def update_assets_tool(
assets: Union[Dict[str, Any], List[Dict[str, Any]]],
attribute_name: str,
attribute_values: List[str],
):
"""
Update one or multiple assets with different values for the same attribute.
Args:
assets (Union[Dict[str, Any], List[Dict[str, Any]]]): Asset(s) to update.
Can be a single UpdatableAsset or a list of UpdatableAsset objects.
attribute_name (str): Name of the attribute to update.
Only "user_description" and "certificate_status" are supported.
attribute_values (List[str]): List of values to set for the attribute.
For certificateStatus, only "VERIFIED", "DRAFT", or "DEPRECATED" are allowed.
Returns:
Dict[str, Any]: Dictionary containing:
- updated_count: Number of assets successfully updated
- errors: List of any errors encountered
Examples:
# Update certificate status for a single asset
result = update_assets_tool(
assets={
"guid": "asset-guid-here",
"name": "Asset Name",
"type_name": "Asset Type Name",
"qualified_name": "Asset Qualified Name"
},
attribute_name="certificate_status",
attribute_values=["VERIFIED"]
)
# Update user description for multiple assets
result = update_assets_tool(
assets=[
{
"guid": "asset-guid-1",
"name": "Asset Name 1",
"type_name": "Asset Type Name 1",
"qualified_name": "Asset Qualified Name 1"
},
{
"guid": "asset-guid-2",
"name": "Asset Name 2",
"type_name": "Asset Type Name 2",
"qualified_name": "Asset Qualified Name 2"
}
],
attribute_name="user_description",
attribute_values=[
"New description for asset 1", "New description for asset 2"
]
)
"""
try:
# Convert string attribute name to enum
attr_enum = UpdatableAttribute(attribute_name)
# For certificate status, validate and convert values to enum
if attr_enum == UpdatableAttribute.CERTIFICATE_STATUS:
attribute_values = [CertificateStatus(val) for val in attribute_values]
# Convert assets to UpdatableAsset objects
if isinstance(assets, dict):
updatable_assets = [UpdatableAsset(**assets)]
elif isinstance(assets, list):
updatable_assets = [UpdatableAsset(**asset) for asset in assets]
else:
raise ValueError("Assets must be a dictionary or a list of dictionaries")
return update_assets(
updatable_assets=updatable_assets,
attribute_name=attr_enum,
attribute_values=attribute_values,
)
except ValueError as e:
return {"updated_count": 0, "errors": [str(e)]}