-
Notifications
You must be signed in to change notification settings - Fork 630
Expand file tree
/
Copy pathtool_service.py
More file actions
6764 lines (5970 loc) · 335 KB
/
tool_service.py
File metadata and controls
6764 lines (5970 loc) · 335 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
# -*- coding: utf-8 -*-
"""Location: ./mcpgateway/services/tool_service.py
Copyright 2025
SPDX-License-Identifier: Apache-2.0
Authors: Mihai Criveti
Tool Service Implementation.
This module implements tool management and invocation according to the MCP specification.
It handles:
- Tool registration and validation
- Tool invocation with schema validation
- Tool federation across gateways
- Event notifications for tool changes
- Active/inactive tool management
"""
# Standard
import asyncio
import base64
import binascii
from datetime import datetime, timezone
from functools import lru_cache
import json # NOTE: httpx uses stdlib json, not orjson, so response.json() raises json.JSONDecodeError
import logging
import os
import re
import ssl
import time
from types import SimpleNamespace
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union
from urllib.parse import parse_qs, urlparse
import uuid
# Third-Party
import anyio
import httpx
import jq
import jsonschema
from jsonschema import Draft4Validator, Draft6Validator, Draft7Validator, validators
from mcp import ClientSession, types
from mcp.client.sse import sse_client
from mcp.client.streamable_http import streamablehttp_client
import orjson
from pydantic import BaseModel, ValidationError
from sqlalchemy import and_, delete, desc, or_, select
from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.orm import joinedload, selectinload, Session
# First-Party
from mcpgateway.cache.global_config_cache import global_config_cache
from mcpgateway.common.models import Gateway as PydanticGateway
from mcpgateway.common.models import TextContent
from mcpgateway.common.models import Tool as PydanticTool
from mcpgateway.common.models import ToolResult
from mcpgateway.common.validators import SecurityValidator
from mcpgateway.config import settings
from mcpgateway.db import A2AAgent as DbA2AAgent
from mcpgateway.db import fresh_db_session
from mcpgateway.db import Gateway as DbGateway
from mcpgateway.db import get_for_update, server_tool_association
from mcpgateway.db import Tool as DbTool
from mcpgateway.db import ToolMetric, ToolMetricsHourly
from mcpgateway.observability import create_child_span, create_span, inject_trace_context_headers, otel_context_active, set_span_attribute, set_span_error
from mcpgateway.plugins.framework import (
GlobalContext,
HttpHeaderPayload,
PluginContextTable,
PluginError,
PluginViolationError,
ToolHookType,
ToolPostInvokePayload,
ToolPreInvokePayload,
)
from mcpgateway.plugins.framework.constants import GATEWAY_METADATA, TOOL_METADATA
from mcpgateway.schemas import AuthenticationValues, ToolCreate, ToolMetrics, ToolRead, ToolUpdate, TopPerformer
from mcpgateway.services.audit_trail_service import get_audit_trail_service
from mcpgateway.services.base_service import BaseService
from mcpgateway.services.event_service import EventService
from mcpgateway.services.logging_service import LoggingService
from mcpgateway.services.mcp_session_pool import get_mcp_session_pool, TransportType
from mcpgateway.services.metrics_buffer_service import get_metrics_buffer_service
from mcpgateway.services.metrics_cleanup_service import delete_metrics_in_batches, pause_rollup_during_purge
from mcpgateway.services.metrics_query_service import get_top_performers_combined
from mcpgateway.services.oauth_manager import OAuthManager
from mcpgateway.services.observability_service import current_trace_id, ObservabilityService
from mcpgateway.services.performance_tracker import get_performance_tracker
from mcpgateway.services.structured_logger import get_structured_logger
from mcpgateway.services.team_management_service import TeamManagementService
from mcpgateway.utils.correlation_id import get_correlation_id
from mcpgateway.utils.create_slug import slugify
from mcpgateway.utils.display_name import generate_display_name
from mcpgateway.utils.gateway_access import build_gateway_auth_headers, check_gateway_access, extract_gateway_id_from_headers
from mcpgateway.utils.metrics_common import build_top_performers
from mcpgateway.utils.pagination import decode_cursor, encode_cursor, unified_paginate
from mcpgateway.utils.passthrough_headers import compute_passthrough_headers_cached
from mcpgateway.utils.retry_manager import ResilientHttpClient
from mcpgateway.utils.services_auth import decode_auth, encode_auth
from mcpgateway.utils.sqlalchemy_modifier import json_contains_tag_expr
from mcpgateway.utils.ssl_context_cache import get_cached_ssl_context
from mcpgateway.utils.trace_context import format_trace_team_scope
from mcpgateway.utils.trace_redaction import is_input_capture_enabled, is_output_capture_enabled, serialize_trace_payload
from mcpgateway.utils.url_auth import apply_query_param_auth, sanitize_exception_message, sanitize_url_for_logging
from mcpgateway.utils.validate_signature import validate_signature
# Cache import (lazy to avoid circular dependencies)
_REGISTRY_CACHE = None
_TOOL_LOOKUP_CACHE = None
def _get_registry_cache():
"""Get registry cache singleton lazily.
Returns:
RegistryCache instance.
"""
global _REGISTRY_CACHE # pylint: disable=global-statement
if _REGISTRY_CACHE is None:
# First-Party
from mcpgateway.cache.registry_cache import registry_cache # pylint: disable=import-outside-toplevel
_REGISTRY_CACHE = registry_cache
return _REGISTRY_CACHE
def _get_tool_lookup_cache():
"""Get tool lookup cache singleton lazily.
Returns:
ToolLookupCache instance.
"""
global _TOOL_LOOKUP_CACHE # pylint: disable=global-statement
if _TOOL_LOOKUP_CACHE is None:
# First-Party
from mcpgateway.cache.tool_lookup_cache import tool_lookup_cache # pylint: disable=import-outside-toplevel
_TOOL_LOOKUP_CACHE = tool_lookup_cache
return _TOOL_LOOKUP_CACHE
# Initialize logging service first
logging_service = LoggingService()
logger = logging_service.get_logger(__name__)
# Initialize performance tracker, structured logger, audit trail, and metrics buffer for tool operations
perf_tracker = get_performance_tracker()
structured_logger = get_structured_logger("tool_service")
audit_trail = get_audit_trail_service()
metrics_buffer = get_metrics_buffer_service()
_ENCRYPTED_TOOL_HEADER_VALUE_KEY = "_mcpgateway_encrypted_header_value_v1"
_TOOL_HEADER_DATA_KEY = "data"
_TOOL_HEADER_LEGACY_VALUE_KEY = "value"
_SENSITIVE_TOOL_HEADER_PATTERNS = (
re.compile(r"^authorization$", re.IGNORECASE),
re.compile(r"^proxy-authorization$", re.IGNORECASE),
re.compile(r"^x-api-key$", re.IGNORECASE),
re.compile(r"^api-key$", re.IGNORECASE),
re.compile(r"^apikey$", re.IGNORECASE),
# Keep broad-enough auth matching while avoiding operational noise from
# non-secret tracing/idempotency headers (e.g. X-Correlation-Token).
re.compile(r"^x-(?:auth|api|access|refresh|client|bearer|session|security)[-_]?(?:token|secret|key)$", re.IGNORECASE),
re.compile(r"^(?:auth|api|access|refresh|client|bearer|session|security)[-_]?(?:token|secret|key)$", re.IGNORECASE),
# Protocol-level and credential-bearing headers that must not be set via mapping.
re.compile(r"^cookie$", re.IGNORECASE),
re.compile(r"^set-cookie$", re.IGNORECASE),
re.compile(r"^host$", re.IGNORECASE),
re.compile(r"^transfer-encoding$", re.IGNORECASE),
re.compile(r"^content-length$", re.IGNORECASE),
re.compile(r"^connection$", re.IGNORECASE),
re.compile(r"^upgrade$", re.IGNORECASE),
)
def _is_sensitive_tool_header_name(name: str) -> bool:
"""Return whether a tool header name should be treated as sensitive.
Args:
name: Header name to evaluate.
Returns:
``True`` when header value should be protected.
"""
normalized_name = str(name).strip().lower()
return any(pattern.match(normalized_name) for pattern in _SENSITIVE_TOOL_HEADER_PATTERNS)
def _is_encrypted_tool_header_value(value: Any) -> bool:
"""Return whether a header value uses encrypted envelope format.
Args:
value: Header value candidate.
Returns:
``True`` when value is an encrypted envelope mapping.
"""
return isinstance(value, dict) and isinstance(value.get(_ENCRYPTED_TOOL_HEADER_VALUE_KEY), str)
def _encrypt_tool_header_value(value: Any, existing_value: Any = None) -> Any:
"""Encrypt a single sensitive tool header value.
Args:
value: Incoming header value from payload.
existing_value: Existing stored value used for masked-value merges.
Returns:
Encrypted envelope, preserved existing value, or ``None`` when cleared.
"""
if value is None or value == "":
return value
if value == settings.masked_auth_value:
if _is_encrypted_tool_header_value(existing_value):
return existing_value
if existing_value in (None, ""):
return None
return _encrypt_tool_header_value(existing_value, None)
if _is_encrypted_tool_header_value(value):
return value
encrypted = encode_auth({_TOOL_HEADER_DATA_KEY: str(value)})
return {_ENCRYPTED_TOOL_HEADER_VALUE_KEY: encrypted}
def _protect_tool_headers_for_storage(headers: Optional[Dict[str, Any]], existing_headers: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
"""Encrypt sensitive tool header values before persistence.
Args:
headers: Incoming tool headers payload.
existing_headers: Existing stored headers used for masked-value merges.
Returns:
Header mapping with sensitive values protected for storage, or ``None``.
"""
if headers is None:
return None
if not isinstance(headers, dict):
return None
existing_by_lower: Dict[str, Any] = {}
if isinstance(existing_headers, dict):
for key, existing_value in existing_headers.items():
existing_by_lower[str(key).strip().lower()] = existing_value
protected: Dict[str, Any] = {}
for key, value in headers.items():
if _is_sensitive_tool_header_name(key):
existing_value = existing_by_lower.get(str(key).strip().lower())
protected[key] = _encrypt_tool_header_value(value, existing_value)
else:
protected[key] = value
return protected
def _decrypt_tool_header_value(value: Any) -> Any:
"""Decrypt a single tool header envelope when possible.
Args:
value: Stored header value, possibly encrypted.
Returns:
Decrypted plain value when envelope is valid, else original value.
"""
if not _is_encrypted_tool_header_value(value):
return value
encrypted_payload = value.get(_ENCRYPTED_TOOL_HEADER_VALUE_KEY)
if not encrypted_payload:
return value
try:
decoded = decode_auth(encrypted_payload)
if isinstance(decoded, dict):
if _TOOL_HEADER_DATA_KEY in decoded:
return decoded[_TOOL_HEADER_DATA_KEY]
if _TOOL_HEADER_LEGACY_VALUE_KEY in decoded:
return decoded[_TOOL_HEADER_LEGACY_VALUE_KEY]
except Exception as exc:
logger.warning("Failed to decrypt tool header value: %s", exc)
return value
def _decrypt_tool_headers_for_runtime(headers: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""Decrypt tool header map for runtime outbound requests.
Args:
headers: Stored header mapping.
Returns:
Header mapping with encrypted values decrypted where possible.
"""
if not isinstance(headers, dict):
return {}
return {key: _decrypt_tool_header_value(value) for key, value in headers.items()}
#: Top-level keys that the MCP ``CallToolResult`` envelope admits (including
#: the gateway's internal snake-case aliases). Any dict with keys outside
#: this set is treated as a business payload rather than an MCP envelope.
#: See :func:`_looks_like_mcp_envelope`.
_MCP_ENVELOPE_KEYS: frozenset[str] = frozenset(
{
"content",
"isError",
"is_error",
"structuredContent",
"structured_content",
"_meta",
"meta",
}
)
def _looks_like_mcp_envelope(payload: dict) -> bool:
"""Return ``True`` when a dict strongly resembles an MCP ``CallToolResult`` envelope.
Used by :meth:`ToolService._coerce_to_tool_result` to decide whether a
raw dict should be promoted to a ``ToolResult`` via
``ToolResult.model_validate``. The check has two layers:
1. **No unknown top-level keys.** ``ToolResult`` inherits
``BaseModelWithConfigDict``, which uses Pydantic's default
``extra="ignore"`` — any sibling field not declared on the model
is **silently dropped** at validation time. Without this first
check, a REST payload like
``{"content": [{"type": "text", "text": "ok"}], "isError": false,
"recognitionId": "rec-1"}`` would model-validate cleanly and lose
``recognitionId`` without warning (Codex-flagged regression).
So we reject any dict whose keys aren't a subset of
:data:`_MCP_ENVELOPE_KEYS`.
2. **At least one positive MCP signal.** Even when the key set is a
valid subset, we require at least one MCP-specific marker —
either ``isError``/``is_error``, ``structuredContent``/
``structured_content``, or ``content`` holding MCP ``ContentBlock``-
shaped items (dicts with a string ``type``). This stops a
minimal ``{"content": "plain text"}`` shape, which *could* be a
REST payload that coincidentally uses an allowed key name, from
being interpreted as MCP.
Both checks must pass. A REST business payload like
``{"content": [{"widget": "x"}], "id": 1}`` fails check (1) (``id`` is
not an MCP envelope key); a minimal ``{"content": "hello"}`` fails
check (2) (no positive marker); both are therefore correctly treated
as opaque JSON by the caller.
Args:
payload: The dict candidate.
Returns:
``True`` if the dict is confidently an MCP envelope and safe to
round-trip through ``ToolResult.model_validate`` without losing
sibling fields, else ``False``.
"""
keys = payload.keys()
# Layer 1: reject if there are any keys outside the envelope schema.
# This is what guards against silent field-dropping for business payloads
# that happen to include ``content`` / ``isError`` among other fields.
if not keys <= _MCP_ENVELOPE_KEYS:
return False
# Layer 2: require a positive MCP signal so we don't misclassify
# anonymous REST bodies that merely happen to use a subset of allowed keys.
if "isError" in keys or "is_error" in keys:
return True
if "structuredContent" in keys or "structured_content" in keys:
return True
content = payload.get("content")
if isinstance(content, list) and content and all(isinstance(item, dict) and isinstance(item.get("type"), str) for item in content):
return True
return False
def _safe_type_name(obj: Any) -> str:
"""Return ``type(obj).__name__``, or a sentinel if that itself raises.
Used inside :meth:`ToolService._coerce_to_tool_result`'s last-resort
fallback so logging and diagnostic text on a pathological object
(broken proxy, ``__class__`` descriptor that raises, etc.) cannot
themselves raise and escape the "always returns a valid
``ToolResult``" invariant.
"""
try:
return type(obj).__name__
except Exception: # pylint: disable=broad-except
return "<untypeable>"
def _safe_text_repr(obj: Any, fallback_type: str) -> str:
"""Coerce an arbitrary object to a non-raising text representation.
Tries ``str(obj)``, then ``repr(obj)``, then ``f"<{fallback_type}
object>"``, and finally a fixed sentinel. Used by the opaque-JSON
last-resort branch of
:meth:`ToolService._coerce_to_tool_result` — neither ``str`` nor
``repr`` is guaranteed to succeed on arbitrary Python objects (a
class can override either to raise), and without this staged
fallback a malicious or simply buggy payload could escape the
helper and break the "never raises" contract downstream code relies
on.
Args:
obj: The payload to stringify.
fallback_type: Pre-computed type name used in the third-tier
sentinel; keeps ``type().__name__`` out of this function's
hot path since it has its own :func:`_safe_type_name`
guard upstream.
Returns:
A ``str``. Never raises.
"""
try:
text = str(obj)
if isinstance(text, str):
return text
except Exception: # pylint: disable=broad-except
pass # nosec B110
try:
text = repr(obj)
if isinstance(text, str):
return text
except Exception: # pylint: disable=broad-except
pass # nosec B110
# ``fallback_type`` came from ``_safe_type_name`` so it's
# guaranteed to be a ``str`` already.
return f"<{fallback_type} object (unrepresentable)>"
def _handle_json_parse_error(response, error, is_error_response: bool = False) -> dict:
"""Handle JSON parsing failures with graceful fallback to raw text.
Args:
response: The HTTP response object with .text attribute
error: The exception that was raised during JSON parsing
is_error_response: If True, logs as "error response", else "response"
Returns:
Dictionary with response_text key containing the raw response text
(truncated to REST_RESPONSE_TEXT_MAX_LENGTH if longer to avoid exposing sensitive data),
or error details if response body is empty/None
"""
msg = "error response" if is_error_response else "response"
if not response.text:
logger.warning(f"Failed to parse JSON {msg}: {error}. Response body was empty.")
return {"error": "Empty response body"}
max_length = settings.rest_response_text_max_length
text = response.text[:max_length] if len(response.text) > max_length else response.text
if len(response.text) > max_length:
logger.warning(f"Failed to parse JSON {msg}: {error}. Response truncated from {len(response.text)} to {max_length} characters.")
else:
logger.warning(f"Failed to parse JSON {msg}: {error}")
return {"response_text": text}
@lru_cache(maxsize=256)
def _compile_jq_filter(jq_filter: str):
"""Cache compiled jq filter program.
Args:
jq_filter: The jq filter string to compile.
Returns:
Compiled jq program object.
Raises:
ValueError: If the jq filter is invalid.
"""
# pylint: disable=c-extension-no-member
return jq.compile(jq_filter)
@lru_cache(maxsize=128)
def _get_validator_class_and_check(schema_json: str) -> Tuple[type, dict]:
"""Cache schema validation and validator class selection.
This caches the expensive operations:
1. Deserializing the schema
2. Selecting the appropriate validator class based on $schema
3. Checking the schema is valid
Supports multiple JSON Schema drafts by using fallback validators when the
auto-detected validator fails. This handles schemas using older draft features
(e.g., Draft 4 style exclusiveMinimum: true) that are invalid in newer drafts.
Args:
schema_json: Canonical JSON string of the schema (used as cache key).
Returns:
Tuple of (validator_class, schema_dict) ready for instantiation.
"""
schema = orjson.loads(schema_json)
# First try auto-detection based on $schema
validator_cls = validators.validator_for(schema)
try:
validator_cls.check_schema(schema)
return validator_cls, schema
except jsonschema.exceptions.SchemaError:
pass
# Fallback: try older drafts that may accept schemas with legacy features
# (e.g., Draft 4/6 style boolean exclusiveMinimum/exclusiveMaximum)
for fallback_cls in [Draft7Validator, Draft6Validator, Draft4Validator]:
try:
fallback_cls.check_schema(schema)
return fallback_cls, schema
except jsonschema.exceptions.SchemaError:
continue
# If no validator accepts the schema, use the original and let it fail
# with a clear error message during validation
validator_cls.check_schema(schema)
return validator_cls, schema
def _canonicalize_schema(schema: dict) -> str:
"""Create a canonical JSON string of a schema for use as a cache key.
Args:
schema: The JSON Schema dictionary.
Returns:
Canonical JSON string with sorted keys.
"""
return orjson.dumps(schema, option=orjson.OPT_SORT_KEYS).decode()
def _validate_with_cached_schema(instance: Any, schema: dict) -> None:
"""Validate instance against schema using cached validator class.
Creates a fresh validator instance for thread safety, but reuses
the cached validator class and schema check. Uses best_match to
preserve jsonschema.validate() error selection semantics.
Args:
instance: The data to validate.
schema: The JSON Schema to validate against.
Raises:
error: The best matching ValidationError from jsonschema validation.
jsonschema.exceptions.ValidationError: If validation fails.
jsonschema.exceptions.SchemaError: If the schema itself is invalid.
"""
schema_json = _canonicalize_schema(schema)
validator_cls, checked_schema = _get_validator_class_and_check(schema_json)
# Create fresh validator instance for thread safety
validator = validator_cls(checked_schema)
# Use best_match to match jsonschema.validate() error selection behavior
error = jsonschema.exceptions.best_match(validator.iter_errors(instance))
if error is not None:
raise error
def extract_using_jq(data, jq_filter=""):
"""
Extracts data from a given input (string, dict, or list) using a jq filter string.
Uses cached compiled jq programs for performance.
Args:
data (str, dict, list): The input JSON data. Can be a string, dict, or list.
jq_filter (str): The jq filter string to extract the desired data.
Returns:
The result of applying the jq filter to the input data.
Examples:
>>> extract_using_jq('{"a": 1, "b": 2}', '.a')
[1]
>>> extract_using_jq({'a': 1, 'b': 2}, '.b')
[2]
>>> extract_using_jq('[{"a": 1}, {"a": 2}]', '.[].a')
[1, 2]
>>> extract_using_jq('not a json', '.a')
['Invalid JSON string provided.']
>>> extract_using_jq({'a': 1}, '')
{'a': 1}
"""
if not jq_filter or jq_filter == "":
return data
# Validate that jq_filter looks like a valid jq expression
jq_filter_str = str(jq_filter).strip()
if not jq_filter_str:
return data
# Check if it looks like an email address (common mistake when jsonpath_filter
# field contains corrupted data). Intentionally simple regex to avoid false
# positives with valid jq expressions like .foo|.bar
if re.match(r"^[^.\[\]|]+@[^.\[\]|]+\.[^.\[\]|]+$", jq_filter_str):
logger.warning(f"Invalid jq filter (email address): {jq_filter_str}. Treating as empty filter.")
return data
# Track if input was originally a string (for error handling)
was_string = isinstance(data, str)
if was_string:
# If the input is a string, parse it as JSON
try:
data = orjson.loads(data)
except orjson.JSONDecodeError:
return ["Invalid JSON string provided."]
elif not isinstance(data, (dict, list)):
# If the input is not a string, dict, or list, raise an error
return ["Input data must be a JSON string, dictionary, or list."]
# Apply the jq filter to the data using cached compiled program
try:
program = _compile_jq_filter(jq_filter)
result = program.input(data).all()
if result == [None]:
return [TextContent(type="text", text="Error applying jsonpath filter")]
except Exception as e:
message = "Error applying jsonpath filter: " + str(e)
return [TextContent(type="text", text=message)]
return result
_VALID_HTTP_HEADER_NAME = re.compile(r"^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$")
_INVALID_HEADER_VALUE_CHARS = re.compile(r"[\r\n\x00]")
def _validate_mapping_contents(mapping: dict, label: str, tool_name: str) -> dict[str, str]:
"""Validate that a mapping dict contains only string keys and string values.
Raises:
ToolInvocationError: If the mapping contains non-string keys or values.
"""
if not all(isinstance(k, str) and isinstance(v, str) for k, v in mapping.items()):
raise ToolInvocationError(f"Tool '{tool_name}' has invalid {label}: non-string keys or values. Check the tool's {label} configuration.")
return mapping
def _validate_header_mapping_targets(mapping: dict[str, str], tool_name: str) -> None:
"""Validate that header mapping target names are safe and well-formed.
Raises:
ToolInvocationError: If any target header name is sensitive or malformed.
"""
for target_header in mapping.values():
if _is_sensitive_tool_header_name(target_header):
raise ToolInvocationError(f"header_mapping for tool '{tool_name}' targets sensitive header {repr(target_header[:64])}")
if not _VALID_HTTP_HEADER_NAME.match(target_header):
raise ToolInvocationError(f"header_mapping for tool '{tool_name}' contains invalid header name {repr(target_header[:64])}")
def apply_mapping_into_target(data_obj: dict, mapping_obj: dict | None, target_obj: dict | None = None) -> dict:
"""Map fields from data_obj whose keys appear in mapping_obj, renaming them per mapping_obj's values, and merge into target_obj.
Only data_obj keys present in mapping_obj are included; unmapped keys are excluded from the result.
If mapping_obj is None or empty, returns target_obj unchanged.
If no target_obj is provided, an empty dict is used as the base.
Args:
data_obj: Source data whose keys may be mapped.
mapping_obj: Key-renaming map (old_key -> new_key), or None/empty to skip mapping.
target_obj: Base dict to merge mapped entries into. Mapped entries overwrite on collision.
Returns:
A new dict containing all entries from target_obj plus renamed entries from data_obj.
"""
if target_obj is None:
target_obj = {}
if not mapping_obj:
return target_obj
if logger.isEnabledFor(logging.DEBUG):
dropped = {k for k in data_obj if k not in mapping_obj}
if dropped:
structured_logger.log(level="DEBUG", message=f"apply_mapping_into_target: unmapped keys excluded: {sorted(dropped)}", component="tool_service")
return {**target_obj, **{mapping_obj[k]: v for k, v in data_obj.items() if k in mapping_obj}}
class ToolError(Exception):
"""Base class for tool-related errors.
Examples:
>>> from mcpgateway.services.tool_service import ToolError
>>> err = ToolError("Something went wrong")
>>> str(err)
'Something went wrong'
"""
class ToolNotFoundError(ToolError):
"""Raised when a requested tool is not found.
Examples:
>>> from mcpgateway.services.tool_service import ToolNotFoundError
>>> err = ToolNotFoundError("Tool xyz not found")
>>> str(err)
'Tool xyz not found'
>>> isinstance(err, ToolError)
True
"""
class ToolNameConflictError(ToolError):
"""Raised when a tool name conflicts with existing (active or inactive) tool."""
def __init__(self, name: str, enabled: bool = True, tool_id: Optional[int] = None, visibility: str = "public"):
"""Initialize the error with tool information.
Args:
name: The conflicting tool name.
enabled: Whether the existing tool is enabled or not.
tool_id: ID of the existing tool if available.
visibility: The visibility of the tool ("public" or "team").
Examples:
>>> from mcpgateway.services.tool_service import ToolNameConflictError
>>> err = ToolNameConflictError('test_tool', enabled=False, tool_id=123)
>>> str(err)
'Public Tool already exists with name: test_tool (currently inactive, ID: 123)'
>>> err.name
'test_tool'
>>> err.enabled
False
>>> err.tool_id
123
"""
self.name = name
self.enabled = enabled
self.tool_id = tool_id
if visibility == "team":
vis_label = "Team-level"
elif visibility == "private":
vis_label = "Private"
else:
vis_label = "Public"
message = f"{vis_label} Tool already exists with name: {name}"
if not enabled:
message += f" (currently inactive, ID: {tool_id})"
super().__init__(message)
class ToolLockConflictError(ToolError):
"""Raised when a tool row is locked by another transaction."""
class ToolValidationError(ToolError):
"""Raised when tool validation fails.
Examples:
>>> from mcpgateway.services.tool_service import ToolValidationError
>>> err = ToolValidationError("Invalid tool configuration")
>>> str(err)
'Invalid tool configuration'
>>> isinstance(err, ToolError)
True
"""
class ToolInvocationError(ToolError):
"""Raised when tool invocation fails.
Examples:
>>> from mcpgateway.services.tool_service import ToolInvocationError
>>> err = ToolInvocationError("Tool execution failed")
>>> str(err)
'Tool execution failed'
>>> isinstance(err, ToolError)
True
>>> # Test with detailed error
>>> detailed_err = ToolInvocationError("Network timeout after 30 seconds")
>>> "timeout" in str(detailed_err)
True
>>> isinstance(err, ToolError)
True
"""
class ToolTimeoutError(ToolInvocationError):
"""Raised when tool invocation times out.
This subclass is used to distinguish timeout errors from other invocation errors.
Timeout handlers call tool_post_invoke before raising this, so the generic exception
handler should skip calling post_invoke again to avoid double-counting failures.
Attributes:
retry_delay_ms: Delay in milliseconds requested by the retry plugin.
0 (default) means no retry. Set by the timeout handler after
invoking the post-invoke hook so the outer catch block can honour
the signal without calling post_invoke a second time.
"""
def __init__(self, message: str, retry_delay_ms: int = 0) -> None:
"""Initialise with an optional retry delay from the post-invoke hook.
Args:
message: Human-readable error description.
retry_delay_ms: Milliseconds the gateway should wait before retrying.
"""
super().__init__(message)
self.retry_delay_ms = retry_delay_ms
def _coerce_retry_policy_int(raw_value: Any, *, default: int, minimum: int) -> int:
"""Normalize retry policy integer settings from plugin config."""
if raw_value is None:
return default
value = int(raw_value)
if value < minimum:
raise ValueError(f"Retry policy integer must be >= {minimum}")
return value
def _coerce_retry_policy_statuses(raw_value: Any) -> List[int]:
"""Normalize retryable status codes from plugin config."""
if raw_value is None:
return [429, 500, 502, 503, 504]
if isinstance(raw_value, (str, bytes)) or not isinstance(raw_value, (list, tuple, set)):
raise ValueError("Retry policy retry_on_status must be a sequence of integers")
return [int(code) for code in raw_value]
def _coerce_retry_policy_bool(raw_value: Any, *, default: bool) -> bool:
"""Normalize retry policy booleans using explicit string parsing."""
if raw_value is None:
return default
if isinstance(raw_value, bool):
return raw_value
if isinstance(raw_value, (int, float)) and raw_value in (0, 1):
return bool(raw_value)
if isinstance(raw_value, str):
normalized = raw_value.strip().lower()
if normalized in {"1", "true", "t", "yes", "y", "on"}:
return True
if normalized in {"0", "false", "f", "no", "n", "off"}:
return False
raise ValueError("Retry policy boolean must be a bool-like value")
def _build_retry_policy_config(raw_cfg: Optional[Dict[str, Any]], tool_name: str) -> Dict[str, Any]:
"""Build a gateway-owned retry policy view from plugin config."""
cfg = raw_cfg or {}
if not isinstance(cfg, dict):
raise ValueError("Retry policy config must be a mapping")
effective_cfg: Dict[str, Any] = {
"max_retries": _coerce_retry_policy_int(cfg.get("max_retries"), default=2, minimum=0),
"backoff_base_ms": _coerce_retry_policy_int(cfg.get("backoff_base_ms"), default=200, minimum=1),
"max_backoff_ms": _coerce_retry_policy_int(cfg.get("max_backoff_ms"), default=5000, minimum=1),
"retry_on_status": _coerce_retry_policy_statuses(cfg.get("retry_on_status")),
"jitter": _coerce_retry_policy_bool(cfg.get("jitter"), default=True),
"check_text_content": _coerce_retry_policy_bool(cfg.get("check_text_content"), default=False),
}
tool_overrides = cfg.get("tool_overrides") or {}
if not isinstance(tool_overrides, dict):
raise ValueError("Retry policy tool_overrides must be a mapping")
overrides = tool_overrides.get(tool_name)
if overrides:
if not isinstance(overrides, dict):
raise ValueError("Retry policy tool override must be a mapping")
effective_cfg.update({key: value for key, value in overrides.items() if key in effective_cfg})
effective_cfg["max_retries"] = _coerce_retry_policy_int(effective_cfg.get("max_retries"), default=2, minimum=0)
effective_cfg["backoff_base_ms"] = _coerce_retry_policy_int(effective_cfg.get("backoff_base_ms"), default=200, minimum=1)
effective_cfg["max_backoff_ms"] = _coerce_retry_policy_int(effective_cfg.get("max_backoff_ms"), default=5000, minimum=1)
effective_cfg["retry_on_status"] = _coerce_retry_policy_statuses(effective_cfg.get("retry_on_status"))
effective_cfg["jitter"] = _coerce_retry_policy_bool(effective_cfg.get("jitter"), default=True)
effective_cfg["check_text_content"] = _coerce_retry_policy_bool(effective_cfg.get("check_text_content"), default=False)
effective_cfg["max_retries"] = min(effective_cfg["max_retries"], settings.max_tool_retries)
return effective_cfg
class ToolService(BaseService):
"""Service for managing and invoking tools.
Handles:
- Tool registration and deregistration.
- Tool invocation and validation.
- Tool federation.
- Event notifications.
- Active/inactive tool management.
"""
_visibility_model_cls = DbTool
def __init__(self) -> None:
"""Initialize the tool service.
Examples:
>>> from mcpgateway.services.tool_service import ToolService
>>> service = ToolService()
>>> isinstance(service._event_service, EventService)
True
>>> hasattr(service, '_http_client')
True
"""
self._event_service = EventService(channel_name="mcpgateway:tool_events")
self._http_client = ResilientHttpClient(client_args={"timeout": settings.federation_timeout, "verify": not settings.skip_ssl_verify})
self.oauth_manager = OAuthManager(
request_timeout=int(settings.oauth_request_timeout if hasattr(settings, "oauth_request_timeout") else 30),
max_retries=int(settings.oauth_max_retries if hasattr(settings, "oauth_max_retries") else 3),
)
async def initialize(self) -> None:
"""Initialize the service.
Examples:
>>> from mcpgateway.services.tool_service import ToolService
>>> service = ToolService()
>>> import asyncio
>>> asyncio.run(service.initialize()) # Should log "Initializing tool service"
"""
logger.info("Initializing tool service")
await self._event_service.initialize()
async def shutdown(self) -> None:
"""Shutdown the service.
Examples:
>>> from mcpgateway.services.tool_service import ToolService
>>> service = ToolService()
>>> import asyncio
>>> asyncio.run(service.shutdown()) # Should log "Tool service shutdown complete"
"""
await self._http_client.aclose()
await self._event_service.shutdown()
logger.info("Tool service shutdown complete")
async def get_top_tools(self, db: Session, limit: Optional[int] = 5, include_deleted: bool = False) -> List[TopPerformer]:
"""Retrieve the top-performing tools based on execution count.
Queries the database to get tools with their metrics, ordered by the number of executions
in descending order. Returns a list of TopPerformer objects containing tool details and
performance metrics. Results are cached for performance.
Args:
db (Session): Database session for querying tool metrics.
limit (Optional[int]): Maximum number of tools to return. Defaults to 5.
include_deleted (bool): Whether to include deleted tools from rollups.
Returns:
List[TopPerformer]: A list of TopPerformer objects, each containing:
- id: Tool ID.
- name: Tool name.
- execution_count: Total number of executions.
- avg_response_time: Average response time in seconds, or None if no metrics.
- success_rate: Success rate percentage, or None if no metrics.
- last_execution: Timestamp of the last execution, or None if no metrics.
"""
# Check cache first (if enabled)
# First-Party
from mcpgateway.cache.metrics_cache import is_cache_enabled, metrics_cache # pylint: disable=import-outside-toplevel
effective_limit = limit or 5
cache_key = f"top_tools:{effective_limit}:include_deleted={include_deleted}"
if is_cache_enabled():
cached = metrics_cache.get(cache_key)
if cached is not None:
return cached
# Use combined query that includes both raw metrics and rollup data
results = get_top_performers_combined(
db,
metric_type="tool",
entity_model=DbTool,
limit=effective_limit,
include_deleted=include_deleted,
)
top_performers = build_top_performers(results)
# Cache the result (if enabled)
if is_cache_enabled():
metrics_cache.set(cache_key, top_performers)
return top_performers
def _build_tool_cache_payload(self, tool: DbTool, gateway: Optional[DbGateway]) -> Dict[str, Any]:
"""Build cache payload for tool lookup by name.
Args:
tool: Tool ORM instance.
gateway: Optional gateway ORM instance.
Returns:
Cache payload dict for tool lookup.
"""
tool_payload = {
"id": str(tool.id),
"name": tool.name,
"original_name": tool.original_name,
"url": tool.url,
"description": tool.description,
"original_description": tool.original_description,
"integration_type": tool.integration_type,
"request_type": tool.request_type,
"headers": tool.headers or {},