-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmcp_server.py
More file actions
1345 lines (1156 loc) · 46 KB
/
Copy pathmcp_server.py
File metadata and controls
1345 lines (1156 loc) · 46 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
#!/usr/bin/env python3
"""
OpenAPI to MCP Server
Converts OpenAPI specifications to MCP tools and exposes them via Model Context Protocol
Supports both stdio and SSE transports
"""
import asyncio
import json
import logging
import os
import sys
import glob
from typing import Dict, Any, Optional, List
from pathlib import Path
from urllib.parse import urlparse
import httpx
from mcp.server.fastmcp import FastMCP
from dotenv import load_dotenv
# Setup logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler(), logging.FileHandler("mcp_server.log")],
)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
logger.info("Environment variables loaded")
# Initialize FastMCP server
mcp = FastMCP("openapi-to-mcp")
logger.info("FastMCP server initialized")
# Configuration
SWAGGER_FOLDER = "swagger_files"
DEFAULT_TIMEOUT = 30.0
# SSE Configuration to help with connection issues
SSE_TIMEOUT = 60.0
SSE_KEEPALIVE = 30.0
# Global storage for OpenAPI spec and tools
openapi_spec: Optional[Dict[str, Any]] = None
api_base_url: Optional[str] = None
# Global variable to store user-provided 3DSpace URL
user_3dspace_url: Optional[str] = None
def get_3dspace_url() -> str:
"""Get the user-provided 3DSpace URL"""
if user_3dspace_url is None:
raise ValueError("3DSpace URL not set. Please provide the 3DSpace URL first.")
return user_3dspace_url
def is_valid_swagger_file(file_path: str) -> bool:
"""Check if a JSON file is a valid OpenAPI/Swagger specification"""
try:
# Try UTF-8 first, then fallback to other encodings
for encoding in ["utf-8", "utf-8-sig", "latin-1", "cp1252"]:
try:
with open(file_path, "r", encoding=encoding) as f:
data = json.load(f)
break
except UnicodeDecodeError:
continue
else:
logger.debug(f"Could not decode file with any encoding: {file_path}")
return False
# Check for OpenAPI 3.x format
if "openapi" in data and isinstance(data["openapi"], str):
if data["openapi"].startswith("3."):
logger.debug(f"Valid OpenAPI 3.x file: {file_path}")
return True
# Check for Swagger 2.x format
if "swagger" in data and isinstance(data["swagger"], str):
if data["swagger"].startswith("2."):
logger.debug(f"Valid Swagger 2.x file: {file_path}")
return True
# Must have info section
if "info" not in data:
logger.debug(f"Invalid swagger file (no info section): {file_path}")
return False
# Must have paths section
if "paths" not in data:
logger.debug(f"Invalid swagger file (no paths section): {file_path}")
return False
logger.debug(f"Valid swagger file: {file_path}")
return True
except (json.JSONDecodeError, KeyError, TypeError) as e:
logger.debug(f"Invalid swagger file {file_path}: {str(e)}")
return False
def merge_swagger_specs(specs: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Merge multiple OpenAPI/Swagger specifications into a single consolidated spec"""
if not specs:
raise ValueError("No specifications to merge")
if len(specs) == 1:
return specs[0]
# Use the first spec as the base
merged_spec = specs[0].copy()
# Start with the first spec's info, but update title to indicate it's merged
merged_spec["info"] = merged_spec.get("info", {}).copy()
merged_spec["info"]["title"] = "Merged OpenAPI Specifications"
merged_spec["info"][
"description"
] = f"Consolidated from {len(specs)} OpenAPI specifications"
# Initialize paths if not present
if "paths" not in merged_spec:
merged_spec["paths"] = {}
# Merge paths from all specs
for i, spec in enumerate(specs[1:], 1):
spec_paths = spec.get("paths", {})
for path, path_item in spec_paths.items():
if path in merged_spec["paths"]:
# Path already exists, merge the operations
logger.warning(
f"Path {path} exists in multiple specs, merging operations"
)
for method, operation in path_item.items():
if method in merged_spec["paths"][path]:
# Operation already exists, add suffix to operationId to avoid conflicts
if "operationId" in operation:
operation["operationId"] = (
f"{operation['operationId']}_spec{i}"
)
logger.warning(
f"Duplicate operation {method} {path}, renamed operationId"
)
merged_spec["paths"][path][method] = operation
else:
merged_spec["paths"][path] = path_item
# Merge components/definitions if present
components_keys = [
"components",
"definitions",
"parameters",
"responses",
"securityDefinitions",
]
for key in components_keys:
if key in merged_spec:
for spec in specs[1:]:
if key in spec:
if isinstance(merged_spec[key], dict) and isinstance(
spec[key], dict
):
merged_spec[key].update(spec[key])
# Merge servers (prefer first spec's servers, but add unique ones)
all_servers = merged_spec.get("servers", [])
existing_urls = {server.get("url") for server in all_servers}
for spec in specs[1:]:
for server in spec.get("servers", []):
if server.get("url") not in existing_urls:
all_servers.append(server)
existing_urls.add(server.get("url"))
if all_servers:
merged_spec["servers"] = all_servers
logger.info(f"Successfully merged {len(specs)} OpenAPI specifications")
return merged_spec
async def load_openapi_spec() -> Dict[str, Any]:
"""Load OpenAPI specifications from swagger folder and merge them"""
global openapi_spec, api_base_url
if openapi_spec is not None:
logger.debug("OpenAPI spec already loaded, returning cached version")
return openapi_spec
try:
logger.info(f"Loading OpenAPI specifications from {SWAGGER_FOLDER}")
# Create swagger folder if it doesn't exist
swagger_folder_path = Path(SWAGGER_FOLDER)
if not swagger_folder_path.exists():
swagger_folder_path.mkdir(parents=True, exist_ok=True)
logger.info(f"Created swagger folder: {SWAGGER_FOLDER}")
# Find all JSON files in the swagger folder
json_files = glob.glob(f"{SWAGGER_FOLDER}/*.json")
logger.info(f"Found {len(json_files)} JSON files in {SWAGGER_FOLDER}")
# Filter for valid swagger files
valid_swagger_files = []
for file_path in json_files:
if is_valid_swagger_file(file_path):
valid_swagger_files.append(file_path)
logger.info(f"Valid swagger file: {file_path}")
else:
logger.warning(f"Skipping invalid swagger file: {file_path}")
if not valid_swagger_files:
logger.warning(
f"No valid OpenAPI files found in {SWAGGER_FOLDER}, creating sample spec"
)
# Create a sample OpenAPI spec if none exists
sample_spec = {
"openapi": "3.0.0",
"info": {
"title": "Sample API",
"version": "1.0.0",
"description": "A sample API for demonstration",
},
"servers": [
{
"url": "https://jsonplaceholder.typicode.com",
"description": "JSONPlaceholder - Free fake API for testing",
}
],
"paths": {
"/posts": {
"get": {
"operationId": "getPosts",
"summary": "Get all posts",
"description": "Retrieve all posts from the API",
"responses": {"200": {"description": "List of posts"}},
},
"post": {
"operationId": "createPost",
"summary": "Create a new post",
"description": "Create a new post",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"title": {"type": "string"},
"body": {"type": "string"},
"userId": {"type": "integer"},
},
}
}
},
},
},
},
"/posts/{id}": {
"get": {
"operationId": "getPostById",
"summary": "Get post by ID",
"parameters": [
{
"name": "id",
"in": "path",
"required": True,
"schema": {"type": "integer"},
}
],
}
},
"/users": {
"get": {"operationId": "getUsers", "summary": "Get all users"}
},
"/users/{id}": {
"get": {
"operationId": "getUserById",
"summary": "Get user by ID",
"parameters": [
{
"name": "id",
"in": "path",
"required": True,
"schema": {"type": "integer"},
}
],
}
},
},
}
sample_file_path = swagger_folder_path / "sample_api.json"
with open(sample_file_path, "w", encoding="utf-8") as f:
json.dump(sample_spec, f, indent=2)
logger.info(f"Created sample OpenAPI specification at {sample_file_path}")
openapi_spec = sample_spec
else:
# Load all valid swagger files
loaded_specs = []
for file_path in valid_swagger_files:
logger.info(f"Loading OpenAPI file: {file_path}")
# Try multiple encodings for loading
for encoding in ["utf-8", "utf-8-sig", "latin-1", "cp1252"]:
try:
with open(file_path, "r", encoding=encoding) as f:
spec = json.load(f)
loaded_specs.append(spec)
logger.debug(
f"Loaded spec from {file_path}: {spec.get('info', {}).get('title', 'Unknown')}"
)
break
except UnicodeDecodeError:
continue
else:
logger.error(
f"Could not decode file with any encoding: {file_path}"
)
continue
# Merge all specifications into one
if len(loaded_specs) == 1:
openapi_spec = loaded_specs[0]
logger.info(
f"Using single OpenAPI specification: {openapi_spec.get('info', {}).get('title', 'Unknown')}"
)
else:
openapi_spec = merge_swagger_specs(loaded_specs)
logger.info(
f"Merged {len(loaded_specs)} OpenAPI specifications into one"
)
# Set a placeholder base URL - actual URL will be provided by user
api_base_url = "{3DSpace}"
logger.info(f"OpenAPI spec loaded successfully")
return openapi_spec
except Exception as e:
logger.error(f"Failed to load OpenAPI specifications: {str(e)}")
raise Exception(f"Failed to load OpenAPI specifications: {str(e)}")
def get_operation_base_url(operation_path: str, operation_method: str) -> str:
"""Get the base URL for a specific operation, using user-provided 3DSpace URL"""
try:
base_url = get_3dspace_url()
logger.debug(
f"Using user-provided 3DSpace URL for {operation_method} {operation_path}: {base_url}"
)
return base_url
except ValueError:
logger.warning("3DSpace URL not set, using placeholder URL")
return "https://3dspace.mydomain.com/3dspace"
async def make_api_request(
method: str,
path: str,
headers: Optional[Dict[str, str]] = None,
params: Optional[Dict[str, Any]] = None,
query_params: Optional[Dict[str, Any]] = None,
body: Optional[Dict[str, Any]] = None,
base_url_override: Optional[str] = None,
) -> Dict[str, Any]:
"""Make HTTP request to the API"""
# Get the appropriate base URL for this operation
if base_url_override:
operation_base_url = base_url_override
logger.info(f"Using base URL override: {operation_base_url}")
else:
operation_base_url = get_operation_base_url(path, method)
# Replace path parameters
formatted_path = path
if params:
for key, value in params.items():
placeholder = "{" + key + "}"
formatted_path = formatted_path.replace(placeholder, str(value))
logger.debug(f"Formatted path with parameters: {formatted_path}")
# Construct full URL
if operation_base_url.endswith("/") and formatted_path.startswith("/"):
url = operation_base_url[:-1] + formatted_path
elif not operation_base_url.endswith("/") and not formatted_path.startswith("/"):
url = operation_base_url + "/" + formatted_path
else:
url = operation_base_url + formatted_path
# Prepare headers
request_headers = headers or {}
logger.info(f"Making {method.upper()} request to: {url}")
logger.debug(f"Headers: {request_headers}")
logger.debug(f"Query params: {query_params}")
logger.debug(f"Body: {body}")
try:
timeout = httpx.Timeout(DEFAULT_TIMEOUT)
async with httpx.AsyncClient(timeout=timeout) as client:
if method.lower() == "get":
response = await client.get(
url, headers=request_headers, params=query_params
)
elif method.lower() == "post":
response = await client.post(
url, headers=request_headers, json=body, params=query_params
)
elif method.lower() == "put":
response = await client.put(
url, headers=request_headers, json=body, params=query_params
)
elif method.lower() == "delete":
response = await client.delete(
url, headers=request_headers, params=query_params
)
elif method.lower() == "patch":
response = await client.patch(
url, headers=request_headers, json=body, params=query_params
)
else:
response = await client.request(
method.upper(),
url,
headers=request_headers,
json=body,
params=query_params,
)
logger.info(
f"API request completed: {method.upper()} {url} - Status: {response.status_code}"
)
# Handle different content types
content_type = response.headers.get("content-type", "").lower()
if "application/json" in content_type:
try:
response_body = response.json()
except:
response_body = response.text
logger.warning(
f"Failed to parse JSON response, using text: {response.text[:200]}..."
)
else:
response_body = response.text
return {
"status_code": response.status_code,
"headers": dict(response.headers),
"body": response_body,
"url": url,
"method": method.upper(),
"success": 200 <= response.status_code < 300,
}
except Exception as e:
logger.error(f"API request failed: {method.upper()} {url} - Error: {str(e)}")
return {
"error": str(e),
"status_code": 500,
"url": url,
"method": method.upper(),
"success": False,
}
@mcp.resource("openapi://spec")
def get_openapi_spec() -> str:
"""Get the loaded OpenAPI specification"""
if openapi_spec is None:
return "OpenAPI specification not loaded"
return json.dumps(
{
"info": openapi_spec.get("info", {}),
"servers": openapi_spec.get("servers", []),
"paths_count": len(openapi_spec.get("paths", {})),
"base_url": api_base_url,
},
indent=2,
)
@mcp.resource("openapi://paths")
def list_api_paths() -> str:
"""List all available API paths and methods"""
if openapi_spec is None:
return "OpenAPI specification not loaded"
paths = openapi_spec.get("paths", {})
api_paths = []
for path, methods in paths.items():
for method, details in methods.items():
if method.lower() in [
"get",
"post",
"put",
"delete",
"patch",
"head",
"options",
]:
operation_id = details.get("operationId", f"{method}_{path}")
summary = details.get("summary", f"{method.upper()} {path}")
api_paths.append(
{
"operation_id": operation_id,
"method": method.upper(),
"path": path,
"summary": summary,
}
)
return json.dumps(api_paths, indent=2)
@mcp.tool()
async def set_3dspace_url(url: str) -> str:
"""Set the 3DSpace URL that will be used for all API calls
Args:
url: The 3DSpace URL (e.g., https://3dspace.mydomain.com/3dspace)
Returns:
Confirmation message
"""
global user_3dspace_url
# Clean up the URL - remove trailing slash if present
clean_url = url.rstrip("/")
# Validate URL format
try:
parsed = urlparse(clean_url)
if not parsed.scheme or not parsed.netloc:
return json.dumps(
{
"error": "Invalid URL format. Please provide a complete URL like https://3dspace.mydomain.com/3dspace"
}
)
except Exception as e:
return json.dumps({"error": f"Invalid URL: {str(e)}"})
user_3dspace_url = clean_url
logger.info(f"3DSpace URL set to: {user_3dspace_url}")
return json.dumps(
{
"success": True,
"message": f"3DSpace URL set to: {user_3dspace_url}",
"url": user_3dspace_url,
}
)
@mcp.tool()
async def list_available_tools() -> str:
"""
List all available MCP tools with their descriptions and parameters
"""
# Load spec to ensure we have the latest operations
await load_openapi_spec()
logger.info("Listing available tools")
tools_info = {
"mcp_tools": [
{
"name": "list_available_tools",
"description": "List all available MCP tools with their descriptions",
"parameters": [],
},
{
"name": "api_request",
"description": "Make API requests using OpenAPI operation IDs",
"parameters": [
{
"name": "operation_id",
"type": "string",
"required": True,
"description": "The operation ID from OpenAPI spec",
},
{
"name": "path_params",
"type": "object",
"required": False,
"description": "Path parameters",
},
{
"name": "query_params",
"type": "object",
"required": False,
"description": "Query parameters",
},
{
"name": "headers",
"type": "object",
"required": False,
"description": "Additional headers",
},
{
"name": "body",
"type": "object",
"required": False,
"description": "Request body for POST/PUT/PATCH",
},
],
},
{
"name": "generic_api_call",
"description": "Make generic API calls to any endpoint",
"parameters": [
{
"name": "method",
"type": "string",
"required": True,
"description": "HTTP method",
},
{
"name": "path",
"type": "string",
"required": True,
"description": "API path",
},
{
"name": "path_params",
"type": "object",
"required": False,
"description": "Path parameters",
},
{
"name": "query_params",
"type": "object",
"required": False,
"description": "Query parameters",
},
{
"name": "headers",
"type": "object",
"required": False,
"description": "Headers",
},
{
"name": "body",
"type": "object",
"required": False,
"description": "Request body",
},
],
},
{
"name": "search_operations",
"description": "Search for API operations by keyword",
"parameters": [
{
"name": "query",
"type": "string",
"required": True,
"description": "Search term",
}
],
},
{
"name": "get_security_context",
"description": "Get security context information from 3DSpace and format as Role.Organization.CollabSpace strings",
"parameters": [
{
"name": "headers",
"type": "object",
"required": False,
"description": "Authentication headers (Authorization and ENO_CSRF_TOKEN required)",
}
],
},
{
"name": "get_csrf_token",
"description": "Get CSRF token from 3DSpace for PUT, PATCH, POST, or DELETE operations",
"parameters": [
{
"name": "headers",
"type": "object",
"required": False,
"description": "Authentication headers (Authorization required)",
}
],
},
],
"api_operations": [],
}
# Add available API operations
if openapi_spec:
paths = openapi_spec.get("paths", {})
for path, methods in paths.items():
for method, details in methods.items():
if method.lower() in [
"get",
"post",
"put",
"delete",
"patch",
"head",
"options",
]:
operation_id = details.get("operationId", f"{method}_{path}")
summary = details.get("summary", f"{method.upper()} {path}")
description = details.get("description", "")
tools_info["api_operations"].append(
{
"operation_id": operation_id,
"method": method.upper(),
"path": path,
"summary": summary,
"description": description,
}
)
tools_info["total_mcp_tools"] = len(tools_info["mcp_tools"])
tools_info["total_api_operations"] = len(tools_info["api_operations"])
logger.info(
f"Listed {tools_info['total_mcp_tools']} MCP tools and {tools_info['total_api_operations']} API operations"
)
return json.dumps(tools_info, indent=2)
@mcp.tool()
async def api_request(
operation_id: str,
path_params: Optional[Dict[str, Any]] = None,
query_params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
body: Optional[Dict[str, Any]] = None,
) -> str:
"""
Make an API request using operation ID from the OpenAPI specification
Args:
operation_id: The operationId from the OpenAPI spec
path_params: Path parameters for the request (e.g., {"id": "123"})
query_params: Query parameters for the request (e.g., {"limit": 10})
headers: Additional headers for the request
body: Request body for POST/PUT/PATCH requests
"""
logger.info(f"Making API request with operation ID: {operation_id}")
# Load spec if not already loaded
spec = await load_openapi_spec()
# Find the operation by operation_id
paths = spec.get("paths", {})
operation_found = False
target_path = None
target_method = None
for path, methods in paths.items():
for method, details in methods.items():
if method.lower() not in [
"get",
"post",
"put",
"delete",
"patch",
"head",
"options",
]:
continue
op_id = details.get("operationId")
if not op_id:
# Generate operation ID from method and path
clean_path = (
path.replace("/", "_")
.replace("{", "")
.replace("}", "")
.replace(":", "_")
)
op_id = f"{method}_{clean_path}"
if op_id == operation_id:
target_path = path
target_method = method
operation_found = True
logger.debug(f"Found operation: {target_method.upper()} {target_path}")
break
if operation_found:
break
if not operation_found:
available_operations = []
for path, methods in paths.items():
for method, details in methods.items():
if method.lower() in [
"get",
"post",
"put",
"delete",
"patch",
"head",
"options",
]:
op_id = details.get("operationId", f"{method}_{path}")
available_operations.append(op_id)
logger.warning(
f"Operation '{operation_id}' not found. Available operations: {available_operations[:5]}"
)
return f"Operation '{operation_id}' not found. Available operations: {', '.join(available_operations[:10])}"
# Make the API request
result = await make_api_request(
method=target_method,
path=target_path,
headers=headers,
params=path_params,
query_params=query_params,
body=body,
)
logger.info(f"API request completed for operation: {operation_id}")
return json.dumps(result, indent=2)
@mcp.tool()
async def generic_api_call(
method: str,
path: str,
path_params: Optional[Dict[str, Any]] = None,
query_params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
body: Optional[Dict[str, Any]] = None,
) -> str:
"""
Make a generic API call to any path
Args:
method: HTTP method (GET, POST, PUT, DELETE, PATCH)
path: API path (e.g., "/users/{id}")
path_params: Path parameters (e.g., {"id": "123"})
query_params: Query parameters (e.g., {"limit": 10})
headers: Additional headers
body: Request body for POST/PUT/PATCH requests
"""
logger.info(f"Making generic API call: {method.upper()} {path}")
# Ensure spec is loaded to get base URL
await load_openapi_spec()
# Validate method
if method.upper() not in [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"HEAD",
"OPTIONS",
]:
logger.error(f"Invalid HTTP method: {method}")
return f"Invalid HTTP method: {method}. Supported methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS"
# Make the API request
result = await make_api_request(
method=method,
path=path,
headers=headers,
params=path_params,
query_params=query_params,
body=body,
)
logger.info(f"Generic API call completed: {method.upper()} {path}")
return json.dumps(result, indent=2)
@mcp.tool()
async def search_operations(query: str) -> str:
"""
Search for API operations by name, path, or description
Args:
query: Search term to find matching operations
"""
logger.info(f"Searching operations with query: '{query}'")
# Load spec if not already loaded
spec = await load_openapi_spec()
paths = spec.get("paths", {})
matching_operations = []
for path, methods in paths.items():
for method, details in methods.items():
if method.lower() not in [
"get",
"post",
"put",
"delete",
"patch",
"head",
"options",
]:
continue
operation_id = details.get("operationId", f"{method}_{path}")
summary = details.get("summary", "")
description = details.get("description", "")
# Search in operation_id, path, summary, and description
search_text = f"{operation_id} {path} {summary} {description}".lower()
if query.lower() in search_text:
matching_operations.append(
{
"operation_id": operation_id,
"method": method.upper(),
"path": path,
"summary": summary,
"description": description,
}
)
logger.info(f"Found {len(matching_operations)} operations matching '{query}'")
if not matching_operations:
logger.warning(f"No operations found matching '{query}'")
return f"No operations found matching '{query}'"
return json.dumps(matching_operations, indent=2)
@mcp.tool()
async def get_security_context(
headers: Optional[Dict[str, str]] = None,
) -> str:
"""
Get security context information from 3DSpace and format it as Role.Organization.CollabSpace strings
Args:
headers: Authentication headers (Authorization and ENO_CSRF_TOKEN required)
Returns:
JSON response with formatted security context array and original collabspaces data
"""
logger.info("Getting security context from 3DSpace")
# Ensure spec is loaded to get base URL
await load_openapi_spec()
if not headers:
logger.warning("Security context request failed: Missing headers")
return json.dumps(
{
"error": "Headers required. Please provide Authorization and ENO_CSRF_TOKEN headers.",
"success": False,
},
indent=2,
)
logger.debug(
f"Making security context request with headers: {list(headers.keys())}"
)
# Use user-provided 3DSpace URL for security context requests
try:
security_base_url = get_3dspace_url()
logger.debug(
f"Using user-provided 3DSpace URL for security context request: {security_base_url}"
)
except ValueError as e:
return json.dumps(
{
"error": str(e),
"success": False,
},
indent=2,
)
# Make the API request to get user's collaborative spaces
result = await make_api_request(
method="GET",
path="/resources/modeler/pno/person",
headers=headers,
query_params={"current": True, "select": "collabspaces"},
base_url_override=security_base_url,
)