Skip to content

SkillsToolset API Reference

Prefer the SkillsCapability API when your app uses capabilities=[...].

When using SkillsToolset directly with toolsets=[...], skill instructions are injected into the agent's context automatically.

Bases: FunctionToolset[Any]

Pydantic AI toolset for automatic skill discovery and integration.

See skills docs for more information.

This is the primary interface for integrating skills with Pydantic AI agents. It manages skills directly and provides tools for skill interaction.

Provides the following tools to agents: - list_skills(): List all available skills - load_skill(skill_name): Load a specific skill's instructions - read_skill_resource(skill_name, resource_name): Read a skill resource file - run_skill_script(skill_name, script_name, args): Execute a skill script

Example
from pydantic_ai import Agent, SkillsToolset

# Default: uses ./skills directory
agent = Agent(
    model='openai:gpt-5.2',
    instructions="You are a helpful assistant.",
    toolsets=[SkillsToolset()]
)

# Multiple directories
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(directories=["./skills", "./more-skills"])]
)

# Programmatic skills
from pydantic_ai_skills import Skill

custom_skill = Skill(
    name="my-skill",
    description="Custom skill",
    content="Instructions here",
)
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(skills=[custom_skill])]
)

# Combined mode: both programmatic skills and directories
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(
        skills=[custom_skill],
        directories=["./skills"]
    )]
)

# Using SkillsDirectory instances directly
from pydantic_ai_skills import SkillsDirectory

