-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.py
More file actions
1463 lines (1152 loc) · 50.9 KB
/
config.py
File metadata and controls
1463 lines (1152 loc) · 50.9 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
"""
Reading settings from environment variables and providing a settings object
for the application configuration.
"""
import sys
from httpx import URL
from io import StringIO
from pathlib import Path
from typing import Any, Dict, Iterable, List, Literal, Optional, Set, Union
from datetime import timedelta
import threading
import warnings
from pydantic import (
AliasChoices,
AnyHttpUrl,
BaseModel,
ConfigDict,
Field,
field_validator,
model_validator,
)
from pydantic_settings import BaseSettings, SettingsConfigDict
import yaml
from mcp_agent.agents.agent_spec import AgentSpec
class MCPAuthorizationServerSettings(BaseModel):
"""Configuration for exposing the MCP Agent server as an OAuth protected resource."""
enabled: bool = False
"""Whether to expose this MCP app as an OAuth-protected resource server."""
issuer_url: AnyHttpUrl | None = None
"""Issuer URL advertised to clients (must resolve to provider metadata)."""
resource_server_url: AnyHttpUrl | None = None
"""Base URL of the protected resource (used for discovery and validation)."""
service_documentation_url: AnyHttpUrl | None = None
"""Optional URL pointing to resource server documentation for clients."""
required_scopes: List[str] = Field(default_factory=list)
"""Scopes that clients must present when accessing this resource."""
jwks_uri: AnyHttpUrl | None = None
"""Optional JWKS endpoint for validating JWT access tokens."""
client_id: str | None = None
"""Client id to use when calling the introspection endpoint."""
client_secret: str | None = None
"""Client secret to use when calling the introspection endpoint."""
token_cache_ttl_seconds: int = Field(300, ge=0)
"""How long (in seconds) to cache positive introspection/JWT validation results."""
# RFC 9068 audience validation settings
# TODO: this should really depend on the app_id, or config_id so that we can enforce unique values.
# To be removed and replaced with a fixed value once we have app_id/config_id support
expected_audiences: List[str] = Field(default_factory=list)
"""List of audience values this resource server accepts.
MUST be configured to comply with RFC 9068 audience validation.
Audience validation is always enforced when authorization is enabled."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
@model_validator(mode="after")
def _validate_required_urls(self) -> "MCPAuthorizationServerSettings":
if self.enabled:
missing = []
if self.issuer_url is None:
missing.append("issuer_url")
if self.resource_server_url is None:
missing.append("resource_server_url")
# Validate audience configuration for RFC 9068 compliance
if not self.expected_audiences:
missing.append("expected_audiences (required for RFC 9068 compliance)")
if missing:
raise ValueError(
" | ".join(missing) + " must be set when authorization is enabled"
)
return self
class MCPOAuthClientSettings(BaseModel):
"""Configuration for authenticating to downstream OAuth-protected MCP servers."""
enabled: bool = False
"""Whether OAuth auth is enabled for this downstream server."""
scopes: List[str] = Field(default_factory=list)
"""OAuth scopes to request when authorizing."""
resource: AnyHttpUrl | None = None
"""Protected resource identifier to include in token/authorize requests (RFC 8707)."""
authorization_server: AnyHttpUrl | None = None
"""Authorization server base URL (provider metadata is discovered from this root)."""
client_id: str | None = None
"""OAuth client identifier registered with the authorization server."""
client_secret: str | None = None
"""OAuth client secret for confidential clients."""
# Support for pre-configured access tokens (bypasses OAuth flow)
access_token: str | None = None
"""Optional pre-seeded access token that bypasses the interactive flow."""
refresh_token: str | None = None
"""Optional refresh token stored alongside a pre-seeded access token."""
expires_at: float | None = None
"""Epoch timestamp (seconds) when the pre-seeded token expires."""
token_type: str = "Bearer"
"""Token type returned by the provider; defaults to Bearer."""
redirect_uri_options: List[str] = Field(default_factory=list)
"""Allowed redirect URI values; the flow selects from this list."""
extra_authorize_params: Dict[str, str] = Field(default_factory=dict)
"""Additional query parameters to append to the authorize request."""
extra_token_params: Dict[str, str] = Field(default_factory=dict)
"""Additional form parameters to append to the token request."""
require_pkce: bool = True
"""Whether to enforce PKCE when initiating the authorization code flow."""
use_internal_callback: bool = True
"""When true, attempt to use the app's internal callback URL before loopback."""
include_resource_parameter: bool = True
"""Whether to include the RFC 8707 `resource` parameter in authorize/token requests."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class OAuthTokenStoreSettings(BaseModel):
"""Settings for OAuth token persistence."""
backend: Literal["memory", "redis"] = "memory"
"""Persistence backend to use for storing tokens."""
redis_url: str | None = None
"""Connection URL for Redis when using the redis backend."""
redis_prefix: str = "mcp_agent:oauth_tokens"
"""Key prefix used when writing tokens to Redis."""
refresh_leeway_seconds: int = Field(60, ge=0)
"""Seconds before expiry when tokens should be refreshed."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class OAuthSettings(BaseModel):
"""Global OAuth-related settings for MCP Agent."""
token_store: OAuthTokenStoreSettings = Field(
default_factory=OAuthTokenStoreSettings
)
"""Token storage configuration shared across downstream servers."""
flow_timeout_seconds: int = Field(300, ge=30)
"""Maximum number of seconds to wait for an authorization callback before timing out."""
callback_base_url: AnyHttpUrl | None = None
"""Base URL for internal callbacks (used when `use_internal_callback` is true)."""
# Fixed loopback ports to try (client-only OAuth). If empty, loopback is disabled.
loopback_ports: list[int] = Field(default_factory=lambda: [33418, 33419, 33420])
"""Ports to use for local loopback callbacks when internal callbacks are unavailable."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class MCPServerAuthSettings(BaseModel):
"""Represents authentication configuration for a server."""
api_key: str | None = None
oauth: MCPOAuthClientSettings | None = None
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class MCPRootSettings(BaseModel):
"""Represents a root directory configuration for an MCP server."""
uri: str
"""The URI identifying the root. Must start with file://"""
name: Optional[str] = None
"""Optional name for the root."""
server_uri_alias: Optional[str] = None
"""Optional URI alias for presentation to the server"""
@field_validator("uri", "server_uri_alias")
@classmethod
def validate_uri(cls, v: str) -> str:
"""Validate that the URI starts with file:// (required by specification 2024-11-05)"""
if not v.startswith("file://"):
raise ValueError("Root URI must start with file://")
return v
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class MCPServerSettings(BaseModel):
"""
Represents the configuration for an individual server.
"""
# TODO: saqadri - server name should be something a server can provide itself during initialization
name: str | None = None
"""The name of the server."""
# TODO: saqadri - server description should be something a server can provide itself during initialization
description: str | None = None
"""The description of the server."""
transport: Literal["stdio", "sse", "streamable_http", "websocket"] = "stdio"
"""The transport mechanism."""
command: str | None = None
"""The command to execute the server (e.g. npx) in stdio mode."""
args: List[str] = Field(default_factory=list)
"""The arguments for the server command in stdio mode."""
cwd: str | None = None
"""The working directory to use when spawning the server process in stdio mode."""
url: str | None = None
"""The URL for the server for SSE, Streamble HTTP or websocket transport."""
headers: Dict[str, str] | None = None
"""HTTP headers for SSE or Streamable HTTP requests."""
http_timeout_seconds: int | None = None
"""
HTTP request timeout in seconds for SSE or Streamable HTTP requests.
Note: This is different from read_timeout_seconds, which
determines how long (in seconds) the client will wait for a new
event before disconnecting
"""
read_timeout_seconds: int | None = None
"""
Timeout in seconds the client will wait for a new event before
disconnecting from an SSE or Streamable HTTP server connection.
"""
terminate_on_close: bool = True
"""
For Streamable HTTP transport, whether to terminate the session on connection close.
"""
auth: MCPServerAuthSettings | None = None
"""The authentication configuration for the server."""
roots: List[MCPRootSettings] | None = None
"""Root directories this server has access to."""
env: Dict[str, str] | None = None
"""Environment variables to pass to the server process."""
allowed_tools: Set[str] | None = None
"""
Set of tool names to allow from this server. If specified, only these tools will be exposed to agents.
Tool names should match exactly.
Note: Empty list will result in the agent having no access to tools.
"""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class MCPSettings(BaseModel):
"""Configuration for all MCP servers."""
servers: Dict[str, MCPServerSettings] = Field(default_factory=dict)
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
@field_validator("servers", mode="before")
def none_to_dict(cls, v):
return {} if v is None else v
class VertexAIMixin(BaseModel):
"""Common fields for Vertex AI-compatible settings."""
project: str | None = Field(
default=None,
validation_alias=AliasChoices("project", "PROJECT_ID", "GOOGLE_CLOUD_PROJECT"),
)
location: str | None = Field(
default=None,
validation_alias=AliasChoices(
"location", "LOCATION", "CLOUD_LOCATION", "GOOGLE_CLOUD_LOCATION"
),
)
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class BedrockMixin(BaseModel):
"""Common fields for Bedrock-compatible settings."""
aws_access_key_id: str | None = Field(
default=None,
validation_alias=AliasChoices("aws_access_key_id", "AWS_ACCESS_KEY_ID"),
)
aws_secret_access_key: str | None = Field(
default=None,
validation_alias=AliasChoices("aws_secret_access_key", "AWS_SECRET_ACCESS_KEY"),
)
aws_session_token: str | None = Field(
default=None,
validation_alias=AliasChoices("aws_session_token", "AWS_SESSION_TOKEN"),
)
aws_region: str | None = Field(
default=None,
validation_alias=AliasChoices("aws_region", "AWS_REGION"),
)
profile: str | None = Field(
default=None,
validation_alias=AliasChoices("profile", "AWS_PROFILE"),
)
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class BedrockSettings(BaseSettings, BedrockMixin):
"""
Settings for using Bedrock models in the MCP Agent application.
"""
model_config = SettingsConfigDict(
env_prefix="",
extra="allow",
arbitrary_types_allowed=True,
env_file=".env",
env_file_encoding="utf-8",
)
class AnthropicSettings(BaseSettings, VertexAIMixin, BedrockMixin):
"""
Settings for using Anthropic models in the MCP Agent application.
"""
api_key: str | None = Field(
default=None,
validation_alias=AliasChoices(
"api_key", "ANTHROPIC_API_KEY", "anthropic__api_key"
),
)
default_model: str | None = Field(
default=None,
validation_alias=AliasChoices(
"default_model", "ANTHROPIC_DEFAULT_MODEL", "anthropic__default_model"
),
)
provider: Literal["anthropic", "bedrock", "vertexai"] = Field(
default="anthropic",
validation_alias=AliasChoices(
"provider", "ANTHROPIC_PROVIDER", "anthropic__provider"
),
)
base_url: str | URL | None = Field(default=None)
model_config = SettingsConfigDict(
env_prefix="ANTHROPIC_",
extra="allow",
arbitrary_types_allowed=True,
env_file=".env",
env_file_encoding="utf-8",
)
class CohereSettings(BaseSettings):
"""
Settings for using Cohere models in the MCP Agent application.
"""
api_key: str | None = Field(
default=None,
validation_alias=AliasChoices("api_key", "COHERE_API_KEY", "cohere__api_key"),
)
model_config = SettingsConfigDict(
env_prefix="COHERE_",
extra="allow",
arbitrary_types_allowed=True,
env_file=".env",
env_file_encoding="utf-8",
)
class OpenAISettings(BaseSettings):
"""
Settings for using OpenAI models in the MCP Agent application.
"""
api_key: str | None = Field(
default=None,
validation_alias=AliasChoices("api_key", "OPENAI_API_KEY", "openai__api_key"),
)
reasoning_effort: Literal["low", "medium", "high"] = Field(
default="medium",
validation_alias=AliasChoices(
"reasoning_effort", "OPENAI_REASONING_EFFORT", "openai__reasoning_effort"
),
)
base_url: str | None = Field(
default=None,
validation_alias=AliasChoices(
"base_url", "OPENAI_BASE_URL", "openai__base_url"
),
)
user: str | None = Field(
default=None,
validation_alias=AliasChoices("user", "openai__user"),
)
default_headers: Dict[str, str] | None = None
default_model: str | None = Field(
default=None,
validation_alias=AliasChoices(
"default_model", "OPENAI_DEFAULT_MODEL", "openai__default_model"
),
)
# NOTE: An http_client can be programmatically specified
# and will be used by the OpenAI client. However, since it is
# not a JSON-serializable object, it cannot be set via configuration.
# http_client: Client | None = None
model_config = SettingsConfigDict(
env_prefix="OPENAI_",
extra="allow",
arbitrary_types_allowed=True,
env_file=".env",
env_file_encoding="utf-8",
)
class AzureSettings(BaseSettings):
"""
Settings for using Azure models in the MCP Agent application.
"""
api_key: str | None = Field(
default=None,
validation_alias=AliasChoices(
"api_key", "AZURE_OPENAI_API_KEY", "AZURE_AI_API_KEY", "azure__api_key"
),
)
endpoint: str | None = Field(
default=None,
validation_alias=AliasChoices(
"endpoint", "AZURE_OPENAI_ENDPOINT", "AZURE_AI_ENDPOINT", "azure__endpoint"
),
)
api_version: str | None = Field(
default=None,
validation_alias=AliasChoices(
"api_version",
"AZURE_OPENAI_API_VERSION",
"AZURE_AI_API_VERSION",
"azure__api_version",
),
)
"""API version for AzureOpenAI client (e.g., '2025-04-01-preview')"""
azure_deployment: str | None = Field(
default=None,
validation_alias=AliasChoices(
"azure_deployment",
"AZURE_OPENAI_DEPLOYMENT",
"AZURE_AI_DEPLOYMENT",
"azure__azure_deployment",
),
)
"""Azure deployment name (optional, defaults to model name if not specified)"""
azure_ad_token: str | None = Field(
default=None,
validation_alias=AliasChoices(
"azure_ad_token",
"AZURE_AD_TOKEN",
"AZURE_AI_AD_TOKEN",
"azure__azure_ad_token",
),
)
"""Azure AD token for Entra ID authentication"""
azure_ad_token_provider: Any | None = Field(
default=None,
validation_alias=AliasChoices(
"azure_ad_token_provider",
"AZURE_AD_TOKEN_PROVIDER",
"AZURE_AI_AD_TOKEN_PROVIDER",
),
)
"""Azure AD token provider for dynamic token generation"""
credential_scopes: List[str] | None = Field(
default=["https://cognitiveservices.azure.com/.default"]
)
default_model: str | None = Field(
default=None,
validation_alias=AliasChoices(
"default_model", "AZURE_OPENAI_DEFAULT_MODEL", "azure__default_model"
),
)
model_config = SettingsConfigDict(
env_prefix="AZURE_",
extra="allow",
arbitrary_types_allowed=True,
env_file=".env",
env_file_encoding="utf-8",
)
class GoogleSettings(BaseSettings, VertexAIMixin):
"""
Settings for using Google models in the MCP Agent application.
"""
api_key: str | None = Field(
default=None,
validation_alias=AliasChoices(
"api_key", "GOOGLE_API_KEY", "GEMINI_API_KEY", "google__api_key"
),
)
vertexai: bool = Field(
default=False,
validation_alias=AliasChoices(
"vertexai", "GOOGLE_VERTEXAI", "google__vertexai"
),
)
default_model: str | None = Field(
default=None,
validation_alias=AliasChoices(
"default_model", "GOOGLE_DEFAULT_MODEL", "google__default_model"
),
)
model_config = SettingsConfigDict(
env_prefix="GOOGLE_",
extra="allow",
arbitrary_types_allowed=True,
env_file=".env",
env_file_encoding="utf-8",
)
class VertexAISettings(BaseSettings, VertexAIMixin):
"""Standalone Vertex AI settings (for future use)."""
model_config = SettingsConfigDict(
env_prefix="VERTEXAI_",
extra="allow",
arbitrary_types_allowed=True,
env_file=".env",
env_file_encoding="utf-8",
)
class SubagentSettings(BaseModel):
"""
Settings for discovering and loading project/user subagents (AgentSpec files).
Supports common formats like Claude Code subagents.
"""
enabled: bool = True
"""Enable automatic subagent discovery and loading."""
search_paths: List[str] = Field(
default_factory=lambda: [
".claude/agents",
"~/.claude/agents",
".mcp-agent/agents",
"~/.mcp-agent/agents",
]
)
"""Ordered list of directories to scan. Earlier entries take precedence on name conflicts (project before user)."""
pattern: str = "**/*.*"
"""Glob pattern within each directory to match files (YAML/JSON/Markdown supported)."""
definitions: List[AgentSpec] = Field(default_factory=list)
"""Inline AgentSpec definitions directly in config."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class TemporalSettings(BaseModel):
"""
Temporal settings for the MCP Agent application.
"""
host: str
namespace: str = "default"
api_key: str | None = None
tls: bool = False
task_queue: str
max_concurrent_activities: int | None = None
timeout_seconds: int | None = 60
rpc_metadata: Dict[str, str] | None = None
id_reuse_policy: Literal[
"allow_duplicate",
"allow_duplicate_failed_only",
"reject_duplicate",
"terminate_if_running",
] = "allow_duplicate"
workflow_task_modules: List[str] = Field(default_factory=list)
"""Additional module paths to import before creating a Temporal worker. Each should be importable."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class WorkflowTaskRetryPolicy(BaseModel):
"""
Declarative retry policy for workflow tasks / activities (mirrors Temporal RetryPolicy fields).
Durations can be specified either as seconds (number) or ISO8601 timedelta strings; both are
coerced to datetime.timedelta instances.
"""
maximum_attempts: int | None = None
initial_interval: timedelta | float | str | None = None
backoff_coefficient: float | None = None
maximum_interval: timedelta | float | str | None = None
non_retryable_error_types: List[str] | None = None
model_config = ConfigDict(extra="forbid")
@field_validator("initial_interval", "maximum_interval", mode="before")
@classmethod
def _coerce_interval(cls, value):
if value is None:
return None
if isinstance(value, timedelta):
return value
if isinstance(value, (int, float)):
return timedelta(seconds=value)
if isinstance(value, str):
try:
seconds = float(value)
return timedelta(seconds=seconds)
except Exception:
raise TypeError(
"Retry interval strings must be parseable as seconds."
) from None
raise TypeError(
"Retry interval must be seconds (number or string) or a timedelta."
)
def to_temporal_kwargs(self) -> Dict[str, Any]:
data: Dict[str, Any] = {}
if self.maximum_attempts is not None:
data["maximum_attempts"] = self.maximum_attempts
if self.initial_interval is not None:
data["initial_interval"] = self.initial_interval
if self.backoff_coefficient is not None:
data["backoff_coefficient"] = self.backoff_coefficient
if self.maximum_interval is not None:
data["maximum_interval"] = self.maximum_interval
if self.non_retryable_error_types:
data["non_retryable_error_types"] = list(self.non_retryable_error_types)
return data
class UsageTelemetrySettings(BaseModel):
"""
Settings for usage telemetry in the MCP Agent application.
Anonymized usage metrics are sent to a telemetry server to help improve the product.
"""
enabled: bool = True
"""Enable usage telemetry in the MCP Agent application."""
enable_detailed_telemetry: bool = False
"""If enabled, detailed telemetry data, including prompts and agents, will be sent to the telemetry server."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class TracePathSettings(BaseModel):
"""
Settings for configuring trace file paths with dynamic elements like timestamps or session IDs.
"""
path_pattern: str = "traces/mcp-agent-trace-{unique_id}.jsonl"
"""
Path pattern for trace files with a {unique_id} placeholder.
The placeholder will be replaced according to the unique_id setting.
Example: "traces/mcp-agent-trace-{unique_id}.jsonl"
"""
unique_id: Literal["timestamp", "session_id"] = "timestamp"
"""
Type of unique identifier to use in the trace filename:
"""
timestamp_format: str = "%Y%m%d_%H%M%S"
"""
Format string for timestamps when unique_id is set to "timestamp".
Uses Python's datetime.strftime format.
"""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class TraceOTLPSettings(BaseModel):
"""
Settings for OTLP exporter in OpenTelemetry.
"""
endpoint: str
"""OTLP endpoint for exporting traces."""
headers: Dict[str, str] | None = None
"""Optional headers for OTLP exporter."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class ConsoleExporterSettings(BaseModel):
"""Console exporter uses stdout; no extra settings required."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class FileExporterSettings(BaseModel):
"""File exporter settings for writing traces to a file."""
path: str | None = None
path_settings: TracePathSettings | None = None
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class OTLPExporterSettings(BaseModel):
endpoint: str | None = None
headers: Dict[str, str] | None = None
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
OpenTelemetryExporterSettings = Union[
ConsoleExporterSettings,
FileExporterSettings,
OTLPExporterSettings,
]
class OpenTelemetrySettings(BaseModel):
"""
OTEL settings for the MCP Agent application.
"""
enabled: bool = False
exporters: List[
Union[
Literal["console", "file", "otlp"],
Dict[Literal["console"], ConsoleExporterSettings | Dict],
Dict[Literal["file"], FileExporterSettings | Dict],
Dict[Literal["otlp"], OTLPExporterSettings | Dict],
ConsoleExporterSettings,
FileExporterSettings,
OTLPExporterSettings,
]
] = []
"""
Exporters to use (can enable multiple simultaneously). Each exporter accepts
either a plain string name (e.g. "console") or a keyed mapping (e.g.
`{file: {path: "path/to/file"}}`).
Backward compatible:
- `exporters: ["console", "otlp"]`
- `exporters: [{type: "file", path: "/tmp/out"}]`
Schema:
- `exporters: [console: {}, file: {path: "trace.jsonl"}, otlp: {endpoint: "https://..."}]`
- `exporters: ["console", {file: {path: "trace.jsonl"}}]`
Strings fall back to legacy fields like `otlp_settings`, `path`, and
`path_settings` when no explicit config is present"""
service_name: str = "mcp-agent"
service_instance_id: str | None = None
service_version: str | None = None
sample_rate: float = 1.0
"""Sample rate for tracing (1.0 = sample everything)"""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
@model_validator(mode="before")
@classmethod
def _coerce_exporters_schema(cls, data: Dict) -> Dict:
"""
Normalize exporter entries for backward compatibility.
This validator handles three exporter formats:
- String exporters like ["console", "file", "otlp"] with top-level legacy fields
- Type-discriminated format with 'type' field: [{type: "console"}, {type: "otlp", endpoint: "..."}]
- Key-discriminated format: [{console: {}}, {otlp: {endpoint: "..."}}]
Conversion logic:
- String exporters → Keep as-is, will be finalized in _finalize_exporters using legacy fields
- {type: "X", ...} → Convert to {X: {...}} by removing 'type' and using it as dict key
- {X: {...}} → Keep as-is (already in correct format)
"""
if not isinstance(data, dict):
return data
exporters = data.get("exporters")
if not isinstance(exporters, list):
return data
normalized: List[Union[str, Dict[str, Dict[str, object]]]] = []
for entry in exporters:
# Plain string like "console" or "file"
# These will be expanded later using legacy fields (path, otlp_settings, etc.)
if isinstance(entry, str):
normalized.append(entry)
continue
# Handle BaseModel instances passed directly (e.g., from tests or re-validation)
# If already a typed exporter settings instance, keep as-is (already finalized)
if isinstance(
entry,
(ConsoleExporterSettings, FileExporterSettings, OTLPExporterSettings),
):
normalized.append(entry)
continue
# Handle other BaseModel instances by converting to dict
if isinstance(entry, BaseModel):
entry = entry.model_dump(exclude_none=True)
# Fall through to dict processing below
if isinstance(entry, dict):
# Type-discriminated format: Extract 'type' field and use it as the dict key
# Example: {type: "otlp", endpoint: "..."} → {otlp: {endpoint: "..."}}
if "type" in entry:
entry = entry.copy()
exporter_type = entry.pop("type")
normalized.append({exporter_type: entry})
continue
# Key-discriminated format: Single-key dict like {console: {}} or {otlp: {endpoint: "..."}}
if len(entry) == 1:
normalized.append(entry)
continue
raise ValueError(
"OpenTelemetry exporters must be strings, type-tagged dicts, or "
'keyed mappings (e.g. `- console`, `- {type: "file"}`, '
'`- {file: {path: "trace.jsonl"}}`).'
)
data["exporters"] = normalized
return data
@model_validator(mode="after")
@classmethod
def _finalize_exporters(cls, values: "OpenTelemetrySettings"):
"""
Convert exporter entries to key-discriminated dict format for serialization compatibility.
This validator runs after Pydantic validation and:
1. Extracts legacy top-level fields (path, path_settings, otlp_settings) from the model
2. Converts string exporters and dict exporters to key-discriminated dict format
3. Falls back to legacy fields when string exporters don't provide explicit config
4. Removes legacy fields from the model to avoid leaking them in serialization
Output format is key-discriminated dicts (e.g., {console: {}}, {file: {path: "..."}}) to ensure
that re-serialization and re-validation works correctly.
Example conversions:
- "file" + path="trace.jsonl" → {file: {path: "trace.jsonl"}}
- "otlp" + otlp_settings={endpoint: "..."} → {otlp: {endpoint: "...", headers: ...}}
"""
finalized_exporters: List[Dict[str, Dict[str, Any]]] = []
# Extract legacy top-level fields (captured via extra="allow" in model_config)
# These fields were previously defined at the top level of OpenTelemetrySettings
legacy_path = getattr(values, "path", None)
legacy_path_settings = getattr(values, "path_settings", None)
# Normalize legacy_path_settings to TracePathSettings if it's a dict or BaseModel
if isinstance(legacy_path_settings, dict):
legacy_path_settings = TracePathSettings.model_validate(
legacy_path_settings
)
elif legacy_path_settings is not None and not isinstance(
legacy_path_settings, TracePathSettings
):
legacy_path_settings = TracePathSettings.model_validate(
getattr(
legacy_path_settings, "model_dump", lambda **_: legacy_path_settings
)()
)
# Extract legacy otlp_settings and normalize to dict
legacy_otlp = getattr(values, "otlp_settings", None)
if isinstance(legacy_otlp, BaseModel):
legacy_otlp = legacy_otlp.model_dump(exclude_none=True)
elif not isinstance(legacy_otlp, dict):
legacy_otlp = {}
for exporter in values.exporters:
# If already a typed BaseModel instance, convert to key-discriminated dict format
if isinstance(exporter, ConsoleExporterSettings):
console_dict = exporter.model_dump(exclude_none=True)
finalized_exporters.append({"console": console_dict})
continue
elif isinstance(exporter, FileExporterSettings):
file_dict = exporter.model_dump(exclude_none=True)
finalized_exporters.append({"file": file_dict})
continue
elif isinstance(exporter, OTLPExporterSettings):
otlp_dict = exporter.model_dump(exclude_none=True)
finalized_exporters.append({"otlp": otlp_dict})
continue
exporter_name: str | None = None
payload: Dict[str, object] = {}
if isinstance(exporter, str):
exporter_name = exporter
elif isinstance(exporter, dict):
if len(exporter) != 1:
raise ValueError(
"OpenTelemetry exporter mappings must have exactly one key"
)
exporter_name, payload = next(iter(exporter.items()))
if payload is None:
payload = {}
elif isinstance(payload, BaseModel):
payload = payload.model_dump(exclude_none=True)
elif not isinstance(payload, dict):
raise ValueError(
'Exporter configuration must be a dict. Example: `- file: {path: "trace.jsonl"}`'
)
else:
raise TypeError(f"Unexpected exporter entry: {exporter!r}")
if exporter_name == "console":
console_settings = ConsoleExporterSettings.model_validate(payload or {})
finalized_exporters.append(
{"console": console_settings.model_dump(exclude_none=True)}
)
elif exporter_name == "file":
file_payload = payload.copy()
file_payload.setdefault("path", legacy_path)
if (
"path_settings" not in file_payload
and legacy_path_settings is not None
):
file_payload["path_settings"] = legacy_path_settings
file_settings = FileExporterSettings.model_validate(file_payload)
finalized_exporters.append(
{"file": file_settings.model_dump(exclude_none=True)}
)
elif exporter_name == "otlp":
otlp_payload = payload.copy()
otlp_payload.setdefault("endpoint", legacy_otlp.get("endpoint"))
otlp_payload.setdefault("headers", legacy_otlp.get("headers"))
otlp_settings = OTLPExporterSettings.model_validate(otlp_payload)
finalized_exporters.append(
{"otlp": otlp_settings.model_dump(exclude_none=True)}
)
else: