-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
3967 lines (3444 loc) · 166 KB
/
server.py
File metadata and controls
3967 lines (3444 loc) · 166 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# server.py
import os
from typing import Any, Dict, Optional
import httpx
from mcp.server.fastmcp.server import FastMCP, Context
from dotenv import load_dotenv
import asyncio
from datetime import datetime, timedelta
import json
import urllib.parse
import logging
import hashlib
import base64
# Load environment variables FIRST
load_dotenv()
# Configure logging system BEFORE importing any other modules
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
LOG_FILE = os.getenv("LOG_FILE", "omada_mcp_server.log")
# Convert to absolute path if relative path provided
if not os.path.isabs(LOG_FILE):
# Use the directory where this script is located
script_dir = os.path.dirname(os.path.abspath(__file__))
LOG_FILE = os.path.join(script_dir, LOG_FILE)
# Create logs directory if it doesn't exist
log_dir = os.path.dirname(LOG_FILE)
if log_dir and not os.path.exists(log_dir):
os.makedirs(log_dir)
# Configure logging with both file and console handlers
logging.basicConfig(
level=getattr(logging, LOG_LEVEL, logging.INFO),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(LOG_FILE, encoding='utf-8'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Configure cache logger - it will use root logger's handlers via propagation
cache_logger = logging.getLogger('cache')
cache_logger.setLevel(getattr(logging, LOG_LEVEL, logging.INFO))
# Don't add handlers, let it propagate to root logger
cache_logger.propagate = True
logger.info(f"Logging initialized. Writing logs to: {os.path.abspath(LOG_FILE)}")
logger.info(f"Cache logger will use root logger handlers (level: {LOG_LEVEL})")
# NOW import modules that create loggers - logging is already configured
from helpers import validate_required_fields, build_error_response, build_success_response, build_pagination_clause, json_to_graphql_syntax
from cache import OmadaCache
from cache_config import get_ttl_for_operation, should_cache, DEFAULT_TTL
logger.info("All modules imported successfully")
# Configure optimized HTTP client with HTTP/2 support and connection pooling
# This client is reused across all requests for better performance
http_client = httpx.AsyncClient(
http2=True, # Enable HTTP/2 multiplexing for concurrent requests
timeout=httpx.Timeout(30.0, connect=10.0), # 30s total, 10s connect timeout
limits=httpx.Limits(
max_keepalive_connections=20, # Reuse up to 20 connections
max_connections=100, # Support up to 100 concurrent requests
keepalive_expiry=300.0 # Keep connections alive for 5 minutes
),
headers={
"User-Agent": "Omada-MCP-Server/1.0",
},
)
logger.info("HTTP client configured with HTTP/2 support and connection pooling")
def get_function_log_level(function_name: str) -> int:
"""
Get the log level for a specific function, falling back to global LOG_LEVEL.
Args:
function_name: Name of the function to get log level for
Returns:
logging level constant (e.g., logging.DEBUG, logging.INFO)
"""
# Try function-specific log level first
func_log_level = os.getenv(f"LOG_LEVEL_{function_name}", "").upper()
# If not set, use global LOG_LEVEL
if not func_log_level:
func_log_level = LOG_LEVEL
# Convert string to logging level, default to INFO if invalid
return getattr(logging, func_log_level, logging.INFO)
def set_function_logger_level(function_name: str) -> tuple:
"""
Set the logger level for a specific function and return the old levels.
Args:
function_name: Name of the function
Returns:
Tuple of (old_logger_level, old_handler_levels) for restoration
"""
old_level = logger.level
new_level = get_function_log_level(function_name)
# Save old handler levels before changing them
old_handler_levels = [(handler, handler.level) for handler in logger.handlers]
# Set logger level
logger.setLevel(new_level)
# IMPORTANT: Also set handler levels so they don't filter out DEBUG messages
# Handlers have their own level filter separate from the logger level
for handler in logger.handlers:
handler.setLevel(new_level)
# Log the level change if it's different (only at DEBUG level to avoid noise)
if old_level != new_level and new_level <= logging.DEBUG:
logger.debug(f"Function '{function_name}' using log level: {logging.getLevelName(new_level)}")
return (old_level, old_handler_levels)
def with_function_logging(func):
"""
Decorator to automatically set function-specific logging level.
Usage:
@with_function_logging
@mcp.tool()
async def my_function():
pass
"""
if asyncio.iscoroutinefunction(func):
async def async_wrapper(*args, **kwargs):
old_level, old_handler_levels = set_function_logger_level(func.__name__)
# Log function entrance at INFO level
logger.info(f"ENTERING function: {func.__name__}")
try:
result = await func(*args, **kwargs)
# Log function exit at INFO level
logger.info(f"EXITING function: {func.__name__}")
return result
except Exception as e:
# Log function exit with error at INFO level
logger.info(f"EXITING function: {func.__name__} with error: {type(e).__name__}")
raise
finally:
# Restore logger level
logger.setLevel(old_level)
# Restore handler levels
for handler, level in old_handler_levels:
handler.setLevel(level)
# Manually preserve metadata without setting __wrapped__ (which causes FastMCP to bypass decorator)
async_wrapper.__name__ = func.__name__
async_wrapper.__doc__ = func.__doc__
async_wrapper.__module__ = func.__module__
async_wrapper.__qualname__ = func.__qualname__
async_wrapper.__annotations__ = func.__annotations__
# Also update __dict__ as functools.wraps does
async_wrapper.__dict__.update(func.__dict__)
return async_wrapper
else:
def sync_wrapper(*args, **kwargs):
old_level, old_handler_levels = set_function_logger_level(func.__name__)
# Log function entrance at INFO level
logger.info(f"ENTERING function: {func.__name__}")
try:
result = func(*args, **kwargs)
# Log function exit at INFO level
logger.info(f"EXITING function: {func.__name__}")
return result
except Exception as e:
# Log function exit with error at INFO level
logger.info(f"EXITING function: {func.__name__} with error: {type(e).__name__}")
raise
finally:
# Restore logger level
logger.setLevel(old_level)
# Restore handler levels
for handler, level in old_handler_levels:
handler.setLevel(level)
# Manually preserve metadata without setting __wrapped__ (which causes FastMCP to bypass decorator)
sync_wrapper.__name__ = func.__name__
sync_wrapper.__doc__ = func.__doc__
sync_wrapper.__module__ = func.__module__
sync_wrapper.__qualname__ = func.__qualname__
sync_wrapper.__annotations__ = func.__annotations__
# Also update __dict__ as functools.wraps does
sync_wrapper.__dict__.update(func.__dict__)
return sync_wrapper
# Custom Exception Classes
class OmadaServerError(Exception):
"""Base exception for Omada server errors"""
def __init__(self, message: str, status_code: int = None, response_body: str = None):
self.status_code = status_code
self.response_body = response_body
super().__init__(message)
class AuthenticationError(OmadaServerError):
"""Raised when authentication fails"""
pass
class ODataQueryError(OmadaServerError):
"""Raised when OData query is malformed or fails"""
pass
mcp = FastMCP("OmadaIdentityMCP")
# Initialize caching system
CACHE_ENABLED = os.getenv("CACHE_ENABLED", "true").lower() == "true"
CACHE_TTL_SECONDS = int(os.getenv("CACHE_TTL_SECONDS", str(DEFAULT_TTL)))
CACHE_AUTO_CLEANUP = os.getenv("CACHE_AUTO_CLEANUP", "true").lower() == "true"
if CACHE_ENABLED:
cache = OmadaCache(default_ttl=CACHE_TTL_SECONDS, auto_cleanup=CACHE_AUTO_CLEANUP)
logger.info(f"✅ Cache system ENABLED (TTL: {CACHE_TTL_SECONDS}s, Auto-cleanup: {CACHE_AUTO_CLEANUP})")
else:
cache = None
logger.info("⚠️ Cache system DISABLED")
# Register MCP Prompts for workflow guidance
from prompts import register_prompts
register_prompts(mcp)
# Register MCP Completions for autocomplete suggestions
from completions import register_completions
register_completions(mcp)
def _get_omada_base_url(omada_base_url: str = None) -> str:
"""
Get Omada base URL from parameter or environment variable.
Args:
omada_base_url: Optional base URL parameter
Returns:
Base URL with trailing slash removed
Raises:
Exception if base URL not found in parameter or environment
"""
if not omada_base_url:
omada_base_url = os.getenv("OMADA_BASE_URL")
if not omada_base_url:
raise Exception("OMADA_BASE_URL not found in environment variables or parameters")
return omada_base_url.rstrip('/')
def _build_odata_filter(field_name: str, value: str, operator: str) -> str:
"""
Build an OData filter expression based on the operator.
Args:
field_name: The field name (e.g., "FIRSTNAME", "LASTNAME")
value: The value to filter by
operator: The OData operator (eq, ne, contains, startswith, etc.)
Returns:
OData filter expression string
"""
# Escape single quotes in value
escaped_value = value.replace("'", "''")
if operator in ["eq", "ne", "gt", "ge", "lt", "le", "like"]:
# Standard comparison operators (including LIKE)
return f"{field_name} {operator} '{escaped_value}'"
elif operator == "contains":
# Contains function
return f"contains({field_name}, '{escaped_value}')"
elif operator == "startswith":
# Starts with function
return f"startswith({field_name}, '{escaped_value}')"
elif operator == "endswith":
# Ends with function
return f"endswith({field_name}, '{escaped_value}')"
elif operator == "substringof":
# Substring of function (reverse of contains)
return f"substringof('{escaped_value}', {field_name})"
else:
# Fallback to eq if unknown operator
return f"{field_name} eq '{escaped_value}'"
def _summarize_entities(data: dict, entity_type: str) -> dict:
"""
Create a summarized version of entity data with only key fields.
Args:
data: The full OData response
entity_type: Type of entity being summarized
Returns:
Summarized data with key fields only
"""
if not data or "value" not in data:
return data
# Define key fields for each entity type
summary_fields = {
"Identity": ["Id", "UId", "DISPLAYNAME", "FIRSTNAME", "LASTNAME", "EMAIL", "EMPLOYEEID", "DEPARTMENT", "STATUS"],
"Resource": ["Id", "DISPLAYNAME", "DESCRIPTION", "RESOURCEKEY", "STATUS", "Systemref"],
"Role": ["Id", "DISPLAYNAME", "DESCRIPTION", "STATUS"],
"Account": ["Id", "ACCOUNTNAME", "DISPLAYNAME", "STATUS", "SYSTEM"],
"Application": ["Id", "DISPLAYNAME", "DESCRIPTION", "STATUS"],
"System": ["Id", "DISPLAYNAME", "DESCRIPTION", "STATUS"],
"CalculatedAssignments": ["Id", "AssignmentKey", "AccountName", "Identity", "Resource"],
"AssignmentPolicy": ["Id", "DISPLAYNAME", "DESCRIPTION", "STATUS"]
}
# Get relevant fields for this entity type
fields_to_keep = summary_fields.get(entity_type, ["Id", "DISPLAYNAME", "DESCRIPTION"])
summarized_entities = []
for entity in data.get("value", []):
summary = {}
for field in fields_to_keep:
if field in entity:
value = entity[field]
# Truncate long text fields
if isinstance(value, str) and len(value) > 100:
summary[field] = value[:97] + "..."
else:
summary[field] = value
# Always include Id if available
if "Id" in entity and "Id" not in summary:
summary["Id"] = entity["Id"]
summarized_entities.append(summary)
# Return summarized data with same structure
result = data.copy()
result["value"] = summarized_entities
return result
def _summarize_graphql_data(data: list, data_type: str) -> list:
"""
Create a summarized version of GraphQL response data with only key fields.
Args:
data: List of GraphQL response objects
data_type: Type of data being summarized (e.g., "PendingApproval", "AccessRequest")
Returns:
Summarized data with key fields only
"""
if not data or not isinstance(data, list):
return data
# Define key fields for each GraphQL data type
# Fields listed here are ONLY fields that will be returned
summary_fields = {
"PendingApproval": ["workflowStep", "workflowStepTitle", "reason", "resourceAssignment"],
"AccessRequest": ["id", "beneficiary", "resource", "status"],
"CalculatedAssignment": ["complianceStatus", "account", "resource", "identity"],
"Context": ["id", "displayName", "type"],
"Resource": ["id", "name", "description", "system"]
}
# Define fields to explicitly exclude (technical fields users shouldn't see)
exclude_fields = {
"PendingApproval": ["surveyId", "surveyObjectKey", "history"],
"AccessRequest": [],
"CalculatedAssignment": [],
"Context": [],
"Resource": []
}
# Get relevant fields for this data type
fields_to_keep = summary_fields.get(data_type, ["id", "name"])
fields_to_exclude = exclude_fields.get(data_type, [])
summarized = []
for item in data:
summary = {}
# Only include explicitly allowed fields
for field in fields_to_keep:
if field in item:
value = item[field]
# Truncate long text fields
if isinstance(value, str) and len(value) > 100:
summary[field] = value[:97] + "..."
else:
summary[field] = value
# Don't auto-add id field for PendingApproval type
# For other types, include id if available and not already in summary
if data_type != "PendingApproval":
if "id" in item and "id" not in summary and "id" not in fields_to_exclude:
summary["id"] = item["id"]
summarized.append(summary)
return summarized
@with_function_logging
@mcp.tool()
async def query_omada_entity(entity_type: str = "Identity",
filters: dict = None,
count_only: bool = False,
summary_mode: bool = True,
top: int = None,
skip: int = None,
select_fields: str = None,
order_by: str = None,
expand: str = None,
include_count: bool = False,
bearer_token: str = None,
impersonate_user: str = None) -> str:
"""
Generic query function for any Omada entity type (Identity, Resource, Role, etc).
IMPORTANT - Key Identity Field Names (use EXACTLY as shown - all UPPERCASE):
Core Fields:
- EMAIL (not "email", "MAIL", or "EMAILADDRESS")
- FIRSTNAME (not "firstname" or "first_name")
- LASTNAME (not "lastname" or "last_name")
- DISPLAYNAME (not "displayname" or "display_name")
- IDENTITYID (the user's login ID, not "identity_id")
- EMPLOYEEID (not "employee_id" or "EmployeeId")
- JOBTITLE (not "job_title" or "JobTitle")
- DEPARTMENT (not "department")
- COMPANY (not "company")
- STATUS (not "status")
Reference Fields (for expanding related data):
- JOBTITLE_REF (expands to full job title object with Id, DisplayName, etc.)
- COMPANY_REF (expands to full company/organization object)
- MANAGER_REF (expands to manager identity details)
- DEPARTMENT_REF (expands to full department object)
Other Important Fields:
- UId (32-character GUID - use for identity_id in GraphQL functions)
- Id (integer database ID - rarely used)
- LOCATION (physical location/office)
- COSTCENTER (cost center code)
- TITLE (may be different from JOBTITLE in some configurations)
Example: Querying with field and expanding reference:
select_fields="FIRSTNAME,LASTNAME,EMAIL,JOBTITLE,IDENTITYID,UId"
expand="JOBTITLE_REF,COMPANY_REF,MANAGER_REF"
Args:
entity_type: Type of entity to query (Identity, Resource, Role, Account, etc)
filters: Dictionary containing filter criteria:
{
"field_filters": [{"field": "EMAIL", "value": "user@domain.com", "operator": "eq"}],
"resource_type_id": 1011066, # For Resource entities
"resource_type_name": "APPLICATION_ROLES", # Alternative to resource_type_id
"system_id": 1011066, # For Resource entities
"identity_id": 1006500, # For CalculatedAssignments entities
"custom_filter": "FIRSTNAME eq 'John' and LASTNAME eq 'Doe'" # Custom OData filter
}
count_only: If True, returns only the count of matching records
summary_mode: If True, returns only key fields as a summary instead of full objects
top: Maximum number of records to return (OData $top)
skip: Number of records to skip (OData $skip)
select_fields: Comma-separated list of fields to select (OData $select)
order_by: Field(s) to order by (OData $orderby)
expand: Comma-separated list of related entities to expand (OData $expand)
include_count: Include total count in response (adds $count=true)
bearer_token: Optional bearer token to use instead of acquiring a new one
impersonate_user: Optional email address for user impersonation (required for user-delegated tokens)
Examples:
# Query by email (IMPORTANT: field name is "EMAIL" not "email" or "MAIL")
await query_omada_entity("Identity", filters={
"field_filters": [{"field": "EMAIL", "value": "user@domain.com", "operator": "eq"}]
})
# Query by first name
await query_omada_entity("Identity", filters={
"field_filters": [{"field": "FIRSTNAME", "value": "John", "operator": "eq"}]
})
# Resource filtering
await query_omada_entity("Resource", filters={
"resource_type_id": 123,
"system_id": 456
})
# Multiple filters combined
await query_omada_entity("Identity", filters={
"field_filters": [{"field": "DEPARTMENT", "value": "IT", "operator": "eq"}],
"custom_filter": "STATUS eq 'ACTIVE'"
})
# CalculatedAssignments for specific identity
await query_omada_entity("CalculatedAssignments", filters={
"identity_id": 1006500
})
# Count only with custom filter
await query_omada_entity("Identity",
filters={"custom_filter": "DEPARTMENT eq 'Engineering'"},
count_only=True
)
Returns:
JSON response with entity data, count, or error message
"""
try:
# Validate entity type
valid_entities = ["Identity", "Resource", "Role", "Account", "Application", "System", "CalculatedAssignments", "AssignmentPolicy"]
if entity_type not in valid_entities:
return f"❌ Invalid entity type '{entity_type}'. Valid types: {', '.join(valid_entities)}"
# Get base URL using helper function (reads from environment)
try:
omada_base_url = _get_omada_base_url()
except Exception as e:
return f"❌ {str(e)}"
# Build the endpoint URL based on entity type
if entity_type == "CalculatedAssignments":
endpoint_url = f"{omada_base_url}/OData/BuiltIn/{entity_type}"
else:
endpoint_url = f"{omada_base_url}/OData/DataObjects/{entity_type}"
# Build query parameters
query_params = {}
# Initialize filters dictionary if not provided
if filters is None:
filters = {}
# Extract filter components from the filters dictionary
field_filters = filters.get("field_filters", [])
resource_type_id = filters.get("resource_type_id")
resource_type_name = filters.get("resource_type_name")
system_id = filters.get("system_id")
identity_id = filters.get("identity_id")
custom_filter = filters.get("custom_filter")
# Handle entity-specific filtering logic
auto_filters = []
# For Resource entities, handle resource_type and system filtering
if entity_type == "Resource":
if resource_type_name and not resource_type_id:
env_key = f"RESOURCE_TYPE_{resource_type_name.upper()}"
resource_type_id = os.getenv(env_key)
if not resource_type_id:
return f"❌ Resource type '{resource_type_name}' not found in environment variables. Check {env_key}"
resource_type_id = int(resource_type_id)
if resource_type_id:
auto_filters.append(f"Systemref/Id eq {resource_type_id}")
# Add system_id filter for querying resources by system (only if not already filtered by resource_type_id)
if system_id and not resource_type_id:
auto_filters.append(f"Systemref/Id eq {system_id}")
# Handle generic field filtering for any entity type
if field_filters:
for field_filter in field_filters:
if isinstance(field_filter, dict) and "field" in field_filter and "value" in field_filter:
field_name = field_filter["field"]
field_value = field_filter["value"]
field_operator = field_filter.get("operator", "eq")
auto_filters.append(_build_odata_filter(field_name, field_value, field_operator))
# For CalculatedAssignments entities, handle identity_id filtering
if entity_type == "CalculatedAssignments":
if identity_id:
auto_filters.append(f"Identity/Id eq {identity_id}")
# Combine automatic filters with custom filter condition
all_filters = []
if auto_filters:
all_filters.extend(auto_filters)
if custom_filter:
all_filters.append(f"({custom_filter})")
if all_filters:
query_params['$filter'] = " and ".join(all_filters)
# Add count parameter if requested
if count_only:
query_params['$count'] = 'true'
query_params['$top'] = '0' # Don't return actual records, just count
else:
# Add other OData parameters
if top:
query_params['$top'] = str(top)
if skip:
query_params['$skip'] = str(skip)
if select_fields:
query_params['$select'] = select_fields
if order_by:
query_params['$orderby'] = order_by
if expand:
query_params['$expand'] = expand
if include_count:
query_params['$count'] = 'true'
# Construct final URL with query parameters
if query_params:
query_string = urllib.parse.urlencode(query_params)
endpoint_url = f"{endpoint_url}?{query_string}"
# Bearer token is always required (OAuth functions migrated to oauth_mcp_server)
if bearer_token:
logger.debug("Using provided bearer token for OData request")
# Strip "Bearer " prefix if already present to avoid double-prefix
clean_token = bearer_token.replace("Bearer ", "").replace("bearer ", "").strip()
auth_header = f"Bearer {clean_token}"
logger.debug(f"Token length: {len(clean_token)} characters")
logger.debug(f"Full bearer_token parameter: {bearer_token}")
logger.debug(f"Clean token (after strip): {clean_token}")
logger.debug(f"Full Authorization header: {auth_header}")
else:
# OAuth token functions have been migrated to oauth_mcp_server
# bearer_token is now mandatory for all authentication methods
raise Exception(
"bearer_token parameter is required.\n"
"OAuth token functions have been migrated to oauth_mcp_server.\n\n"
"Workflow:\n"
"1. Use oauth_mcp_server to obtain a bearer token:\n"
" - For Device Code flow: 'start device authentication' then 'complete device authentication'\n"
" - For Client Credentials: use oauth_mcp_server's token acquisition functions\n"
"2. Pass the token to this function using bearer_token parameter\n\n"
"Example: bearer_token='eyJ0eXAiOiJKV1QiLCJhbGc...'"
)
# Make API call to Omada
headers = {
"Authorization": auth_header,
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
# Add impersonate_user header if provided (required for user-delegated tokens like device code)
if impersonate_user:
headers["impersonate_user"] = impersonate_user
logger.debug(f"Using impersonate_user: {impersonate_user}")
response = await http_client.get(endpoint_url, headers=headers, timeout=30.0)
if response.status_code == 200:
# Parse the response
data = response.json()
if count_only:
# Return just the count
count = data.get("@odata.count", len(data.get("value", [])))
return build_success_response(
data=None,
endpoint=endpoint_url,
entity_type=entity_type,
count=count,
filter=query_params.get('$filter', 'none')
)
else:
# Return full data with metadata
entities_found = len(data.get("value", []))
total_count = data.get("@odata.count") # Available if $count=true was included
# Apply summarization if requested
response_data = data
if summary_mode:
response_data = _summarize_entities(data, entity_type)
# Build response with entity-specific metadata
extra_fields = {
"entity_type": entity_type,
"entities_returned": entities_found,
"total_count": total_count,
"filter": query_params.get('$filter', 'none'),
"summary_mode": summary_mode
}
# Add entity-specific metadata
if entity_type == "Resource" and resource_type_id:
extra_fields["resource_type_id"] = resource_type_id
return build_success_response(
data=response_data,
endpoint=endpoint_url,
**extra_fields
)
elif response.status_code == 400:
raise ODataQueryError(f"Bad request - invalid OData query: {response.text[:200]}", response.status_code)
elif response.status_code == 401:
raise AuthenticationError("Authentication failed - token may be expired", response.status_code)
elif response.status_code == 403:
raise AuthenticationError("Access forbidden - insufficient permissions", response.status_code)
elif response.status_code == 404:
raise OmadaServerError("Omada endpoint not found - check base URL", response.status_code)
elif response.status_code >= 500:
raise OmadaServerError(f"Omada server error: {response.status_code}", response.status_code, response.text)
else:
raise OmadaServerError(f"Unexpected response: {response.status_code}", response.status_code, response.text)
except AuthenticationError as e:
return build_error_response(
error_type="AuthenticationError",
message=str(e)
)
except ODataQueryError as e:
return build_error_response(
error_type="ODataQueryError",
message=str(e)
)
except OmadaServerError as e:
return build_error_response(
error_type="OmadaServerError",
message=str(e)
)
except httpx.RequestError as e:
return build_error_response(
error_type="NetworkError",
message=str(e)
)
except Exception as e:
return build_error_response(
error_type=type(e).__name__,
message=str(e)
)
@with_function_logging
@mcp.tool()
async def query_omada_identity(field_filters: list = None,
filter_condition: str = None,
count_only: bool = False,
summary_mode: bool = True,
top: int = None,
skip: int = None,
select_fields: str = None,
order_by: str = None,
include_count: bool = False,
bearer_token: str = None) -> str:
"""
Query Omada Identity entities (wrapper for query_omada_entity).
IMPORTANT LLM INSTRUCTIONS - UId Field Handling:
When summary_mode=True (default), the response includes the UId field:
1. DO NOT display the "UId" field to the user in your responses
2. ONLY show user-friendly fields: DISPLAYNAME, FIRSTNAME, LASTNAME, EMAIL, EMPLOYEEID, DEPARTMENT, STATUS
3. INTERNALLY store/remember the "UId" value for each identity
4. When the user selects an identity by name/email, USE the corresponding "UId" value
for any subsequent API calls that require an identity_id or identity_ids parameter
5. The "UId" is a 32-character GUID (e.g., "2c68e1df-1335-4e8c-8ef9-eff1d2005629") required
by GraphQL functions but not useful for end users to see
Example user presentation:
"Found identity: Robert Wolf (ROBWOL@domain.com)
Department: Finance, Employee ID: EMP12345"
But internally remember:
- Robert Wolf: UId="2c68e1df-1335-4e8c-8ef9-eff1d2005629"
When user says "Get assignments for Robert Wolf", use UId="2c68e1df-1335-4e8c-8ef9-eff1d2005629"
in the identity_ids parameter.
IMPORTANT - Identity Field Names (use EXACTLY as shown):
- EMAIL (not "email", "MAIL", or "EMAILADDRESS")
- FIRSTNAME (not "firstname" or "first_name")
- LASTNAME (not "lastname" or "last_name")
- DISPLAYNAME, EMPLOYEEID, DEPARTMENT, STATUS
Args:
field_filters: List of field filters:
[{"field": "EMAIL", "value": "user@domain.com", "operator": "eq"},
{"field": "FIRSTNAME", "value": "Emma", "operator": "eq"},
{"field": "LASTNAME", "value": "Taylor", "operator": "startswith"}]
filter_condition: Custom OData filter condition
count_only: If True, returns only the count
top: Maximum number of records to return
skip: Number of records to skip
select_fields: Comma-separated list of fields to select
order_by: Field(s) to order by
include_count: Include total count in response
bearer_token: Optional bearer token to use instead of acquiring a new one
summary_mode: If True (default), returns only key fields including UId (use UId internally, don't display to user)
Returns:
JSON response with identity data including:
- UId: 32-character GUID (for internal use in subsequent API calls - don't display to user)
- DISPLAYNAME, FIRSTNAME, LASTNAME, EMAIL: User-friendly display fields
- EMPLOYEEID, DEPARTMENT, STATUS: Additional identity attributes
"""
# Build filters dictionary for clean API
filters = {}
if field_filters:
filters["field_filters"] = field_filters
if filter_condition:
filters["custom_filter"] = filter_condition
return await query_omada_entity(
entity_type="Identity",
filters=filters if filters else None,
count_only=count_only,
summary_mode=summary_mode,
top=top,
skip=skip,
select_fields=select_fields,
order_by=order_by,
include_count=include_count,
bearer_token=bearer_token
)
@with_function_logging
@mcp.tool()
async def query_omada_resources(resource_type_id: int = None,
resource_type_name: str = None,
system_id: int = None,
filter_condition: str = None,
count_only: bool = False,
top: int = None,
skip: int = None,
select_fields: str = None,
order_by: str = None,
include_count: bool = False,
bearer_token: str = None) -> str:
"""
Query Omada Resource entities using OData API (for ADMINISTRATIVE queries only).
WARNING: DO NOT USE THIS for access request workflows!
- This function does NOT scope resources to user permissions
- This does NOT show what a user can request
- For access requests, use get_requestable_resources or get_resources_for_beneficiary instead
USE THIS FUNCTION for:
- Administrative resource queries
- Bulk resource reports
- System-level resource inventory
- Resource type analysis
Query Omada Resource entities (wrapper for query_omada_entity).
Args:
resource_type_id: Numeric ID for resource type (e.g., 1011066 for Application Roles)
resource_type_name: Name-based lookup for resource type (e.g., "APPLICATION_ROLES")
system_id: Numeric ID for system reference to filter resources by system (e.g., 1011066)
filter_condition: Custom OData filter condition
count_only: If True, returns only the count
top: Maximum number of records to return
skip: Number of records to skip
select_fields: Comma-separated list of fields to select
order_by: Field(s) to order by
include_count: Include total count in response
bearer_token: Optional bearer token to use instead of acquiring a new one
Returns:
JSON response with resource data or error message
"""
# Build filters dictionary for clean API
filters = {}
if resource_type_id:
filters["resource_type_id"] = resource_type_id
if resource_type_name:
filters["resource_type_name"] = resource_type_name
if system_id:
filters["system_id"] = system_id
if filter_condition:
filters["custom_filter"] = filter_condition
return await query_omada_entity(
entity_type="Resource",
filters=filters if filters else None,
count_only=count_only,
top=top,
skip=skip,
select_fields=select_fields,
order_by=order_by,
include_count=include_count,
bearer_token=bearer_token
)
@with_function_logging
@mcp.tool()
async def query_omada_entities(entity_type: str = "Identity",
field_filters: list = None,
filter_condition: str = None,
count_only: bool = False,
top: int = None,
skip: int = None,
select_fields: str = None,
order_by: str = None,
expand: str = None,
include_count: bool = False,
bearer_token: str = None) -> str:
"""
Modern generic query function for Omada entities using field filters.
Args:
entity_type: Type of entity to query (Identity, Resource, System, etc)
field_filters: List of field filters:
[{"field": "FIRSTNAME", "value": "Emma", "operator": "eq"},
{"field": "LASTNAME", "value": "Taylor", "operator": "startswith"}]
filter_condition: Custom OData filter condition
count_only: If True, returns only the count
top: Maximum number of records to return
skip: Number of records to skip
select_fields: Comma-separated list of fields to select
order_by: Field(s) to order by
expand: Comma-separated list of related entities to expand
include_count: Include total count in response
bearer_token: Optional bearer token to use instead of acquiring a new one
Returns:
JSON response with entity data or error message
"""
# Build filters dictionary for clean API
filters = {}
if field_filters:
filters["field_filters"] = field_filters
if filter_condition:
filters["custom_filter"] = filter_condition
return await query_omada_entity(
entity_type=entity_type,
filters=filters if filters else None,
count_only=count_only,
top=top,
skip=skip,
select_fields=select_fields,
order_by=order_by,
expand=expand,
include_count=include_count,
bearer_token=bearer_token
)
@with_function_logging
@mcp.tool()
async def query_calculated_assignments(identity_id: int = None,
select_fields: str = "AssignmentKey,AccountName",
expand: str = "Identity,Resource,ResourceType",
filter_condition: str = None,
top: int = None,
skip: int = None,
order_by: str = None,
include_count: bool = False,
bearer_token: str = None) -> str:
"""
Query Omada CalculatedAssignments entities (wrapper for query_omada_entity).
IMPORTANT LLM INSTRUCTIONS:
DO NOT USE THIS TOOL for compliance-related queries!
For compliance queries like:
- "Show compliance issues for {person}"
- "What compliance violations does {person} have?"
- "Check compliance status for {person}"
USE INSTEAD:
- get_calculated_assignments_summary() for quick compliance overview
- get_calculated_assignments_detailed() for detailed compliance info with violations
This OData tool does NOT return compliance status or violation information.
Use the GraphQL tools above which have complianceStatus and violations fields.
Args:
identity_id: Numeric ID for identity to get assignments for (e.g., 1006500)
select_fields: Fields to select (default: "AssignmentKey,AccountName")
expand: Related entities to expand (default: "Identity,Resource,ResourceType")
filter_condition: Custom OData filter condition
top: Maximum number of records to return
skip: Number of records to skip
order_by: Field(s) to order by
include_count: Include total count in response
bearer_token: Optional bearer token to use instead of acquiring a new one
Returns:
JSON response with calculated assignments data or error message
"""
# Build filters dictionary for clean API
filters = {}
if identity_id:
filters["identity_id"] = identity_id
if filter_condition:
filters["custom_filter"] = filter_condition
return await query_omada_entity(
entity_type="CalculatedAssignments",
filters=filters if filters else None,
top=top,
skip=skip,
select_fields=select_fields,
order_by=order_by,
expand=expand,
include_count=include_count,
bearer_token=bearer_token
)
@with_function_logging
@mcp.tool()
async def get_all_omada_identities(top: int = 1000,
skip: int = None,
select_fields: str = None,