dir1 = SkillsDirectory(path="./skills")
agent = Agent(
    model='openai:gpt-5.2',
    toolsets=[SkillsToolset(directories=[dir1, "./more-skills"])]
)
# Skills instructions are automatically injected via get_instructions()
Source code in pydantic_ai_skills/toolset.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
class SkillsToolset(FunctionToolset[Any]):
    """Pydantic AI toolset for automatic skill discovery and integration.

    See [skills docs](../creating-skills.md) for more information.

    This is the primary interface for integrating skills with Pydantic AI agents.
    It manages skills directly and provides tools for skill interaction.

    Provides the following tools to agents:
    - list_skills(): List all available skills
    - load_skill(skill_name): Load a specific skill's instructions
    - read_skill_resource(skill_name, resource_name): Read a skill resource file
    - run_skill_script(skill_name, script_name, args): Execute a skill script

    Example:
        ```python
        from pydantic_ai import Agent, SkillsToolset

        # Default: uses ./skills directory
        agent = Agent(
            model='openai:gpt-5.2',
            instructions="You are a helpful assistant.",
            toolsets=[SkillsToolset()]
        )

        # Multiple directories
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(directories=["./skills", "./more-skills"])]
        )

        # Programmatic skills
        from pydantic_ai_skills import Skill

        custom_skill = Skill(
            name="my-skill",
            description="Custom skill",
            content="Instructions here",
        )
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(skills=[custom_skill])]
        )

        # Combined mode: both programmatic skills and directories
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(
                skills=[custom_skill],
                directories=["./skills"]
            )]
        )

        # Using SkillsDirectory instances directly
        from pydantic_ai_skills import SkillsDirectory

        dir1 = SkillsDirectory(path="./skills")
        agent = Agent(
            model='openai:gpt-5.2',
            toolsets=[SkillsToolset(directories=[dir1, "./more-skills"])]
        )
        # Skills instructions are automatically injected via get_instructions()
        ```
    """

    def __init__(
        self,
        *,
        skills: list[Skill] | None = None,
        directories: list[str | Path | SkillsDirectory] | None = None,
        registries: list[SkillRegistry] | None = None,
        validate: bool = True,
        max_depth: int | None = 3,
        exclude_resources: Iterable[str] | None = None,
        id: str | None = None,
        instruction_template: str | None = None,
        include: Collection[str] | None = None,
        exclude: Collection[str] | None = None,
        exclude_tools: set[str] | list[str] | None = None,
        auto_reload: bool = False,
        max_retries: int = 1,
    ) -> None:
        """Initialize the skills toolset.

        Args:
            skills: List of pre-loaded Skill objects. Can be combined with `directories`.
            directories: List of directories or SkillsDirectory instances to discover skills from.
                Can be combined with `skills`. If both are None, defaults to ["./skills"].
                String/Path entries are converted to SkillsDirectory instances.
            registries: List of SkillRegistry instances (e.g. GitSkillsRegistry) to load
                skills from. Registry skills are fetched lazily on the first async call
                (``get_instructions`` or any tool invocation). Can be combined with
                ``skills`` and ``directories``.
            validate: Validate skill structure during discovery (used when creating SkillsDirectory from str/Path).
            max_depth: Maximum depth for skill discovery (None for unlimited, used when creating SkillsDirectory from str/Path).
            exclude_resources: Extra glob patterns to exclude from resource discovery, in addition to the
                built-in defaults (``__pycache__``, ``*.pyc``, ``.DS_Store`` …). Used when creating
                SkillsDirectory from str/Path. Any readable text file not excluded and not discovered as a
                script becomes a resource. None for defaults only.
            id: Unique identifier for this toolset.
            instruction_template: Custom instruction template for skills system prompt.
                Must include `{skills_list}` placeholder. If None, uses default template.
                Tool usage guidance is provided in the tool docstrings themselves.
            include: Exact skill names to expose. When provided, every other discovered skill is
                omitted from the catalog. Cannot be combined with ``exclude``. Pass an empty
                collection to expose no skills. Unknown names raise ``ValueError``.
            exclude: Exact skill names to omit from the catalog. Cannot be combined with
                ``include``. Unknown names raise ``ValueError``.
            exclude_tools: Set or list of tool names to exclude from registration (e.g., ['run_skill_script']).
                Useful for security or capability restrictions such as disabling script execution.
                Valid tool names: 'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'.
            auto_reload: If True, automatically re-scan all configured directories before each
                agent run by calling :meth:`reload` inside :meth:`get_instructions`. Useful for
                long-lived servers where skill files may be edited at runtime. Programmatic skills
                defined via ``skills=`` or ``@toolset.skill`` are always preserved. Registry
                skills are preserved from the initial load cache (no network calls are made on
                each run). To re-fetch fresh skills from registries, call :meth:`reload` with
                ``include_registries=True`` explicitly. Defaults to False.
            max_retries: Maximum number of times the model is allowed to retry a tool call when
                the tool raises ``ModelRetry`` (e.g. when the LLM passes an unknown
                ``skill_name``, ``resource_name``, or ``script_name``). Forwarded to
                :class:`pydantic_ai.toolsets.FunctionToolset` so every registered tool inherits
                this retry budget. Defaults to 1 (matching Pydantic AI's default).

        Example:
            ```python
            # Default: uses ./skills directory
            toolset = SkillsToolset()

            # Multiple directories
            toolset = SkillsToolset(directories=["./skills", "./more-skills"])

            # Programmatic skills
            toolset = SkillsToolset(skills=[skill1, skill2])

            # Combined mode
            toolset = SkillsToolset(
                skills=[skill1, skill2],
                directories=["./skills", skills_dir_instance]
            )

            # Using SkillsDirectory instances directly
            dir1 = SkillsDirectory(path="./skills")
            toolset = SkillsToolset(directories=[dir1])

            # Expose only a subset of the discovered skills
            toolset = SkillsToolset(directories=["./skills"], include=['arxiv-search'])

            # Expose everything except one skill
            toolset = SkillsToolset(directories=["./skills"], exclude=['web-research'])

            # Excluding specific tools (disable script execution with a set)
            toolset = SkillsToolset(exclude_tools=['run_skill_script'])

            # Auto-reload: re-scan directories before every agent run
            toolset = SkillsToolset(directories=['./skills'], auto_reload=True)

            # Git registry: clone a remote repo and load skills
            from pydantic_ai_skills.registries.git import GitSkillsRegistry
            registry = GitSkillsRegistry(
                repo_url="https://github.com/anthropics/skills",
                path="skills",
            )
            toolset = SkillsToolset(registries=[registry])
            ```
        """
        super().__init__(id=id, max_retries=max_retries)

        self._instruction_template = instruction_template

        self._init_selection(include, exclude)

        # Validate and initialize exclude_tools
        valid_tools = {'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'}
        self._exclude_tools: set[str] = set(exclude_tools or [])
        invalid = self._exclude_tools - valid_tools
        if invalid:
            raise ValueError(f'Unknown tools: {invalid}. Valid: {valid_tools}')

        if 'load_skill' in self._exclude_tools:
            warnings.warn(
                "'load_skill' is a critical tool for skills usage and has been excluded. "
                'Agents will not be able to load skill instructions, which severely limits skill functionality.',
                UserWarning,
                stacklevel=2,
            )

        self._auto_reload = auto_reload

        # Initialize the skills dict and directories list (for refresh)
        self._skills: dict[str, Skill] = {}
        self._programmatic_skills: list[Skill] = []
        self._skill_directories: list[SkillsDirectory] = []
        self._registries: list[SkillRegistry] = list(registries) if registries else []
        self._registry_skills: dict[str, Skill] = {}  # Cache of registry-sourced skills
        self._validate = validate
        self._max_depth = max_depth
        self._exclude_resources = exclude_resources

        # Load programmatic skills first (highest priority)
        if skills is not None:
            for skill in skills:
                self._programmatic_skills.append(skill)
                self._register_skill(skill)

        # Load directory-based skills (second priority)
        if directories is not None:
            self._load_directory_skills(directories)
        elif skills is None and not self._registries:
            # Default: ./skills directory (only if no skills or registries provided)
            default_dir = Path('./skills')
            if not default_dir.exists():
                warnings.warn(
                    f"Default skills directory '{default_dir}' does not exist. No skills will be loaded.",
                    UserWarning,
                    stacklevel=2,
                )
            else:
                self._load_directory_skills([default_dir])

        # Load registry skills (lowest priority — won't override existing)
        self._load_registry_skills()

        # Surface typos in include/exclude once every source has been scanned
        self._validate_selection()

        # Register tools
        self._register_tools()

    @property
    def skills(self) -> dict[str, Skill]:
        """Get the dictionary of loaded skills.

        Returns:
            Dictionary mapping skill names to Skill objects.
        """
        return self._skills

    def _init_selection(self, include: Collection[str] | None, exclude: Collection[str] | None) -> None:
        """Configure skill-name selection, applied to every source.

        Args:
            include: Exact skill names to expose, or None to expose all.
            exclude: Exact skill names to omit, or None to omit none.

        Raises:
            ValueError: If both `include` and `exclude` are provided.
        """
        if include is not None and exclude is not None:
            raise ValueError('include and exclude cannot be used together.')
        self._include = _normalize_selection('include', include) if include is not None else None
        self._exclude = _normalize_selection('exclude', exclude) if exclude is not None else frozenset()
        # Every skill name seen before selection, used to report unknown include/exclude entries.
        self._discovered_names: set[str] = set()

    def _is_selected(self, name: str) -> bool:
        """Return whether *name* passes the configured `include`/`exclude` selection.

        Records the name as discovered so :meth:`_validate_selection` can report
        unknown `include`/`exclude` entries.
        """
        self._discovered_names.add(name)
        if self._include is not None:
            return name in self._include
        return name not in self._exclude

    def _validate_selection(self) -> None:
        """Raise if `include` or `exclude` names no skill from any configured source.

        Raises:
            ValueError: If an `include`/`exclude` entry matches no discovered skill.
        """
        for option, selected in (('include', self._include), ('exclude', self._exclude)):
            if not selected:
                continue
            unknown = sorted(set(selected) - self._discovered_names)
            if unknown:
                available = ', '.join(sorted(self._discovered_names)) or '(none)'
                noun = 'skill' if len(unknown) == 1 else 'skills'
                raise ValueError(f'Unknown {noun} in {option}: {", ".join(unknown)}. Available skills: {available}.')

    def get_skill(self, name: str) -> Skill:
        """Get a specific skill by name.

        Args:
            name: Name of the skill to get.

        Returns:
            The requested Skill object.

        Raises:
            KeyError: If skill is not found.
        """
        if name not in self._skills:
            available = ', '.join(sorted(self._skills.keys())) or 'none'
            raise KeyError(f"Skill '{name}' not found. Available: {available}")
        return self._skills[name]

    def _load_directory_skills(self, directories: list[str | Path | SkillsDirectory]) -> None:
        """Load skills from configured directories.

        Converts directory specifications to SkillsDirectory instances,
        appends them to ``_skill_directories``, then scans all registered
        directories via :meth:`_collect_dir_skills_into`.

        Args:
            directories: List of directory paths or SkillsDirectory instances.
        """
        for directory in directories:
            if isinstance(directory, SkillsDirectory):
                skill_dir = directory
            else:
                skill_dir = SkillsDirectory(
                    path=directory,
                    validate=self._validate,
                    max_depth=self._max_depth,
                    exclude_resources=self._exclude_resources,
                )
            self._skill_directories.append(skill_dir)

        self._collect_dir_skills_into(self._skills)

    def _collect_dir_skills_into(self, target: dict[str, Skill]) -> None:
        """Scan all configured skill directories and populate *target*.

        Programmatic skill names are treated as protected — directory skills
        with the same name are silently skipped so that programmatic skills
        always retain the highest priority.  Within directory-sourced skills,
        later directories override earlier ones (last-directory-wins).

        Args:
            target: Mapping to populate with discovered skills.
        """
        programmatic_names = {s.name for s in self._programmatic_skills}
        for skill_dir in self._skill_directories:
            for skill in skill_dir.get_skills().values():
                if not self._is_selected(skill.name):
                    continue
                if skill.name in programmatic_names:
                    continue  # programmatic always wins
                if skill.name in target:
                    warnings.warn(
                        f"Duplicate skill '{skill.name}' found. Overriding previous occurrence.",
                        UserWarning,
                        stacklevel=3,
                    )
                target[skill.name] = skill

    def _load_registry_skills(self) -> None:
        """Load skills from all configured registries (initial load only).

        Calls ``get_skills()`` on each registry, populates the
        ``_registry_skills`` cache, and registers skills not already present
        (registries have the lowest priority).
        """
        for registry in self._registries:
            try:
                registry_skills = registry.get_skills()
            except Exception as exc:
                warnings.warn(
                    f'Failed to load skills from registry {registry!r}: {exc}',
                    UserWarning,
                    stacklevel=2,
                )
                continue
            for skill in registry_skills:
                self._registry_skills[skill.name] = skill
                if skill.name not in self._skills:
                    self._register_skill(skill)

    def _refresh_registry_cache(self) -> None:
        """Re-fetch skills from all configured registries and update the cache.

        Called by :meth:`reload` when ``include_registries=True``.  Replaces
        ``_registry_skills`` with a freshly fetched snapshot; any registry that
        fails is skipped with a warning and its previous entries are removed
        from the cache.
        """
        new_cache: dict[str, Skill] = {}
        for registry in self._registries:
            try:
                registry_skills = registry.get_skills()
            except Exception as exc:
                warnings.warn(
                    f'Failed to load skills from registry {registry!r}: {exc}',
                    UserWarning,
                    stacklevel=2,
                )
                continue
            for skill in registry_skills:
                new_cache[skill.name] = skill
        self._registry_skills = new_cache

    def _build_resource_xml(self, resource: SkillResource) -> str:
        """Build XML representation of a resource.

        Args:
            resource: The resource to format.

        Returns:
            XML string representation of the resource.
        """
        res_xml = f'<resource name="{resource.name}"'
        if resource.description:
            res_xml += f' description="{resource.description}"'
        if resource.function and resource.function_schema:
            params_json = json.dumps(resource.function_schema.json_schema)
            res_xml += f' parameters={json.dumps(params_json)}'
        res_xml += ' />'
        return res_xml

    def _build_script_xml(self, script: SkillScript) -> str:
        """Build XML representation of a script.

        Args:
            script: The script to format.

        Returns:
            XML string representation of the script.
        """
        scr_xml = f'<script name="{script.name}"'
        if script.description:
            scr_xml += f' description="{script.description}"'
        if script.function and script.function_schema:
            params_json = json.dumps(script.function_schema.json_schema)
            scr_xml += f' parameters={json.dumps(params_json)}'
        scr_xml += ' />'
        return scr_xml

    def _find_skill_resource(self, skill: Skill, resource_name: str) -> SkillResource | None:
        """Find a resource in a skill by name.

        Args:
            skill: The skill to search in.
            resource_name: The resource name to find.

        Returns:
            The resource if found, None otherwise.
        """
        if not skill.resources:
            return None
        for r in skill.resources:
            if r.name == resource_name:
                return r
        return None

    def _find_skill_script(self, skill: Skill, script_name: str) -> SkillScript | None:
        """Find a script in a skill by name.

        Args:
            skill: The skill to search in.
            script_name: The script name to find.

        Returns:
            The script if found, None otherwise.
        """
        if not skill.scripts:
            return None
        for s in skill.scripts:
            if s.name == script_name:
                return s
        return None

    def _register_tools(self) -> None:
        """Register skill management tools with the toolset.

        This method registers skill management tools, excluding any specified in exclude_tools.
        Available tools: list_skills, load_skill, read_skill_resource, run_skill_script.
        """
        if 'list_skills' not in self._exclude_tools:
            self._register_list_skills()
        if 'load_skill' not in self._exclude_tools:
            self._register_load_skill()
        if 'read_skill_resource' not in self._exclude_tools:
            self._register_read_skill_resource()
        if 'run_skill_script' not in self._exclude_tools:
            self._register_run_skill_script()

    def _register_list_skills(self) -> None:
        """Register the list_skills tool."""

        @self.tool
        async def list_skills(_ctx: RunContext[Any]) -> dict[str, str]:  # pyright: ignore[reportUnusedFunction]
            """Get an overview of all available skills and what they do.

            Use this when you need to discover what skills exist or refresh your knowledge
            of available capabilities. Skills provide domain-specific knowledge and instructions
            for specialized tasks.

            Returns:
                Dictionary mapping skill names to their descriptions.
                Empty dictionary if no skills are available.
            """
            return {name: skill.description for name, skill in self._skills.items()}

    def _register_load_skill(self) -> None:
        """Register the load_skill tool."""

        @self.tool
        async def load_skill(ctx: RunContext[Any], skill_name: str) -> str:  # pyright: ignore[reportUnusedFunction]  # noqa: D417
            """Load complete instructions and capabilities for a specific skill.

            A skill contains detailed instructions, supplementary resources (like templates or
            reference docs), and executable scripts. Load a skill when you need to perform a
            task within its domain.

            Args:
                skill_name: Exact name from your available skills list.
                    Must match exactly (e.g., "data-analysis" not "data analysis").

            Returns:
                Structured documentation containing:
                - Skill name, description, and source location
                - Available resources: supplementary files with their parameters
                - Available scripts: executable programs with their parameters
                - Detailed instructions: step-by-step guidance for using the skill

            Important:
            - Read the entire instructions section before taking action
            - Call this before using `read_skill_resource` or `run_skill_script` for this skill
            - Resource and script names are authoritative - use exact names from the output
            - Do NOT infer or guess resource/script names
            - Check parameter schemas if resources or scripts require arguments
            """
            _ = ctx  # Required by Pydantic AI toolset protocol
            if skill_name not in self._skills:
                available = ', '.join(sorted(self._skills.keys())) or 'none'
                raise ModelRetry(
                    f"Skill '{skill_name}' not found. Available skills: {available}. "
                    'Call list_skills to see options and try again with an exact name.'
                )

            skill = self._skills[skill_name]

            # Build resources list with schemas for callable resources
            resources_parts: list[str] = []
            if skill.resources:
                for res in skill.resources:
                    resources_parts.append(self._build_resource_xml(res))
            resources_list = '\n'.join(resources_parts) if resources_parts else '<!-- No resources -->'

            # Build scripts list with schemas for callable scripts
            scripts_parts: list[str] = []
            if skill.scripts:
                for scr in skill.scripts:
                    scripts_parts.append(self._build_script_xml(scr))
            scripts_list = '\n'.join(scripts_parts) if scripts_parts else '<!-- No scripts -->'

            # Format response
            return LOAD_SKILL_TEMPLATE.format(
                skill_name=skill.name,
                description=skill.description,
                uri=skill.uri or 'N/A',
                resources_list=resources_list,
                scripts_list=scripts_list,
                content=skill.content,
            )

    def _register_read_skill_resource(self) -> None:
        """Register the read_skill_resource tool."""

        @self.tool
        async def read_skill_resource(  # pyright: ignore[reportUnusedFunction]  # noqa: D417
            ctx: RunContext[Any],
            skill_name: str,
            resource_name: str,
            args: dict[str, Any] | None = None,
        ) -> str:
            """Access supplementary documentation, templates, or data from a skill.

            Resources are additional files that support skill execution. They can be static
            content (markdown docs, templates, schemas) or dynamic callables (functions that
            generate content based on parameters).

            When to use this:
            - When a skill's instructions reference a specific resource
            - To access form templates, reference documentation, or data schemas
            - When you need supplementary information beyond the skill instructions

            Args:
                skill_name: Name of the skill containing the resource.
                resource_name: Exact name of the resource as listed in the skill.
                    Examples: "FORMS.md", "REFERENCE.md", "get_schema"
                    Must match exactly - do not infer or guess.
                args: Arguments for callable resources (optional for static files).
                    Keys must match the parameter names in the resource's schema.

            Returns:
                The resource content as a string.

            Important:
            - Always call `load_skill(skill_name)` first in this run
            - Get resource names from the skill's documentation first
            - Use exact resource names - do not modify or guess
            - Check if the resource requires arguments (check its schema)
            - Static files don't need args; callables may require them
            """
            if skill_name not in self._skills:
                available = ', '.join(sorted(self._skills.keys())) or 'none'
                raise ModelRetry(
                    f"Skill '{skill_name}' not found. Available skills: {available}. "
                    'Call list_skills first and try again with an exact name.'
                )

            skill = self._skills[skill_name]

            # Find the resource
            resource = self._find_skill_resource(skill, resource_name)

            if resource is None:
                available_resources = [r.name for r in skill.resources] if skill.resources else []
                raise ModelRetry(
                    f"Resource '{resource_name}' not found in skill '{skill_name}'. "
                    f'Available resources: {available_resources}. Use the exact name from load_skill output.'
                )

            # Use resource.load() interface - implementation handles the details
            return await resource.load(ctx=ctx, args=args)

    def _register_run_skill_script(self) -> None:
        """Register the run_skill_script tool."""

        @self.tool
        async def run_skill_script(  # pyright: ignore[reportUnusedFunction]  # noqa: D417
            ctx: RunContext[Any],
            skill_name: str,
            script_name: str,
            args: Annotated[dict[str, Any] | None, BeforeValidator(_coerce_to_dict)] = None,
        ) -> str:
            """Execute a skill script that performs actions or computations.

            Scripts are executable programs provided by skills that can perform actions
            (API calls, file operations), process data (transformations, analysis), or
            generate outputs (reports, visualizations).

            When to use this:
            - When a skill's instructions tell you to run a specific script
            - To perform automated tasks that the skill provides
            - For data processing, API interactions, or file operations

            Args:
                skill_name: Name of the skill containing the script.
                script_name: Exact name of the script as listed in the skill.
                    Examples: "analyze.py", "scripts/analyze.py", "scripts/deploy.sh", "scripts/runner"
                    Must match exactly - do not infer or guess.
                args: Arguments required by the script.
                    Keys must match the parameter names in the script's schema.

            Returns:
                Script execution output including stdout and stderr.

            Important:
            - Always call `load_skill(skill_name)` first in this run
            - Get script names from the skill's documentation first
            - Use exact script names - do not modify or guess
            - Check the script's parameter schema for required arguments
            - Review skill instructions before running scripts
            - Scripts may modify external state (files, databases, APIs)
            - Execution errors are included in the output
            """
            if skill_name not in self._skills:
                available = ', '.join(sorted(self._skills.keys())) or 'none'
                raise ModelRetry(
                    f"Skill '{skill_name}' not found. Available skills: {available}. "
                    'Call list_skills first and try again with an exact name.'
                )

            skill = self._skills[skill_name]

            # Find the script
            script = self._find_skill_script(skill, script_name)

            if script is None:
                available_scripts = [s.name for s in skill.scripts] if skill.scripts else []
                raise ModelRetry(
                    f"Script '{script_name}' not found in skill '{skill_name}'. "
                    f'Available scripts: {available_scripts}. Use the exact name from load_skill output.'
                )

            # Use script.run() interface - implementation handles the details
            return await script.run(ctx=ctx, args=args)

    async def get_instructions(self, ctx: RunContext[Any]) -> str | None:
        """Return instructions to inject into the agent's system prompt.

        Returns the skills system prompt containing usage guidance and all skill metadata.
        When ``auto_reload=True`` was set, re-discovers skills from disk before building
        the prompt so that any edits made since the last run are immediately visible.

        Args:
            ctx: The run context for this agent run.

        Returns:
            The skills system prompt, or None if no skills are loaded.
        """
        if self._auto_reload:
            self.reload()

        if not self._skills:
            return None

        # Build skills list in XML format
        skills_list_lines: list[str] = []
        for skill in sorted(self._skills.values(), key=lambda s: s.name):
            skills_list_lines.append('<skill>')
            skills_list_lines.append(f'<name>{skill.name}</name>')
            skills_list_lines.append(f'<description>{skill.description}</description>')
            if skill.uri:
                skills_list_lines.append(f'<uri>{skill.uri}</uri>')
            skills_list_lines.append('</skill>')
        skills_list = '\n'.join(skills_list_lines)

        # Use custom template if provided, otherwise use default
        if self._instruction_template:
            return self._instruction_template.format(skills_list=skills_list)

        return _INSTRUCTION_SKILLS_HEADER.format(skills_list=skills_list)

    def skill(
        self,
        func: Callable[[], str] | None = None,
        *,
        name: str | None = None,
        description: str | None = None,
        license: str | None = None,
        compatibility: str | None = None,
        metadata: dict[str, Any] | None = None,
        resources: list[SkillResource] | None = None,
        scripts: list[SkillScript] | None = None,
    ) -> Any:
        """Decorator to define a skill using a function.

        The decorated function should return a string containing the skill's instructions/content.
        The skill name is derived from the function name (underscores replaced with hyphens)
        unless explicitly provided via the `name` parameter.

        Example:
            ```python
            from pydantic_ai import RunContext
            from pydantic_ai_skills import SkillsToolset

            skills = SkillsToolset()

            @skills.skill(resources=[], metadata={'version': '1.0'})
            def data_analyzer() -> str:
                '''Analyze data from various sources.'''
                return '''
                Use this skill for data analysis tasks.
                The skill provides tools for querying and analyzing data.
                '''

            @data_analyzer.resource
            async def get_schema(ctx: RunContext[MyDeps]) -> str:
                return await ctx.deps.database.get_schema()

            @data_analyzer.script
            async def run_analysis(ctx: RunContext[MyDeps], query: str) -> str:
                result = await ctx.deps.database.execute(query)
                return str(result)
            ```

        Args:
            func: The function that returns skill content (must return str).
            name: Skill name (defaults to normalized function name: underscores → hyphens).
            description: Skill description (inferred from docstring if not provided).
            license: Optional license information (e.g., "Apache-2.0").
            compatibility: Optional environment requirements (e.g., "Requires Python 3.10+").
            metadata: Additional metadata fields as a dictionary.
            resources: Initial list of resources to attach to the skill.
            scripts: Initial list of scripts to attach to the skill.

        Returns:
            A SkillWrapper instance that can be used to attach resources and scripts.
        """

        def decorator(f: Callable[[], str]) -> SkillWrapper[Any]:
            # Derive name from function name if not provided
            if name is not None:
                # Explicit name provided - validate it directly without normalization
                skill_name = name
                # Validate the explicit name
                if not SKILL_NAME_PATTERN.match(skill_name):
                    raise ValueError(
                        f"Skill name '{skill_name}' is invalid. "
                        'Skill names must contain only lowercase letters, numbers, and hyphens '
                        '(no consecutive hyphens).'
                    )
                if len(skill_name) > 64:
                    raise ValueError(f"Skill name '{skill_name}' exceeds 64 characters ({len(skill_name)} chars).")
            else:
                # Derive and normalize from function name
                skill_name = normalize_skill_name(f.__name__)

            # Extract description from docstring if not provided
            skill_description = description
            if skill_description is None:
                sig = get_signature(f)
                desc, _ = doc_descriptions(f, sig, docstring_format='auto')
                skill_description = desc

            # Create the skill wrapper
            wrapper: SkillWrapper[Any] = SkillWrapper(
                function=f,
                name=skill_name,
                description=skill_description,
                license=license,
                compatibility=compatibility,
                metadata=metadata,
                resources=list(resources) if resources else [],
                scripts=list(scripts) if scripts else [],
            )

            # Convert to Skill once to avoid calling the function twice
            skill = wrapper.to_skill()
            self._register_skill(skill)

            # Track as programmatic so it survives reload()
            self._programmatic_skills.append(skill)

            # Return the wrapper so resources/scripts can be attached
            return wrapper

        if func is None:
            # Called with arguments: @skills.skill(name="custom")
            return decorator
        else:
            # Called without arguments: @skills.skill
            return decorator(func)

    def reload(self, *, include_registries: bool = False) -> None:
        """Re-discover skills from all configured sources.

        Re-scans all configured directories for SKILL.md changes and re-applies
        programmatic skills. Useful for long-lived servers where skill files may be
        edited (by the agent itself, a git-sync job, or a human) without restarting
        the process.

        Priority after reload (same as initial load):

        1. Programmatic skills (``skills=`` param and ``@toolset.skill`` decorated
           functions) — always applied first; directory skills with the same name
           are silently skipped.
        2. Directory skills — fresh filesystem scan via
           :meth:`~pydantic_ai_skills.SkillsDirectory.get_skills`.
        3. Registry skills — always re-applied from the in-memory cache
           (populated at init time); pass ``include_registries=True`` to
           re-fetch from registries and refresh that cache.

        Args:
            include_registries: Whether to re-fetch skills from configured
                registries (e.g. :class:`~pydantic_ai_skills.registries.GitSkillsRegistry`)
                and refresh the registry cache.  Defaults to ``False`` because
                registry operations often involve network or git calls and would
                be unexpectedly slow when called on every agent run.

        Example:
            ```python
            # Manual reload after an external git-sync
            skills_toolset = SkillsToolset(directories=[WORKSPACE / "skills"])

            async def lifespan(app):
                await git_sync()
                skills_toolset.reload()
                yield

            # Automatic reload before every agent run
            skills_toolset = SkillsToolset(
                directories=[WORKSPACE / "skills"],
                auto_reload=True,
            )
            ```
        """
        # Build a new dict atomically to avoid transient empty/partial state visible
        # to concurrent callers.
        new_skills: dict[str, Skill] = {}

        # 1. Highest priority: programmatic skills (always preserved)
        for skill in self._programmatic_skills:
            if self._is_selected(skill.name):
                new_skills[skill.name] = skill

        # 2. Directory skills — programmatic names are protected inside the helper
        self._collect_dir_skills_into(new_skills)

        # 3. Optionally re-fetch registry cache (network/git call)
        if include_registries:
            self._refresh_registry_cache()

        # 4. Lowest priority: registry cache (never overrides higher-priority skills)
        for skill_name, skill in self._registry_skills.items():
            if skill_name not in new_skills and self._is_selected(skill_name):
                new_skills[skill_name] = skill

        # Atomically replace the skills mapping once fully populated
        self._skills = new_skills

    def _register_skill(self, skill: Skill | SkillWrapper[Any]) -> None:
        """Register a skill with the toolset.

        Converts SkillWrapper instances to Skill dataclasses before registering.
        Warns about duplicate skill names (last occurrence wins).

        Args:
            skill: Skill or SkillWrapper instance to register.
        """
        # Convert SkillWrapper to Skill if needed
        if isinstance(skill, SkillWrapper):
            skill = skill.to_skill()

        if not self._is_selected(skill.name):
            return

        # Warn about duplicates
        if skill.name in self._skills:
            warnings.warn(
                f"Duplicate skill '{skill.name}' found. Overriding previous occurrence.",
                UserWarning,
                stacklevel=3,
            )

        # Register the skill
        self._skills[skill.name] = skill

