Repository navigation
Expand file tree
/
Copy pathconfig.py
More file actions
3309 lines (2735 loc) · 121 KB
/
Copy pathconfig.py
File metadata and controls
3309 lines (2735 loc) · 121 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 os
import re
import sys
import warnings
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Final, Literal
from mcp_types import Implementation
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator, model_validator
from pydantic.fields import FieldInfo
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
from fast_agent.command_actions import PluginCommandActionSpec, parse_plugin_command_action_specs
from fast_agent.constants import (
DEFAULT_DURABLE_PROCESS_OUTPUT_RETENTION_BYTES,
DEFAULT_PROCESS_POLL_MAX_WAIT_SECONDS,
DEFAULT_PTC_OUTPUT_BYTE_LIMIT,
MAX_FOREGROUND_AUTO_AWAIT_SECONDS,
MAX_PROCESS_POLL_WAIT_SECONDS,
)
from fast_agent.core.exceptions import ConfigFileError
from fast_agent.home import (
ConfigDiscoveryResult,
discover_config_files,
find_config_in_directory,
resolve_fast_agent_home,
)
from fast_agent.llm.reasoning_effort import ReasoningEffortSetting
from fast_agent.llm.structured_output_mode import StructuredOutputMode
from fast_agent.llm.task_budget import parse_task_budget_tokens, validate_task_budget_tokens
from fast_agent.llm.text_verbosity import TextVerbosityLevel
from fast_agent.mcp.provider_management import (
normalize_access_token,
normalize_client_managed_url_server,
normalize_connector_id,
normalize_provider_managed_url_server,
validate_provider_managed_server_settings,
)
from fast_agent.mcp.server_declaration import (
MCPServerDeclaration,
effective_server_view,
)
from fast_agent.plugins.models import (
PluginContributions,
PluginPostUserTurnSpec,
PluginToolCallReviewSpec,
unloadable_tool_call_review,
)
from fast_agent.tools.environment_config import EnvironmentSpec
from fast_agent.tools.shell_profiles import ShellToolProfile
from fast_agent.types.streaming import StreamingMode
from fast_agent.utils.action_normalization import (
FALSE_ACTION_ALIASES,
TRUE_ACTION_ALIASES,
normalize_action_token,
on_off_label,
)
from fast_agent.utils.collections import unique_preserve_order
from fast_agent.utils.numeric import int_or_none
from fast_agent.utils.text import strip_casefold, strip_str_to_none
from fast_agent.utils.transports import McpClientTransport
MOONSHOT_DEFAULT_MODEL = "kimi-k3.1-pro"
TENCENT_EVAL_DEFAULT_MODEL = "hy4-flash-dev"
HUGGINGFACE_DEFAULT_MODEL = "moonshotai/Kimi-K3.1-Pro:together"
DEFAULT_HUGGINGFACE_MAX_REQUEST_BYTES: Final = 10_485_760
def _default_hf_max_request_bytes() -> int | None:
raw = os.getenv("HF_MAX_REQUEST_BYTES")
if raw is None or not raw.strip():
return DEFAULT_HUGGINGFACE_MAX_REQUEST_BYTES
normalized = raw.strip().casefold()
if normalized in {"none", "null", "off", "0"}:
return None
try:
parsed = int(normalized)
except ValueError:
warnings.warn(
f"Ignoring invalid HF_MAX_REQUEST_BYTES={raw!r}; "
f"using default {DEFAULT_HUGGINGFACE_MAX_REQUEST_BYTES}",
stacklevel=2,
)
return DEFAULT_HUGGINGFACE_MAX_REQUEST_BYTES
if parsed < 1:
warnings.warn(
f"Ignoring non-positive HF_MAX_REQUEST_BYTES={raw!r}; "
f"using default {DEFAULT_HUGGINGFACE_MAX_REQUEST_BYTES}",
stacklevel=2,
)
return DEFAULT_HUGGINGFACE_MAX_REQUEST_BYTES
return parsed
type TerminalImageSize = int | Literal["auto"] | str | None
type ShellWriteTextFileMode = Literal["auto", "on", "off", "apply_patch", "edit_file"]
SHELL_WRITE_TEXT_FILE_MODES: tuple[ShellWriteTextFileMode, ...] = (
"auto",
"on",
"off",
"apply_patch",
"edit_file",
)
SHELL_WRITE_TEXT_FILE_MODE_HELP = "|".join(SHELL_WRITE_TEXT_FILE_MODES)
# OpenAI provider-native compaction (``native_compaction``) on supported routes. Also
# applies when a route has no config section.
NATIVE_COMPACTION_DEFAULT = True
_SHELL_WRITE_TEXT_FILE_MODE_ALIASES: dict[str, ShellWriteTextFileMode] = {
**{mode: mode for mode in SHELL_WRITE_TEXT_FILE_MODES},
**{alias: "on" for alias in TRUE_ACTION_ALIASES},
**{alias: "off" for alias in FALSE_ACTION_ALIASES},
}
def _normalized_config_token(value: str) -> tuple[str, str]:
stripped = value.strip()
return stripped, normalize_action_token(stripped)
def normalize_shell_write_text_file_mode(value: Any) -> ShellWriteTextFileMode | None:
if value is None:
return None
if isinstance(value, bool):
return on_off_label(value)
if isinstance(value, str):
_, normalized = _normalized_config_token(value)
return _SHELL_WRITE_TEXT_FILE_MODE_ALIASES.get(normalized)
return None
def _has_nonblank(value: Any) -> bool:
return value is not None and bool(str(value).strip())
def _reject_bool_integer_field(value: Any, *, field_name: str) -> Any:
if isinstance(value, bool):
raise TypeError(f"{field_name} must be an integer.")
return value
def _reject_bool_number_field(value: Any, *, field_name: str) -> Any:
if isinstance(value, bool):
raise TypeError(f"{field_name} must be a number.")
return value
class MCPServerAuthSettings(BaseModel):
"""Represents authentication configuration for a server.
Minimal OAuth v2.1 support with sensible defaults.
"""
# Enable OAuth for SSE/HTTP transports when the auth block is present.
# If the auth block is omitted entirely, fast-agent starts unauthenticated
# and escalates to OAuth on a 401 challenge.
oauth: bool = True
# Forward the inbound request bearer token to matching upstream services.
# "huggingface" applies only to hf.co, huggingface.co, and *.hf.space URLs.
forward: Literal["huggingface"] | None = None
# Local callback server configuration
redirect_port: int = 3030
redirect_path: str = "/callback"
# Optional scope override. If set to a list, values are space-joined.
scope: str | list[str] | None = None
# Token persistence: use OS keychain via 'keyring' by default; fallback to 'memory'.
persist: Literal["keyring", "memory"] = "keyring"
# Client ID Metadata Document (CIMD) URL.
# When provided and the server advertises client_id_metadata_document_supported=true,
# this URL will be used as the client_id instead of performing dynamic client registration.
# Must be a valid HTTPS URL with a non-root pathname (e.g., https://example.com/client.json).
# See: https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization
client_metadata_url: str | None = None
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
@field_validator("redirect_port", mode="before")
@classmethod
def _reject_bool_redirect_port(cls, value: Any) -> Any:
return _reject_bool_integer_field(value, field_name="redirect_port")
@field_validator("client_metadata_url", mode="after")
@classmethod
def _validate_client_metadata_url(cls, v: str | None) -> str | None:
"""Validate that client_metadata_url is a valid HTTPS URL with a non-root path."""
if v is None:
return None
from urllib.parse import urlparse
try:
parsed = urlparse(v)
if parsed.scheme != "https":
raise ValueError("client_metadata_url must use HTTPS scheme")
if parsed.path in ("", "/"):
raise ValueError("client_metadata_url must have a non-root pathname")
return v
except ValueError:
raise
except Exception as e:
raise ValueError(f"Invalid client_metadata_url: {e}") from e
class MCPSamplingSettings(BaseModel):
model: str | None = None
"""Model used for sampling requests. Falls back to the agent or configured global model."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class MCPElicitationSettings(BaseModel):
mode: Literal["forms", "auto-cancel", "none"] = "none"
"""Elicitation mode: 'forms' (default UI), 'auto-cancel', 'none' (no capability)"""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class MCPTimelineSettings(BaseModel):
"""Configuration for MCP activity timeline display."""
steps: int = 20
"""Number of timeline buckets to render."""
step_seconds: int = 30
"""Duration of each timeline bucket in seconds."""
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
@staticmethod
def _parse_duration(value: str) -> int:
"""Parse simple duration strings like '30s', '2m', '1h' into seconds."""
pattern = re.compile(r"^\s*(\d+)\s*([smhd]?)\s*$", re.IGNORECASE)
match = pattern.match(value)
if not match:
raise ValueError("Expected duration in seconds (e.g. 30, '45s', '2m').")
amount = int(match.group(1))
unit = strip_casefold(match.group(2))
multiplier = {
"": 1,
"s": 1,
"m": 60,
"h": 3600,
"d": 86400,
}.get(unit)
if multiplier is None:
raise ValueError("Duration unit must be one of s, m, h, or d.")
return amount * multiplier
@field_validator("steps", mode="before")
@classmethod
def _coerce_steps(cls, value: Any) -> int:
if isinstance(value, bool):
raise TypeError("Timeline steps must be an integer.")
if isinstance(value, str):
if not value.strip().isdigit():
raise ValueError("Timeline steps must be a positive integer.")
value = int(value.strip())
elif isinstance(value, float):
value = int(value)
if not isinstance(value, int):
raise TypeError("Timeline steps must be an integer.")
if value <= 0:
raise ValueError("Timeline steps must be greater than zero.")
return value
class MCPDefaultsSettings(BaseModel):
"""Defaults applied to omitted MCP server settings."""
protocol_mode: Literal["auto", "modern", "legacy"] = "auto"
reconnect_on_disconnect: bool = True
include_instructions: bool = True
model_config = ConfigDict(extra="forbid")
class MCPClientSettings(BaseModel):
"""MCP client behavior."""
auto_sampling: bool = True
model_config = ConfigDict(extra="forbid")
class MCPDiagnosticsSettings(BaseModel):
"""MCP diagnostics collection and display settings."""
enabled: bool = True
timeline: MCPTimelineSettings = Field(default_factory=MCPTimelineSettings)
model_config = ConfigDict(extra="forbid")
class SkillsSettings(BaseModel):
"""Configuration for the skills directory override."""
directories: list[str] | None = None
marketplace_url: str | None = None
marketplace_urls: list[str] | None = None
model_config = ConfigDict(extra="ignore")
class CardsSettings(BaseModel):
"""Configuration for card pack registry selection."""
marketplace_url: str | None = None
marketplace_urls: list[str] | None = None
model_config = ConfigDict(extra="ignore")
class PluginsSettings(BaseModel):
"""Configuration for command plugin discovery and marketplace selection."""
enabled: list[str] = Field(default_factory=list)
marketplace_url: str | None = None
marketplace_urls: list[str] | None = None
config: dict[str, dict[str, Any]] = Field(default_factory=dict)
model_config = ConfigDict(extra="ignore")
class HarnessAppSettings(BaseModel):
"""Configuration for the harness application boundary."""
entrypoint: str | None = None
"""Import path for a custom harness app factory, as module:function."""
model_config = ConfigDict(extra="ignore")
class ACPSettings(BaseModel):
"""Configuration for ACP (Agent Client Protocol) server behavior."""
use_client_tools: bool = Field(
default=False,
description=(
"Opt in to delegating shell and filesystem tools to the ACP client when "
"the client advertises terminal or fs capabilities. When False (default), "
"ACP mode keeps fast-agent's native local shell, filesystem, and PTC tools."
),
)
model_config = ConfigDict(extra="ignore")
class ShellSettings(BaseModel):
"""Configuration for shell execution behavior."""
tool_profile: ShellToolProfile = Field(
default="auto",
description=(
"Direct-mode shell contract (canonical PTC always uses shell/process): "
"'auto' selects a model-specific contract; "
"'minimal_process' exposes Bash and Process; "
"'native' retains the legacy execute/poll_process/terminate_process tools; "
"'grok_shell' exposes aligned shell plus Process; "
"'luna_exec' exposes foreground-first exec plus Process; "
"'freeform_shell' exposes the luna_exec contract as a freeform (non-JSON) "
"raw-command shell tool plus Process"
),
)
timeout_seconds: int = Field(
default=90,
description="Maximum seconds without command output before terminating",
)
warning_interval_seconds: int = Field(
default=30,
description="Show timeout warnings every N seconds",
)
interactive_use_pty: bool = Field(
default=True,
description="Use a PTY for interactive prompt shell commands",
)
output_display_lines: int | None = Field(
default=5,
description=(
"Maximum shell output lines to display "
"(head/tail with an ellipsis when truncated; None = no limit)"
),
)
show_bash: bool = Field(
default=True,
description="Show shell command output on the console",
)
output_byte_limit: int | None = Field(
default=16_000,
description="Model-facing shell output preview bytes (None = model-based auto)",
)
running_output_byte_limit: int | None = Field(
default=6000,
ge=256,
description=(
"Preview bytes for a command that is still running (when it outlasts the "
"foreground wait, or a process wait/status returns it running): an eighth from "
"the start of the unread output, the rest from the end; at most "
"output_byte_limit. Applies to session-managed and persistent processes; explicit "
"process preview limits override it. Retention is bounded by the applicable "
"session/durable quota (None = the normal head/tail preview). Default 6000 "
"(750 + 5250 bytes): "
"in A/B runs the model's next step was unchanged, almost always a process wait"
),
)
output_byte_limit_selection: Literal["default", "explicit", "auto"] = Field(
default="default",
repr=False,
json_schema_extra={"internal": True},
)
retain_truncated_output: bool = Field(
default=True,
description=(
"Retain complete truncated shell output in a private session-scoped "
"temporary file and include its path in the model-facing truncation notice"
),
)
retained_output_max_bytes: int = Field(
default=2 * 1024 * 1024,
ge=1,
description="Maximum bytes retained per shell process when retention is enabled",
)
durable_output_max_bytes: int = Field(
default=DEFAULT_DURABLE_PROCESS_OUTPUT_RETENTION_BYTES,
ge=1,
description="Maximum bytes retained in each durable process output log",
)
retained_output_temp_directory: Path | None = Field(
default=None,
description=(
"Parent directory for private retained-output session directories "
"(None = platform temporary directory)"
),
)
process_poll_max_wait_seconds: int = Field(
default=DEFAULT_PROCESS_POLL_MAX_WAIT_SECONDS,
ge=1,
le=MAX_PROCESS_POLL_WAIT_SECONDS,
description="Maximum duration of one model-initiated managed-process wait",
)
foreground_auto_await_max_seconds: int = Field(
default=30,
ge=0,
le=MAX_FOREGROUND_AUTO_AWAIT_SECONDS,
description=(
"Maximum total foreground runtime before returning a live process; "
"0 returns it at the initial idle or total-runtime yield"
),
)
managed_process_poll_history_folding: Literal["auto", "on", "off"] = Field(
default="auto",
description=(
"Control repetitive quiet poll_process history folding: 'auto' uses "
"validated model metadata, 'on' forces folding, and 'off' disables it"
),
)
missing_cwd_policy: Literal["ask", "create", "warn", "error"] = Field(
default="warn",
description="Policy when an agent shell cwd is missing or invalid",
)
prefer_local_shell: bool = Field(
default=False,
description=(
"In ACP mode, keep the local fast-agent shell runtime instead of replacing it "
"with the ACP client's terminal runtime when the client advertises terminal support"
),
)
enable_read_text_file: bool = Field(
default=True,
description=(
"Expose a local read_text_file tool (ACP-compatible signature) "
"when shell runtime is enabled"
),
)
enable_attach_media: Literal["auto", "on", "off"] = Field(
default="auto",
description=(
"Expose attach_media when shell runtime is enabled. 'auto' exposes it only "
"for models with non-text attachment support; 'on' exposes it with call-time "
"validation; 'off' disables it."
),
)
write_text_file_mode: ShellWriteTextFileMode | None = Field(
default=None,
description=(
"Control which local file edit tool is exposed when shell runtime is enabled "
"('auto' uses apply_patch for Codex and GPT-5.2+ models, edit_file for "
"models that prefer it, and write_text_file plus edit_file otherwise; "
"'on' always exposes write_text_file plus edit_file; 'edit_file' exposes "
"only edit_file; 'apply_patch' always exposes apply_patch; 'off' disables "
"local file edit tools)"
),
)
model_config = ConfigDict(extra="ignore")
@field_validator("timeout_seconds", mode="before")
@classmethod
def _coerce_timeout(cls, value: Any) -> int:
"""Support duration strings like '90s', '2m', '1h'"""
_reject_bool_integer_field(value, field_name="timeout_seconds")
if isinstance(value, str):
return MCPTimelineSettings._parse_duration(value)
return int(value)
@field_validator("warning_interval_seconds", mode="before")
@classmethod
def _coerce_warning_interval(cls, value: Any) -> int:
"""Support duration strings like '30s', '1m'"""
_reject_bool_integer_field(value, field_name="warning_interval_seconds")
if isinstance(value, str):
return MCPTimelineSettings._parse_duration(value)
return int(value)
@field_validator("output_display_lines", mode="before")
@classmethod
def _coerce_output_display_lines(cls, value: Any) -> int | None:
if value is None:
return None
_reject_bool_integer_field(value, field_name="output_display_lines")
if isinstance(value, str):
stripped = value.strip()
if stripped == "":
return None
if not stripped.isdigit():
raise ValueError("output_display_lines must be a non-negative integer.")
value = int(stripped)
else:
value = int(value)
if value < 0:
raise ValueError("output_display_lines must be a non-negative integer.")
return value
@field_validator("output_byte_limit", mode="before")
@classmethod
def _coerce_output_byte_limit(cls, value: Any) -> int | None:
if value is None:
return None
_reject_bool_integer_field(value, field_name="output_byte_limit")
if isinstance(value, str):
return int(value.strip())
return int(value)
@model_validator(mode="before")
@classmethod
def _capture_output_byte_limit_selection(cls, value: Any) -> Any:
if not isinstance(value, dict):
return value
if "output_byte_limit_selection" in value or "output_byte_limit" not in value:
return value
updated = dict(value)
updated["output_byte_limit_selection"] = (
"auto" if value["output_byte_limit"] is None else "explicit"
)
return updated
@field_validator("retained_output_max_bytes", mode="before")
@classmethod
def _coerce_retained_output_max_bytes(cls, value: Any) -> int:
_reject_bool_integer_field(value, field_name="retained_output_max_bytes")
return int(value.strip()) if isinstance(value, str) else int(value)
@field_validator("durable_output_max_bytes", mode="before")
@classmethod
def _coerce_durable_output_max_bytes(cls, value: Any) -> int:
_reject_bool_integer_field(value, field_name="durable_output_max_bytes")
return int(value.strip()) if isinstance(value, str) else int(value)
@field_validator("process_poll_max_wait_seconds", mode="before")
@classmethod
def _coerce_process_poll_max_wait_seconds(cls, value: Any) -> int:
_reject_bool_integer_field(value, field_name="process_poll_max_wait_seconds")
return int(value.strip()) if isinstance(value, str) else int(value)
@field_validator("foreground_auto_await_max_seconds", mode="before")
@classmethod
def _coerce_foreground_auto_await_max_seconds(cls, value: Any) -> int:
_reject_bool_integer_field(value, field_name="foreground_auto_await_max_seconds")
if isinstance(value, str):
return MCPTimelineSettings._parse_duration(value)
if type(value) is not int:
raise TypeError("foreground_auto_await_max_seconds must be an integer")
return value
@field_validator("write_text_file_mode", mode="before")
@classmethod
def _coerce_write_text_file_mode(cls, value: Any) -> ShellWriteTextFileMode | None:
normalized = normalize_shell_write_text_file_mode(value)
if normalized is not None or value is None:
return normalized
raise ValueError(
"write_text_file_mode must be one of: auto, on, off, apply_patch, edit_file"
)
class CompactionSettings(BaseModel):
"""Configuration for conversation history compaction."""
auto: bool = Field(
default=True,
description="Automatically compact history when context usage crosses the threshold",
)
threshold: float | None = Field(
default=None,
gt=0.0,
le=1.0,
description=(
"Fraction of the model context window that triggers auto-compaction, for every "
"model. Unset uses the model's default (e.g. Grok 4.7 compacts at 190k tokens), "
"else 0.85. A model string's compact_at overrides it"
),
)
keep_turns: int = Field(
default=2,
ge=0,
description="Number of recent complete turns kept verbatim after compaction",
)
strategy: Literal["auto", "client"] = Field(
default="auto",
description=(
"How compaction is performed. 'auto' uses provider-native compaction where the "
"model supports it and fast-agent's summary otherwise; 'client' always uses "
"fast-agent's summary"
),
)
prompt: str | None = Field(
default=None,
description=(
"Custom summarization prompt for compaction. Inline text, or a path to a "
"text/markdown file. None uses the built-in prompt (see /compact prompt)."
),
)
model_config = ConfigDict(extra="ignore")
_config_file: str | None = PrivateAttr(default=None)
def configured_prompt(self) -> str | None:
"""The configured summarization prompt (inline text or file contents), if any.
Relative file paths resolve from the config file's directory. An empty or
unreadable setting means no custom prompt: fast-agent's built-in one applies.
"""
configured = self.prompt
if not configured or not configured.strip():
return None
candidate = configured.strip()
if len(candidate) < 1024 and "\n" not in candidate:
try:
path = Path(candidate).expanduser()
if not path.is_absolute() and self._config_file:
path = Path(self._config_file).expanduser().resolve().parent / path
if path.is_file():
return path.read_text(encoding="utf-8").strip() or None
except OSError:
pass
return configured
@property
def has_custom_prompt(self) -> bool:
"""Whether a custom prompt is configured; it requires a written summary."""
return self.configured_prompt() is not None
class CacheWarmSettings(BaseModel):
"""Configuration for keeping provider prompt caches warm between model requests."""
auto: bool = Field(
default=True,
description=(
"Keep the prompt cache warm automatically while a turn waits on tools or "
"subagents, and while an idle session waits for herdr-core children to report"
),
)
max_minutes: int = Field(
default=30,
ge=1,
le=24 * 60,
description=(
"How long automatic warming continues after the last model request; also the "
"default /warm duration"
),
)
interval_seconds: int | None = Field(
default=None,
ge=10,
description=(
"Seconds between keep-warm requests. Unset derives it from the provider's cache "
"retention; set it to warm a model whose retention fast-agent does not know"
),
)
class MCPRootSettings(BaseModel):
"""Represents a root directory configuration for an MCP server."""
uri: str
"""The URI identifying the root. Must start with file://"""
name: str | None = None
"""Optional name for the root."""
server_uri_alias: str | None = 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 v and 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.
"""
name: str | None = None
"""The name of the server."""
description: str | None = None
"""The description of the server."""
management: Literal["client", "provider"] = "client"
"""Whether fast-agent connects locally or delegates MCP execution to the provider."""
transport: McpClientTransport = "stdio"
"""The transport mechanism."""
protocol_mode: Literal["auto", "modern", "legacy"] = "auto"
"""MCP protocol selection: negotiate automatically or force a protocol era."""
command: str | None = None
"""The command to execute the server (e.g. npx)."""
args: list[str] | None = None
"""The arguments for the server command."""
read_timeout_seconds: int | None = None
"""The timeout in seconds for the session."""
ping_interval_seconds: int = 30
"""Interval for MCP ping requests. Set <=0 to disable pinging."""
max_missed_pings: int = 3
"""Number of consecutive missed ping responses before treating the connection as failed."""
http_timeout_seconds: int | None = None
"""Overall HTTP timeout (seconds) for StreamableHTTP transport. Defaults to MCP SDK."""
http_read_timeout_seconds: int | None = None
"""HTTP read timeout (seconds) for StreamableHTTP transport. Defaults to MCP SDK."""
read_transport_sse_timeout_seconds: int = 300
"""The timeout in seconds for the server connection."""
url: str | None = None
"""The URL for the server (e.g. for SSE/SHTTP transport)."""
connector_id: str | None = None
"""OpenAI Responses provider-managed connector identifier."""
headers: dict[str, str] | None = None
"""Headers dictionary for HTTP connections"""
access_token: str | None = None
"""Provider-neutral bearer token for local URL servers or provider-managed MCP."""
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."""
sampling: MCPSamplingSettings | None = None
"""Sampling settings for this Client/Server pair"""
elicitation: MCPElicitationSettings | None = None
"""Elicitation settings for this Client/Server pair"""
cwd: str | None = None
"""Working directory for the executed server command."""
load_on_start: bool = True
"""Whether to connect to this server automatically when the agent starts."""
include_instructions: bool = True
"""Whether to include this server's instructions in the system prompt (default: True)."""
reconnect_on_disconnect: bool = True
"""Whether to automatically reconnect when the server session is terminated (e.g., 404).
When enabled, if a remote StreamableHTTP server returns a 404 indicating the session
has been terminated (e.g., due to server restart), the client will automatically
attempt to re-initialize the connection and retry the operation.
"""
implementation: Implementation | None = None
defer_loading: bool = False
"""Provider-managed OpenAI Responses hint to defer remote tool loading."""
@field_validator(
"read_timeout_seconds",
"ping_interval_seconds",
"http_timeout_seconds",
"http_read_timeout_seconds",
"read_transport_sse_timeout_seconds",
mode="before",
)
@classmethod
def _reject_bool_timeout_value(cls, value: Any) -> Any:
return _reject_bool_integer_field(value, field_name="MCP timeout fields")
@field_validator("max_missed_pings", mode="before")
@classmethod
def _coerce_max_missed_pings(cls, value: Any) -> int:
if isinstance(value, bool):
raise TypeError("max_missed_pings must be an integer.")
if isinstance(value, str):
value = int(value.strip())
value = int(value)
if value <= 0:
raise ValueError("max_missed_pings must be greater than zero.")
return value
@field_validator("access_token", mode="before")
@classmethod
def _normalize_access_token(cls, value: Any) -> str | None:
if value is None:
return None
if not isinstance(value, str):
raise TypeError("access_token must be a string")
return normalize_access_token(value)
@field_validator("connector_id", mode="before")
@classmethod
def _normalize_connector_id(cls, value: Any) -> str | None:
if value is None:
return None
if not isinstance(value, str):
raise TypeError("connector_id must be a string")
return normalize_connector_id(value)
@model_validator(mode="before")
@classmethod
def validate_transport_inference(cls, values):
"""Automatically infer transport type based on url/command presence."""
if not isinstance(values, dict) or "transport" in values:
return values
url = values.get("url")
command = values.get("command")
has_url = _has_nonblank(url)
has_command = _has_nonblank(command)
if has_url:
if has_command:
warnings.warn(
f"MCP Server config has both 'url' ({url}) and 'command' ({command}) specified. "
"Preferring HTTP transport and ignoring command.",
UserWarning,
stacklevel=4,
)
values["command"] = None
values["transport"] = "http"
elif has_command:
values["transport"] = "stdio"
return values
@model_validator(mode="after")
def _normalize_management_specific_settings(self) -> "MCPServerSettings":
if self.management == "provider":
validation = validate_provider_managed_server_settings(self)
if not validation.has_exactly_one_source():
raise ValueError(
"Provider-managed MCP servers require exactly one of url or connector_id"
)
if validation.invalid_fields:
invalid_list = ", ".join(validation.invalid_fields)
raise ValueError(
f"Provider-managed MCP servers have unsupported settings: {invalid_list}"
)
if validation.missing_connector_access_token:
raise ValueError("Provider-managed connectors require access_token")
if validation.has_url:
provider_url = self.url
if provider_url is None:
raise ValueError("Provider-managed URL servers require url")
self.url = normalize_provider_managed_url_server(
transport=self.transport,
url=provider_url,
)
return self
if self.connector_id is not None:
raise ValueError("connector_id is only supported for provider-managed MCP servers")
if self.protocol_mode == "modern" and self.transport == "sse":
raise ValueError("protocol_mode='modern' is not supported with legacy SSE transport")
if self.access_token is not None and not self.url:
raise ValueError("access_token requires a URL-based MCP server")
if self.url:
normalized_server = normalize_client_managed_url_server(
transport=self.transport,
url=self.url,
headers=self.headers,
access_token=self.access_token,
forward_huggingface=(self.auth is not None and self.auth.forward == "huggingface"),
)
self.url = normalized_server.url
self.headers = normalized_server.headers
return self
class MCPSettings(BaseModel):
"""Configuration for all MCP servers."""
defaults: MCPDefaultsSettings = Field(default_factory=MCPDefaultsSettings)
client: MCPClientSettings = Field(default_factory=MCPClientSettings)
diagnostics: MCPDiagnosticsSettings = Field(default_factory=MCPDiagnosticsSettings)
servers: dict[str, MCPServerSettings] = Field(default_factory=dict)
server_declarations: dict[str, MCPServerDeclaration] = Field(
default_factory=dict,
exclude=True,
repr=False,
)
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
@staticmethod
def _serialize_resolved_target_settings(
settings: MCPServerSettings,
) -> dict[str, Any]:
"""Serialize shorthand target settings back to an idempotent raw payload."""
payload = settings.model_dump(mode="python")
# resolve_target_entry() already normalizes access_token into Authorization
# for client-managed URL servers. Strip that synthesized header here so the
# final MCPServerSettings validation only applies the normalization once.
if settings.management != "provider" and settings.access_token is not None:
headers = payload.get("headers")
if isinstance(headers, dict):
expected_authorization = f"Bearer {settings.access_token}"
filtered_headers = {
key: value
for key, value in headers.items()
if not (
isinstance(key, str)
and strip_casefold(key) == "authorization"
and value == expected_authorization
)
}
payload["headers"] = filtered_headers or None
return payload
@classmethod
def _normalize_server_map_entries(
cls,
raw_servers: Any,
*,
warn_nested_names: bool = True,
) -> tuple[dict[Any, Any] | None, dict[str, MCPServerDeclaration]]:
if raw_servers is None:
return {}, {}
if not isinstance(raw_servers, dict):
return None, {}
normalized_servers: dict[Any, Any] = {}
declarations: dict[str, MCPServerDeclaration] = {}
for server_key, raw_entry in raw_servers.items():
if not isinstance(raw_entry, dict):
normalized_servers[server_key] = raw_entry
continue
source_name = str(server_key)
declaration = MCPServerDeclaration.from_source(
name=source_name,
source=raw_entry,
source_path=f"mcp.servers.{source_name}",
)