__init__

__init__(*, skills: list[Skill] | None = None, directories: list[str | Path | SkillsDirectory] | None = None, registries: list[SkillRegistry] | None = None, validate: bool = True, max_depth: int | None = 3, exclude_resources: Iterable[str] | None = None, id: str | None = None, instruction_template: str | None = None, include: Collection[str] | None = None, exclude: Collection[str] | None = None, exclude_tools: set[str] | list[str] | None = None, auto_reload: bool = False, max_retries: int = 1) -> None

Initialize the skills toolset.

Parameters:

Name Type Description Default
skills list[Skill] | None

List of pre-loaded Skill objects. Can be combined with directories.

None
directories list[str | Path | SkillsDirectory] | None

List of directories or SkillsDirectory instances to discover skills from. Can be combined with skills. If both are None, defaults to ["./skills"]. String/Path entries are converted to SkillsDirectory instances.

None
registries list[SkillRegistry] | None

List of SkillRegistry instances (e.g. GitSkillsRegistry) to load skills from. Registry skills are fetched lazily on the first async call (get_instructions or any tool invocation). Can be combined with skills and directories.

None
validate bool

Validate skill structure during discovery (used when creating SkillsDirectory from str/Path).

True
max_depth int | None

Maximum depth for skill discovery (None for unlimited, used when creating SkillsDirectory from str/Path).

3
exclude_resources Iterable[str] | None

Extra glob patterns to exclude from resource discovery, in addition to the built-in defaults (__pycache__, *.pyc, .DS_Store …). Used when creating SkillsDirectory from str/Path. Any readable text file not excluded and not discovered as a script becomes a resource. None for defaults only.

None
id str | None

Unique identifier for this toolset.

None
instruction_template str | None

Custom instruction template for skills system prompt. Must include {skills_list} placeholder. If None, uses default template. Tool usage guidance is provided in the tool docstrings themselves.

None
include Collection[str] | None

Exact skill names to expose. When provided, every other discovered skill is omitted from the catalog. Cannot be combined with exclude. Pass an empty collection to expose no skills. Unknown names raise ValueError.

None
exclude Collection[str] | None

Exact skill names to omit from the catalog. Cannot be combined with include. Unknown names raise ValueError.

None
exclude_tools set[str] | list[str] | None

Set or list of tool names to exclude from registration (e.g., ['run_skill_script']). Useful for security or capability restrictions such as disabling script execution. Valid tool names: 'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'.

None
auto_reload bool

If True, automatically re-scan all configured directories before each agent run by calling :meth:reload inside :meth:get_instructions. Useful for long-lived servers where skill files may be edited at runtime. Programmatic skills defined via skills= or @toolset.skill are always preserved. Registry skills are preserved from the initial load cache (no network calls are made on each run). To re-fetch fresh skills from registries, call :meth:reload with include_registries=True explicitly. Defaults to False.

False
max_retries int

Maximum number of times the model is allowed to retry a tool call when the tool raises ModelRetry (e.g. when the LLM passes an unknown skill_name, resource_name, or script_name). Forwarded to :class:pydantic_ai.toolsets.FunctionToolset so every registered tool inherits this retry budget. Defaults to 1 (matching Pydantic AI's default).

1
Example
# Default: uses ./skills directory
toolset = SkillsToolset()

# Multiple directories
toolset = SkillsToolset(directories=["./skills", "./more-skills"])

# Programmatic skills
toolset = SkillsToolset(skills=[skill1, skill2])

# Combined mode
toolset = SkillsToolset(
    skills=[skill1, skill2],
    directories=["./skills", skills_dir_instance]
)

# Using SkillsDirectory instances directly
dir1 = SkillsDirectory(path="./skills")
toolset = SkillsToolset(directories=[dir1])

# Expose only a subset of the discovered skills
toolset = SkillsToolset(directories=["./skills"], include=['arxiv-search'])

# Expose everything except one skill
toolset = SkillsToolset(directories=["./skills"], exclude=['web-research'])

# Excluding specific tools (disable script execution with a set)
toolset = SkillsToolset(exclude_tools=['run_skill_script'])

# Auto-reload: re-scan directories before every agent run
toolset = SkillsToolset(directories=['./skills'], auto_reload=True)

# Git registry: clone a remote repo and load skills
from pydantic_ai_skills.registries.git import GitSkillsRegistry
registry = GitSkillsRegistry(
    repo_url="https://github.com/anthropics/skills",
    path="skills",
)
toolset = SkillsToolset(registries=[registry])
Source code in pydantic_ai_skills/toolset.py
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
def __init__(
    self,
    *,
    skills: list[Skill] | None = None,
    directories: list[str | Path | SkillsDirectory] | None = None,
    registries: list[SkillRegistry] | None = None,
    validate: bool = True,
    max_depth: int | None = 3,
    exclude_resources: Iterable[str] | None = None,
    id: str | None = None,
    instruction_template: str | None = None,
    include: Collection[str] | None = None,
    exclude: Collection[str] | None = None,
    exclude_tools: set[str] | list[str] | None = None,
    auto_reload: bool = False,
    max_retries: int = 1,
) -> None:
    """Initialize the skills toolset.

    Args:
        skills: List of pre-loaded Skill objects. Can be combined with `directories`.
        directories: List of directories or SkillsDirectory instances to discover skills from.
            Can be combined with `skills`. If both are None, defaults to ["./skills"].
            String/Path entries are converted to SkillsDirectory instances.
        registries: List of SkillRegistry instances (e.g. GitSkillsRegistry) to load
            skills from. Registry skills are fetched lazily on the first async call
            (``get_instructions`` or any tool invocation). Can be combined with
            ``skills`` and ``directories``.
        validate: Validate skill structure during discovery (used when creating SkillsDirectory from str/Path).
        max_depth: Maximum depth for skill discovery (None for unlimited, used when creating SkillsDirectory from str/Path).
        exclude_resources: Extra glob patterns to exclude from resource discovery, in addition to the
            built-in defaults (``__pycache__``, ``*.pyc``, ``.DS_Store`` …). Used when creating
            SkillsDirectory from str/Path. Any readable text file not excluded and not discovered as a
            script becomes a resource. None for defaults only.
        id: Unique identifier for this toolset.
        instruction_template: Custom instruction template for skills system prompt.
            Must include `{skills_list}` placeholder. If None, uses default template.
            Tool usage guidance is provided in the tool docstrings themselves.
        include: Exact skill names to expose. When provided, every other discovered skill is
            omitted from the catalog. Cannot be combined with ``exclude``. Pass an empty
            collection to expose no skills. Unknown names raise ``ValueError``.
        exclude: Exact skill names to omit from the catalog. Cannot be combined with
            ``include``. Unknown names raise ``ValueError``.
        exclude_tools: Set or list of tool names to exclude from registration (e.g., ['run_skill_script']).
            Useful for security or capability restrictions such as disabling script execution.
            Valid tool names: 'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'.
        auto_reload: If True, automatically re-scan all configured directories before each
            agent run by calling :meth:`reload` inside :meth:`get_instructions`. Useful for
            long-lived servers where skill files may be edited at runtime. Programmatic skills
            defined via ``skills=`` or ``@toolset.skill`` are always preserved. Registry
            skills are preserved from the initial load cache (no network calls are made on
            each run). To re-fetch fresh skills from registries, call :meth:`reload` with
            ``include_registries=True`` explicitly. Defaults to False.
        max_retries: Maximum number of times the model is allowed to retry a tool call when
            the tool raises ``ModelRetry`` (e.g. when the LLM passes an unknown
            ``skill_name``, ``resource_name``, or ``script_name``). Forwarded to
            :class:`pydantic_ai.toolsets.FunctionToolset` so every registered tool inherits
            this retry budget. Defaults to 1 (matching Pydantic AI's default).

    Example:
        ```python
        # Default: uses ./skills directory
        toolset = SkillsToolset()

        # Multiple directories
        toolset = SkillsToolset(directories=["./skills", "./more-skills"])

        # Programmatic skills
        toolset = SkillsToolset(skills=[skill1, skill2])

        # Combined mode
        toolset = SkillsToolset(
            skills=[skill1, skill2],
            directories=["./skills", skills_dir_instance]
        )

        # Using SkillsDirectory instances directly
        dir1 = SkillsDirectory(path="./skills")
        toolset = SkillsToolset(directories=[dir1])

        # Expose only a subset of the discovered skills
        toolset = SkillsToolset(directories=["./skills"], include=['arxiv-search'])

        # Expose everything except one skill
        toolset = SkillsToolset(directories=["./skills"], exclude=['web-research'])

        # Excluding specific tools (disable script execution with a set)
        toolset = SkillsToolset(exclude_tools=['run_skill_script'])

        # Auto-reload: re-scan directories before every agent run
        toolset = SkillsToolset(directories=['./skills'], auto_reload=True)

        # Git registry: clone a remote repo and load skills
        from pydantic_ai_skills.registries.git import GitSkillsRegistry
        registry = GitSkillsRegistry(
            repo_url="https://github.com/anthropics/skills",
            path="skills",
        )
        toolset = SkillsToolset(registries=[registry])
        ```
    """
    super().__init__(id=id, max_retries=max_retries)

    self._instruction_template = instruction_template

    self._init_selection(include, exclude)

    # Validate and initialize exclude_tools
    valid_tools = {'list_skills', 'load_skill', 'read_skill_resource', 'run_skill_script'}
    self._exclude_tools: set[str] = set(exclude_tools or [])
    invalid = self._exclude_tools - valid_tools
    if invalid:
        raise ValueError(f'Unknown tools: {invalid}. Valid: {valid_tools}')

    if 'load_skill' in self._exclude_tools:
        warnings.warn(
            "'load_skill' is a critical tool for skills usage and has been excluded. "
            'Agents will not be able to load skill instructions, which severely limits skill functionality.',
            UserWarning,
            stacklevel=2,
        )

    self._auto_reload = auto_reload

    # Initialize the skills dict and directories list (for refresh)
    self._skills: dict[str, Skill] = {}
    self._programmatic_skills: list[Skill] = []
    self._skill_directories: list[SkillsDirectory] = []
    self._registries: list[SkillRegistry] = list(registries) if registries else []
    self._registry_skills: dict[str, Skill] = {}  # Cache of registry-sourced skills
    self._validate = validate
    self._max_depth = max_depth
    self._exclude_resources = exclude_resources

    # Load programmatic skills first (highest priority)
    if skills is not None:
        for skill in skills:
            self._programmatic_skills.append(skill)
            self._register_skill(skill)

    # Load directory-based skills (second priority)
    if directories is not None:
        self._load_directory_skills(directories)
    elif skills is None and not self._registries:
        # Default: ./skills directory (only if no skills or registries provided)
        default_dir = Path('./skills')
        if not default_dir.exists():
            warnings.warn(
                f"Default skills directory '{default_dir}' does not exist. No skills will be loaded.",
                UserWarning,
                stacklevel=2,
            )
        else:
            self._load_directory_skills([default_dir])

    # Load registry skills (lowest priority — won't override existing)
    self._load_registry_skills()

    # Surface typos in include/exclude once every source has been scanned
    self._validate_selection()

    # Register tools
    self._register_tools()

skills property

skills: dict[str, Skill]

Get the dictionary of loaded skills.

Returns:

Type Description
dict[str, Skill]

Dictionary mapping skill names to Skill objects.

get_skill

get_skill(name: str) -> Skill

Get a specific skill by name.

Parameters:

Name Type Description Default
name str

Name of the skill to get.

required

Returns:

Type Description
Skill

The requested Skill object.

Raises:

Type Description
KeyError

If skill is not found.

Source code in pydantic_ai_skills/toolset.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def get_skill(self, name: str) -> Skill:
    """Get a specific skill by name.

    Args:
        name: Name of the skill to get.

    Returns:
        The requested Skill object.

    Raises:
        KeyError: If skill is not found.
    """
    if name not in self._skills:
        available = ', '.join(sorted(self._skills.keys())) or 'none'
        raise KeyError(f"Skill '{name}' not found. Available: {available}")
    return self._skills[name]

get_instructions async

get_instructions(ctx: RunContext[Any]) -> str | None

Return instructions to inject into the agent's system prompt.

Returns the skills system prompt containing usage guidance and all skill metadata. When auto_reload=True was set, re-discovers skills from disk before building the prompt so that any edits made since the last run are immediately visible.

Parameters:

Name Type Description Default
ctx RunContext[Any]

The run context for this agent run.

required

Returns:

Type Description
str | None

The skills system prompt, or None if no skills are loaded.

Source code in pydantic_ai_skills/toolset.py
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
async def get_instructions(self, ctx: RunContext[Any]) -> str | None:
    """Return instructions to inject into the agent's system prompt.

    Returns the skills system prompt containing usage guidance and all skill metadata.
    When ``auto_reload=True`` was set, re-discovers skills from disk before building
    the prompt so that any edits made since the last run are immediately visible.

    Args:
        ctx: The run context for this agent run.

    Returns:
        The skills system prompt, or None if no skills are loaded.
    """
    if self._auto_reload:
        self.reload()

    if not self._skills:
        return None

    # Build skills list in XML format
    skills_list_lines: list[str] = []
    for skill in sorted(self._skills.values(), key=lambda s: s.name):
        skills_list_lines.append('<skill>')
        skills_list_lines.append(f'<name>{skill.name}</name>')
        skills_list_lines.append(f'<description>{skill.description}</description>')
        if skill.uri:
            skills_list_lines.append(f'<uri>{skill.uri}</uri>')
        skills_list_lines.append('</skill>')
    skills_list = '\n'.join(skills_list_lines)

    # Use custom template if provided, otherwise use default
    if self._instruction_template:
        return self._instruction_template.format(skills_list=skills_list)

    return _INSTRUCTION_SKILLS_HEADER.format(skills_list=skills_list)

skill

skill(func: Callable[[], str] | None = None, *, name: str | None = None, description: str | None = None, license: str | None = None, compatibility: str | None = None, metadata: dict[str, Any] | None = None, resources: list[SkillResource] | None = None, scripts: list[SkillScript] | None = None) -> Any

Decorator to define a skill using a function.

The decorated function should return a string containing the skill's instructions/content. The skill name is derived from the function name (underscores replaced with hyphens) unless explicitly provided via the name parameter.

Example
from pydantic_ai import RunContext
from pydantic_ai_skills import SkillsToolset

skills = SkillsToolset()

@skills.skill(resources=[], metadata={'version': '1.0'})
def data_analyzer() -> str:
    '''Analyze data from various sources.'''
    return '''
    Use this skill for data analysis tasks.
    The skill provides tools for querying and analyzing data.
    '''

@data_analyzer.resource
async def get_schema(ctx: RunContext[MyDeps]) -> str:
    return await ctx.deps.database.get_schema()

@data_analyzer.script
async def run_analysis(ctx: RunContext[MyDeps], query: str) -> str:
    result = await ctx.deps.database.execute(query)
    return str(result)

Parameters:

Name Type Description Default
func Callable[[], str] | None

The function that returns skill content (must return str).

None
name str | None

Skill name (defaults to normalized function name: underscores → hyphens).

None
description str | None

Skill description (inferred from docstring if not provided).

None
license str | None

Optional license information (e.g., "Apache-2.0").

None
compatibility str | None

Optional environment requirements (e.g., "Requires Python 3.10+").

None
metadata dict[str, Any] | None

Additional metadata fields as a dictionary.

None
resources list[SkillResource] | None

Initial list of resources to attach to the skill.

None
scripts list[SkillScript] | None

Initial list of scripts to attach to the skill.

None

Returns:

Type Description
Any

A SkillWrapper instance that can be used to attach resources and scripts.

Source code in pydantic_ai_skills/toolset.py
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
def skill(
    self,
    func: Callable[[], str] | None = None,
    *,
    name: str | None = None,
    description: str | None = None,
    license: str | None = None,
    compatibility: str | None = None,
    metadata: dict[str, Any] | None = None,
    resources: list[SkillResource] | None = None,
    scripts: list[SkillScript] | None = None,
) -> Any:
    """Decorator to define a skill using a function.

    The decorated function should return a string containing the skill's instructions/content.
    The skill name is derived from the function name (underscores replaced with hyphens)
    unless explicitly provided via the `name` parameter.

    Example:
        ```python
        from pydantic_ai import RunContext
        from pydantic_ai_skills import SkillsToolset

        skills = SkillsToolset()

        @skills.skill(resources=[], metadata={'version': '1.0'})
        def data_analyzer() -> str:
            '''Analyze data from various sources.'''
            return '''
            Use this skill for data analysis tasks.
            The skill provides tools for querying and analyzing data.
            '''

        @data_analyzer.resource
        async def get_schema(ctx: RunContext[MyDeps]) -> str:
            return await ctx.deps.database.get_schema()

        @data_analyzer.script
        async def run_analysis(ctx: RunContext[MyDeps], query: str) -> str:
            result = await ctx.deps.database.execute(query)
            return str(result)
        ```

    Args:
        func: The function that returns skill content (must return str).
        name: Skill name (defaults to normalized function name: underscores → hyphens).
        description: Skill description (inferred from docstring if not provided).
        license: Optional license information (e.g., "Apache-2.0").
        compatibility: Optional environment requirements (e.g., "Requires Python 3.10+").
        metadata: Additional metadata fields as a dictionary.
        resources: Initial list of resources to attach to the skill.
        scripts: Initial list of scripts to attach to the skill.

    Returns:
        A SkillWrapper instance that can be used to attach resources and scripts.
    """

    def decorator(f: Callable[[], str]) -> SkillWrapper[Any]:
        # Derive name from function name if not provided
        if name is not None:
            # Explicit name provided - validate it directly without normalization
            skill_name = name
            # Validate the explicit name
            if not SKILL_NAME_PATTERN.match(skill_name):
                raise ValueError(
                    f"Skill name '{skill_name}' is invalid. "
                    'Skill names must contain only lowercase letters, numbers, and hyphens '
                    '(no consecutive hyphens).'
                )
            if len(skill_name) > 64:
                raise ValueError(f"Skill name '{skill_name}' exceeds 64 characters ({len(skill_name)} chars).")
        else:
            # Derive and normalize from function name
            skill_name = normalize_skill_name(f.__name__)

        # Extract description from docstring if not provided
        skill_description = description
        if skill_description is None:
            sig = get_signature(f)
            desc, _ = doc_descriptions(f, sig, docstring_format='auto')
            skill_description = desc

        # Create the skill wrapper
        wrapper: SkillWrapper[Any] = SkillWrapper(
            function=f,
            name=skill_name,
            description=skill_description,
            license=license,
            compatibility=compatibility,
            metadata=metadata,
            resources=list(resources) if resources else [],
            scripts=list(scripts) if scripts else [],
        )

        # Convert to Skill once to avoid calling the function twice
        skill = wrapper.to_skill()
        self._register_skill(skill)

        # Track as programmatic so it survives reload()
        self._programmatic_skills.append(skill)

        # Return the wrapper so resources/scripts can be attached
        return wrapper

    if func is None:
        # Called with arguments: @skills.skill(name="custom")
        return decorator
    else:
        # Called without arguments: @skills.skill
        return decorator(func)

reload

reload(*, include_registries: bool = False) -> None

Re-discover skills from all configured sources.

Re-scans all configured directories for SKILL.md changes and re-applies programmatic skills. Useful for long-lived servers where skill files may be edited (by the agent itself, a git-sync job, or a human) without restarting the process.

Priority after reload (same as initial load):

  1. Programmatic skills (skills= param and @toolset.skill decorated functions) — always applied first; directory skills with the same name are silently skipped.
  2. Directory skills — fresh filesystem scan via :meth:~pydantic_ai_skills.SkillsDirectory.get_skills.
  3. Registry skills — always re-applied from the in-memory cache (populated at init time); pass include_registries=True to re-fetch from registries and refresh that cache.

Parameters:

Name Type Description Default
include_registries bool

Whether to re-fetch skills from configured registries (e.g. :class:~pydantic_ai_skills.registries.GitSkillsRegistry) and refresh the registry cache. Defaults to False because registry operations often involve network or git calls and would be unexpectedly slow when called on every agent run.

False
Example
# Manual reload after an external git-sync
skills_toolset = SkillsToolset(directories=[WORKSPACE / "skills"])

async def lifespan(app):
    await git_sync()
    skills_toolset.reload()
    yield

# Automatic reload before every agent run
skills_toolset = SkillsToolset(
    directories=[WORKSPACE / "skills"],
    auto_reload=True,
)
Source code in pydantic_ai_skills/toolset.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
def reload(self, *, include_registries: bool = False) -> None:
    """Re-discover skills from all configured sources.

    Re-scans all configured directories for SKILL.md changes and re-applies
    programmatic skills. Useful for long-lived servers where skill files may be
    edited (by the agent itself, a git-sync job, or a human) without restarting
    the process.

    Priority after reload (same as initial load):

    1. Programmatic skills (``skills=`` param and ``@toolset.skill`` decorated
       functions) — always applied first; directory skills with the same name
       are silently skipped.
    2. Directory skills — fresh filesystem scan via
       :meth:`~pydantic_ai_skills.SkillsDirectory.get_skills`.
    3. Registry skills — always re-applied from the in-memory cache
       (populated at init time); pass ``include_registries=True`` to
       re-fetch from registries and refresh that cache.

    Args:
        include_registries: Whether to re-fetch skills from configured
            registries (e.g. :class:`~pydantic_ai_skills.registries.GitSkillsRegistry`)
            and refresh the registry cache.  Defaults to ``False`` because
            registry operations often involve network or git calls and would
            be unexpectedly slow when called on every agent run.

    Example:
        ```python
        # Manual reload after an external git-sync
        skills_toolset = SkillsToolset(directories=[WORKSPACE / "skills"])

        async def lifespan(app):
            await git_sync()
            skills_toolset.reload()
            yield

        # Automatic reload before every agent run
        skills_toolset = SkillsToolset(
            directories=[WORKSPACE / "skills"],
            auto_reload=True,
        )
        ```
    """
    # Build a new dict atomically to avoid transient empty/partial state visible
    # to concurrent callers.
    new_skills: dict[str, Skill] = {}

    # 1. Highest priority: programmatic skills (always preserved)
    for skill in self._programmatic_skills:
        if self._is_selected(skill.name):
            new_skills[skill.name] = skill

    # 2. Directory skills — programmatic names are protected inside the helper
    self._collect_dir_skills_into(new_skills)

    # 3. Optionally re-fetch registry cache (network/git call)
    if include_registries:
        self._refresh_registry_cache()

    # 4. Lowest priority: registry cache (never overrides higher-priority skills)
    for skill_name, skill in self._registry_skills.items():
        if skill_name not in new_skills and self._is_selected(skill_name):
            new_skills[skill_name] = skill

    # Atomically replace the skills mapping once fully populated
    self._skills = new_skills

options: members: - init - get_instructions - get_skill - skills show_source: true heading_level: 2

Constructor Parameters

The SkillsToolset.__init__() accepts the following parameters:

Parameter Type Default Description
skills list[Skill] \| None None Pre-loaded Skill objects. Can be combined with directories.
directories list[str \| Path \| SkillsDirectory] \| None None Directories or SkillsDirectory instances to discover skills from. Defaults to ["./skills"] if neither skills nor directories provided.
registries list[SkillRegistry] \| None None List of SkillRegistry instances (e.g. GitSkillsRegistry) to load skills from. Can be combined with skills and directories. Registries have the lowest priority.
validate bool True Validate skill structure during discovery. Used when creating SkillsDirectory from str/Path entries.
max_depth int \| None 3 Maximum depth for skill discovery. None for unlimited depth. Used when creating SkillsDirectory from str/Path entries.
id str \| None None Unique identifier for this toolset.
instruction_template str \| None None Custom instruction template for skills system prompt. Must include {skills_list} placeholder. If None, uses default template.
max_retries int 1 Maximum number of times the model is allowed to retry a tool call when the tool raises ModelRetry (e.g. unknown skill / resource / script name). Forwarded to FunctionToolset so every registered tool inherits this retry budget.

Properties

Property Type Description
skills dict[str, Skill] Dictionary of all available skills, keyed by skill name.

Methods

Method Description
get_skill(skill_name: str) -> Skill Retrieve a specific skill by name. Raises KeyError if not found.
get_instructions(ctx: RunContext[Any]) -> str | None Returns formatted system prompt with skills instructions, or None if no skills are loaded. Called automatically by the agent.

Usage Examples

Initialize with File-Based Skills

from pydantic_ai_skills import SkillsToolset

# Basic initialization - defaults to ./skills directory
toolset = SkillsToolset()

# Explicit single directory
toolset = SkillsToolset(directories=["./skills"])

# Multiple directories
toolset = SkillsToolset(
    directories=["./skills", "./shared", "./custom"],
    validate=True,
    max_depth=3,
    id="my-skills"
)

# Using SkillsDirectory instances directly
from pydantic_ai_skills import SkillsDirectory

skills_dir = SkillsDirectory(
    path="./skills",
    validate=True,
    max_depth=3
)
toolset = SkillsToolset(directories=[skills_dir])

Initialize with Git Registry

from pydantic_ai_skills import SkillsToolset
from pydantic_ai_skills.registries import GitSkillsRegistry, GitCloneOptions

# Clone a remote Git repository and load its skills
registry = GitSkillsRegistry(
    repo_url='https://github.com/anthropics/skills',
    path='skills',
    target_dir='./anthropics-skills',
    clone_options=GitCloneOptions(depth=1, single_branch=True),
)

toolset = SkillsToolset(registries=[registry])

# Combine with local skills
toolset = SkillsToolset(
    directories=['./skills'],
    registries=[registry],
)

See Skill Registries for composition patterns (filtering, prefixing, combining).

Initialize with Programmatic Skills

from pydantic_ai import RunContext
from pydantic_ai_skills import Skill, SkillsToolset

# Create a simple programmatic skill
my_skill = Skill(
    name='custom-skill',
    description='Custom programmatic skill',
    content='Instructions for this skill...'
)

# Initialize toolset with programmatic skill
toolset = SkillsToolset(skills=[my_skill])

# Use the @skill() decorator to define skills inline
skills = SkillsToolset()

@skills.skill()
def data_analyzer() -> str:
    """Analyze data from various sources."""
    return "Provide data analysis capabilities..."

@data_analyzer.resource
def get_schema() -> str:
    """Get available schema information."""
    return "## Schema\n\nAvailable columns..."

@data_analyzer.script
async def analyze(ctx: RunContext[MyDeps], query: str) -> str:
    """Run analysis query."""
    return await ctx.deps.database.execute(query)

Mix File-Based and Programmatic Skills

from pydantic_ai_skills import Skill, SkillsToolset

# Create programmatic skills
programmatic_skill = Skill(
    name='runtime-skill',
    description='Created at runtime',
    content='Dynamic skill content...'
)

# Combine both types in a single toolset
toolset = SkillsToolset(
    directories=["./skills"],        # File-based skills from directory
    skills=[programmatic_skill],     # Programmatic skills
    max_depth=3                       # Limit directory discovery depth
)

# Programmatic skills can also be added via decorator
@toolset.skill()
def extra_skill() -> str:
    return "Additional dynamically-defined skill..."

print(f"Total skills loaded: {len(toolset.skills)}")

Custom Instruction Template

from pydantic_ai import Agent
from pydantic_ai_skills import SkillsToolset

custom_instructions = """\
You have specialized skills available for specific domains.

Each skill includes instructions, resources, and executable scripts.

Available skills:
{skills_list}

Use `load_skill` to explore any skill that's relevant to the user's request.
"""

toolset = SkillsToolset(
    directories=["./skills"],
    instruction_template=custom_instructions
)

agent = Agent(
    model='openai:gpt-4o',
    toolsets=[toolset]
)

Use @skill() Decorator

from pydantic_ai_skills import SkillsToolset

skills = SkillsToolset(directories=["./skills"])

@skills.skill(
    name='custom-analyzer',  # Override function name
    license='Apache-2.0',
    compatibility='Python 3.10+',
    metadata={'version': '1.0.0', 'author': 'my-team'}
)
def data_analyzer() -> str:
    """Analyze data from various sources."""
    return """
# Data Analysis Skill

Use this skill to analyze datasets and generate insights.

## Instructions

Load the full skill with `load_skill` to see available resources and scripts.
"""

# Now 'data-analyzer' skill is registered and available to agents

Get Skills Instructions for Agent

from pydantic_ai import Agent
from pydantic_ai_skills import SkillsToolset

toolset = SkillsToolset(directories=["./skills"])

agent = Agent(
    model='openai:gpt-4o',
    instructions="You are a helpful assistant.",
    toolsets=[toolset]
)

# Skill instructions are injected into the agent's system prompt automatically.
result = agent.run_sync('Analyze the quarterly data')

The instructions include: - List of available skills with descriptions - How to use the four skill tools - Best practices for progressive disclosure

Access Skills

# Get all skills
all_skills = toolset.skills

# Get specific skill
skill = toolset.get_skill("arxiv-search")

print(f"Name: {skill.name}")
print(f"Description: {skill.metadata.description}")
print(f"Scripts: {[s.name for s in skill.scripts]}")

Tools Provided

The SkillsToolset automatically registers four tools with agents:

list_skills()

Lists all available skills with descriptions.

Returns: Formatted markdown string

Example:

# Available Skills

## arxiv-search

Search arXiv for research papers (scripts: arxiv_search)

## web-research

Structured approach to web research

load_skill(skill_name: str)

Loads full instructions for a specific skill.

Parameters:

  • skill_name (str): Name of the skill to load

Returns: Full skill content including metadata and instructions

read_skill_resource(skill_name: str, resource_name: str)

Reads a resource file from a skill.

Parameters:

  • skill_name (str): Name of the skill
  • resource_name (str): Resource filename (e.g., "REFERENCE.md")

Returns: Resource file content

run_skill_script(skill_name: str, script_name: str, args: dict[str, Any] | None = None)

Executes a skill script with optional arguments.

Parameters:

  • skill_name (str): Name of the skill
  • script_name (str): Name of the script within the skill
  • args (dict[str, Any], optional): Dictionary of arguments to pass to the script
  • For file-based scripts: Converted to command-line flags (e.g., {"query": "test"}--query test)
  • For callable scripts: Passed as function arguments

Returns: String output from script execution

Raises:

  • pydantic_ai.ModelRetry: If the skill or script doesn't exist (the LLM gets a retry prompt with the available names; respects the max_retries budget configured on SkillsToolset)
  • RuntimeError: If subprocess execution fails to start
  • TimeoutError: If script execution exceeds the configured timeout
  • ValueError: If the script has no URI configured

Example:

# Agent calls the tool
agent.run_sync('Run the arxiv search script with query "machine learning"')

# Internally calls:
# result = await toolset.run_skill_script(
#     'arxiv-search',
#     'arxiv_search',
#     {'query': 'machine learning'}
# )

Decorator: @toolset.skill()

The @toolset.skill() decorator enables defining skills directly on the toolset instance.

Signature:

def skill(
    func: Callable[[], str] | None = None,
    *,
    name: str | None = None,
    description: str | None = None,
    license: str | None = None,
    compatibility: str | None = None,
    metadata: dict[str, Any] | None = None,
    resources: list[SkillResource] | None = None,
    scripts: list[SkillScript] | None = None,
) -> SkillWrapper[Any]

Parameters:

Parameter Type Description
func Callable[[], str] Function returning skill instructions/content. Used as decorator.
name str \| None Override skill name (default: normalize function name). Must match ^[a-z0-9]+(-[a-z0-9]+)*$, max 64 chars.
description str \| None Skill description (default: function docstring). Max 1024 chars.
license str \| None License identifier (e.g., "Apache-2.0").
compatibility str \| None Environment/dependency requirements (e.g., "Requires git, docker"). Max 500 chars.
metadata dict[str, Any] \| None Custom metadata fields (e.g., version, author, tags).
resources list[SkillResource] \| None Initial resources to attach. Can be extended with @skill.resource.
scripts list[SkillScript] \| None Initial scripts to attach. Can be extended with @skill.script.

Returns: SkillWrapper[Any] - Decorated skill that supports @skill.resource and @skill.script decorators

Example:

from pydantic_ai_skills import SkillsToolset

skills = SkillsToolset()

@skills.skill(
    name='data-analyzer',
    license='MIT',
    compatibility='Python 3.10+',
    metadata={'version': '1.0.0', 'author': 'data-team'}
)
def my_analyzer() -> str:
    """Analyze and process data."""
    return "# Data Analysis Skill\n\nUse for data analysis tasks."

# Extended with resources and scripts
@my_analyzer.resource
def get_schema() -> str:
    return "## Schema\n\nDatabase schema information..."

@my_analyzer.script
async def analyze_data(query: str) -> str:
    return f"Analyzed: {query}"

See Advanced Features for detailed decorator documentation.

See Also