К основному содержанию
субагент CX Codex

skills — субагент для Claude Code: навыки агентов и установка

Субагент skills описывает, как подключать к агентам переносимые навыки с инструкциями, ресурсами и скриптами. Пригодится, чтобы оформлять повторяемые рабочие процессы и загружать нужный контекст по запросу.

MIT ★ 521 обновлён 2026-10-29

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/agents/skills.md
Открыть на GitHub

Что делает skills

Материал объясняет устройство Agent Skills: навык хранится в каталоге с обязательным SKILL.md, а дополнительные файлы могут лежать в scripts/, references/ и assets/. В SKILL.md задают YAML-поля и инструкции для агента. Подробные справочные материалы можно вынести в отдельные файлы.

Навыки подключаются через провайдеры: они объявляют доступные навыки и дают агенту инструменты для загрузки инструкций, чтения ресурсов и запуска скриптов. Источником могут быть файлы, код, классы или MCP-серверы; в C# и Python доступны соответствующие варианты. Это описание инструментария Agent Skills, а не готовый навык для конкретной предметной области.

Агент сначала видит названия и описания, а подробные инструкции и ресурсы получает по мере необходимости. allowed-tools помечено как экспериментальное поле, и его поддержка зависит от реализации агента.

Какие задачи решает

  • оформить предметные инструкции как переносимый навык
  • разбить многошаговую задачу на повторяемые инструкции
  • загружать справочные материалы только по запросу
  • подключить навыки из файлов, кода или MCP-сервера

Примеры запросов агенту

  • Объясни, как оформить инструкции для проверки расходов в SKILL.md.
  • Покажи, как агенту загружать справочный файл навыка по запросу.
  • Сравни источники навыков для C# и Python по этому описанию.

Как установить skills

Вручную: положить файлы

.claude/agents/skills.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

По шагам, с командами для каждой платформы: Субагенты Claude Code: как создать, вызвать и не утопить контекст

Вопросы о skills

Как установить skills в Claude Code?

Добавьте файл .claude/agents/skills.md в проект Claude Code.

Что делает субагент skills?

Он описывает формат Agent Skills и способы подключить их к агенту через провайдер. Навыки могут включать инструкции, ресурсы и скрипты, которые агент загружает по мере необходимости.

Какие источники навыков поддерживаются?

В описании перечислены источники из файловой системы, кода, классов и MCP-серверов. Для C# и Python приведены свои провайдеры и варианты источников.

Исходный текст

skills.md · MIT
---
title: Agent Skills
description: Learn how to extend agent capabilities with Agent Skills - portable packages of instructions, scripts, and resources that agents discover and load on demand.
zone_pivot_groups: programming-languages
author: SergeyMenshykh
ms.topic: article
ms.author: semenshi
ms.date: 07/08/2026
ms.service: agent-framework
---

# Agent Skills

[Agent Skills](https://agentskills.io/) are portable packages of instructions, scripts, and resources that give agents specialized capabilities and domain expertise. Skills follow an open specification and implement a progressive disclosure pattern so agents load only the context they need, when they need it.

Use Agent Skills when you want to:

- **Package domain expertise** - Capture specialized knowledge (expense policies, legal workflows, data analysis pipelines) as reusable, portable packages.
- **Extend agent capabilities** - Give agents new abilities without changing their core instructions.
- **Ensure consistency** - Turn multi-step tasks into repeatable, auditable workflows.
- **Enable interoperability** - Reuse the same skill across different Agent Skills-compatible products.

## Skill structure

A skill is a directory containing a `SKILL.md` file with optional subdirectories for resources:

```
expense-report/
├── SKILL.md                          # Required - frontmatter + instructions
├── scripts/
│   └── validate.py                   # Executable code agents can run
├── references/
│   └── POLICY_FAQ.md                 # Reference documents loaded on demand
└── assets/
    └── expense-report-template.md    # Templates and static resources
```

### SKILL.md format

The `SKILL.md` file must contain YAML frontmatter followed by markdown content:

```yaml
---
name: expense-report
description: File and validate employee expense reports according to company policy. Use when asked about expense submissions, reimbursement rules, or spending limits.
license: Apache-2.0
compatibility: Requires python3
metadata:
  author: contoso-finance
  version: "2.1"
---
```

| Field | Required | Description |
|---|---|---|
| `name` | Yes | Max 64 characters. Lowercase letters, numbers, and hyphens only. Must not start or end with a hyphen or contain consecutive hyphens. Must match the parent directory name. |
| `description` | Yes | What the skill does and when to use it. Max 1024 characters. Should include keywords that help agents identify relevant tasks. |
| `license` | No | License name or reference to a bundled license file. |
| `compatibility` | No | Max 500 characters. Indicates environment requirements (intended product, system packages, network access, etc.). |
| `metadata` | No | Arbitrary key-value mapping for additional metadata. |
| `allowed-tools` | No | Space-delimited list of pre-approved tools the skill may use. Experimental - support may vary between agent implementations. |

The markdown body after the frontmatter contains the skill instructions - step-by-step guidance, examples of inputs and outputs, common edge cases, or any content that helps the agent perform the task. Keep `SKILL.md` under 500 lines and move detailed reference material to separate files.

## Progressive disclosure

Agent Skills use a four-stage progressive disclosure pattern to minimize context usage:

1. **Advertise** (~100 tokens per skill) - Skill names and descriptions are injected into the system prompt at the start of each run, so the agent knows what skills are available.
2. **Load** (< 5000 tokens recommended) - When a task matches a skill's domain, the agent calls the `load_skill` tool to retrieve the full SKILL.md body with detailed instructions.
3. **Read resources** (as needed) - The agent calls the `read_skill_resource` tool to fetch supplementary files (references, templates, assets) only when required.
4. **Run scripts** (as needed) - The agent calls the `run_skill_script` tool to execute scripts bundled with a skill.

This pattern keeps the agent's context window lean while giving it access to deep domain knowledge on demand.

> [!NOTE]
> `load_skill` is always advertised. `read_skill_resource` is advertised only when at least one skill has resources. `run_skill_script` is advertised only when at least one skill has scripts.

## Providing skills to an agent

Working with skills involves three building blocks:

- **Provider** - `AgentSkillsProvider` (C#) or `SkillsProvider` (Python) is a context provider that exposes skills to an agent. It advertises the available skills in the system prompt and registers the tools the agent uses to load skills, read resources, and run scripts.
- **Sources** - a source supplies skills to the provider. Skills can come from several source types:
  - **File-based** - skills discovered from `SKILL.md` files in filesystem directories.
  - **Code-defined** - skills defined inline in code using `AgentInlineSkill` (C#) or `InlineSkill` (Python).
  - **Class-based** - skills encapsulated in a class deriving from `AgentClassSkill<T>` (C#) or `ClassSkill` (Python).
  - **MCP-based** - skills discovered from MCP (Model Context Protocol) servers via `UseMcpSkills` (C#) or `MCPSkillsSource` (Python).
- **Builder** - `AgentSkillsProviderBuilder` (C#) assembles multiple sources into a single provider, applying aggregation, deduplication, caching, and optional filtering. In Python, compose source classes such as `AggregatingSkillsSource`, `FilteringSkillsSource`, and `DeduplicatingSkillsSource` directly.

The following sections show how to create skills of each source type, then how to combine sources and construct a provider from them.

## Use Agent Skills with Harness Agent

With a plain agent, create a skills provider, add it to the agent's context
providers, and compose tool-approval middleware when needed. A Harness Agent
can create or include the provider as part of its standard setup.

:::zone pivot="programming-language-csharp"

`HarnessAgent` includes `AgentSkillsProvider` by default and discovers file-based
skills from `Directory.GetCurrentDirectory()`. To use a different source, set
`HarnessAgentOptions.AgentSkillsSource`:

```csharp
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

AIAgent agent = chatClient.AsHarnessAgent(new HarnessAgentOptions
{
    AgentSkillsSource = new AgentFileSkillsSource(
        Path.Combine(AppContext.BaseDirectory, "skills")),
    ToolApprovalAgentOptions = new ToolApprovalAgentOptions
    {
        // Auto-approve load_skill and read_skill_resource, but not run_skill_script.
        AutoApprovalRules = [AgentSkillsProvider.ReadOnlyToolsAutoApprovalRule],
    },
    ChatOptions = new ChatOptions
    {
        Instructions = "Use the available skills when they match the task.",
    },
});
```

`DisableAgentSkillsProvider` defaults to `false`. Set it to `true` to remove the
built-in provider. `AgentSkillsSource` replaces the default current-directory
source, but it doesn't expose `AgentSkillsProviderOptions`. If you need provider
options such as `DisableLoadSkillApproval`, disable the built-in provider and
add your configured `AgentSkillsProvider` through
`HarnessAgentOptions.AIContextProviders`.

To run scripts from file-based skills, pass an `AgentFileSkillScriptRunner`
delegate as the second `AgentFileSkillsSource` constructor argument. Without a
runner, script execution fails when requested.

All three skill tools require approval by default. The harness tool-approval
middleware is enabled by default, but its default options don't auto-approve any
tool. Use `AgentSkillsProvider.ReadOnlyToolsAutoApprovalRule` or
`AgentSkillsProvider.AllToolsAutoApprovalRule` only for skill sources you trust.

:::zone-end

:::zone pivot="programming-language-python"

Agent Skills are opt-in for `create_harness_agent`. Pass `skills_paths` for
file-based discovery:

```python
from pathlib import Path

from agent_framework import SkillsProvider, create_harness_agent

agent = create_harness_agent(
    client=client,
    agent_instructions="Use the available skills when they match the task.",
    skills_paths=Path(__file__).parent / "skills",
    # Auto-approve load_skill and read_skill_resource, but not run_skill_script.
    auto_approval_rules=[SkillsProvider.read_only_tools_auto_approval_rule],
)

session = agent.create_session()
result = await agent.run("Use the appropriate skill for this task.", session=session)
```

`skills_paths` accepts one `str` or `Path`, or a sequence of them. When both
`skills_provider` and `skills_paths` are `None` (the defaults), the harness
doesn't add a `SkillsProvider`. You can combine both parameters to include
code-defined and file-based skills.

The `skills_paths` shortcut constructs `SkillsProvider.from_paths()` without a
`script_runner`. If file-based skills need to execute scripts, create the
provider yourself with
`SkillsProvider.from_paths(..., script_runner=...)` and pass it through
`skills_provider`.

All three skill tools require approval by default. Because the harness installs
`ToolApprovalMiddleware` by default, pass a session on every run and use
`auto_approval_rules` for trusted read-only or all-tool approval policies.

:::zone-end

:::zone pivot="programming-language-go"

A packaged Go harness isn't currently available. Register the Go skills provider
in `agent.Config.ContextProviders` and compose approval middleware directly.

:::zone-end

:::zone pivot="programming-language-csharp"

## File-based skills

Create an `AgentSkillsProvider` pointing to a directory containing your skills, and add it to the agent's context providers. Pass a script runner to enable execution of file-based scripts found in skill directories:

```csharp
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using OpenAI.Responses;

string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!;
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

// Discover skills from the 'skills' directory
var skillsProvider = new AgentSkillsProvider(
    Path.Combine(AppContext.BaseDirectory, "skills"));

// Create an agent with the skills provider
AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
    .GetResponsesClient()
    .AsAIAgent(new ChatClientAgentOptions
    {
        Name = "SkillsAgent",
        ChatOptions = new()
        {
            Instructions = "You are a helpful assistant.",
        },
        AIContextProviders = [skillsProvider],
    },
    model: deploymentName);
```

> [!WARNING]
> `DefaultAzureCredential` is convenient for development but requires careful consideration in production. In production, consider using a specific credential (e.g., `ManagedIdentityCredential`) to avoid latency issues, unintended credential probing, and potential security risks from fallback mechanisms.

### Multiple skill directories

You can point the provider to a single parent directory - each subdirectory containing a `SKILL.md` is automatically discovered as a skill:

```csharp
var skillsProvider = new AgentSkillsProvider(
    Path.Combine(AppContext.BaseDirectory, "all-skills"));
```

Or pass a list of paths to search multiple root directories:

```csharp
var skillsProvider = new AgentSkillsProvider(
    [
        Path.Combine(AppContext.BaseDirectory, "company-skills"),
        Path.Combine(AppContext.BaseDirectory, "team-skills"),
    ]);
```

The provider searches up to two levels deep.

### Customizing resource and script discovery

By default, the provider recognizes resources with extensions `.md`, `.json`, `.yaml`, `.yml`, `.csv`, `.xml`, and `.txt` and scripts with extensions `.py`, `.js`, `.sh`, `.ps1`, `.cs`, and `.csx`. It searches up to two levels deep within each skill directory. Use `AgentFileSkillsSourceOptions` to change these defaults:

```csharp
var fileOptions = new AgentFileSkillsSourceOptions
{
    AllowedResourceExtensions = [".md", ".txt"],
    AllowedScriptExtensions = [".py"],
    SearchDepth = 3, // Search up to 3 levels deep (default is 2)
    ResourceFilter = context => context.RelativeFilePath.StartsWith("references/"),
    ScriptFilter = context => context.RelativeFilePath.StartsWith("scripts/")
                           || context.RelativeFilePath.StartsWith("tools/"),
};

// Via constructor
var skillsProvider = new AgentSkillsProvider(
    Path.Combine(AppContext.BaseDirectory, "skills"),
    fileOptions: fileOptions);

// Via builder
var skillsProvider = new AgentSkillsProviderBuilder()
    .UseFileSkill(Path.Combine(AppContext.BaseDirectory, "skills"), options: fileOptions)
    .Build();
```

`ResourceFilter` and `ScriptFilter` receive an `AgentFileSkillFilterContext` with the skill name and the file's relative path, letting you restrict files by location, naming convention, or any custom logic.

### Script execution

Pass `SubprocessScriptRunner.RunAsync` as the script runner to enable execution of file-based scripts:

```csharp
var skillsProvider = new AgentSkillsProvider(
    Path.Combine(AppContext.BaseDirectory, "skills"),
    SubprocessScriptRunner.RunAsync);
```

`SubprocessScriptRunner.RunAsync` is roughly equivalent to the following:

```csharp
// Simplified equivalent of what SubprocessScriptRunner.RunAsync does internally
using System.Diagnostics;
using System.Text.Json;

static async Task<object?> RunAsync(
    AgentFileSkill skill,
    AgentFileSkillScript script,
    JsonElement? args,
    IServiceProvider? serviceProvider,
    CancellationToken cancellationToken)
{
    var psi = new ProcessStartInfo("python3")
    {
        RedirectStandardOutput = true,
        UseShellExecute = false,
    };
    psi.ArgumentList.Add(script.FullPath);
    if (args is { ValueKind: JsonValueKind.Array } json)
    {
        foreach (var element in json.EnumerateArray())
        {
            psi.ArgumentList.Add(element.GetString()!);
        }
    }
    using var process = Process.Start(psi)!;
    string output = await process.StandardOutput.ReadToEndAsync(cancellationToken);
    await process.WaitForExitAsync(cancellationToken);
    return output.Trim();
}
```

The runner runs each discovered script as a local subprocess. File-based scripts expect arguments as a JSON array of strings - each array element becomes a positional command-line argument.

> [!WARNING]
> `SubprocessScriptRunner` is provided for **demonstration purposes only**. For production use, consider adding:
>
> - Sandboxing (for example, containers or isolated execution environments)
> - Resource limits (CPU, memory, wall-clock timeout)
> - Input validation and allow-listing of executable scripts
> - Structured logging and audit trails

:::zone-end

:::zone pivot="programming-language-python"

## File-based skills

Use the `SkillsProvider.from_paths()` factory to discover skills from directories containing `SKILL.md` files, and add the provider to the agent's context providers:

```python
import os
from pathlib import Path

# Discover skills from the 'skills' directory
skills_provider = SkillsProvider.from_paths(
    skill_paths=Path(__file__).parent / "skills",
)

# Create an agent with the skills provider
endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
deployment = os.environ.get("FOUNDRY_MODEL", "gpt-4o-mini")

client = FoundryChatClient(
    project_endpoint=endpoint,
    model=deployment,
    credential=AzureCliCredential(),
)

agent = Agent(
    client=client,
    instructions="You are a helpful assistant.",
    context_providers=[skills_provider],
)
```

### Multiple skill directories

You can point the provider to a single parent directory - each subdirectory containing a `SKILL.md` is automatically discovered as a skill:

```python
skills_provider = SkillsProvider.from_paths(
    skill_paths=Path(__file__).parent / "all-skills"
)
```

Or pass a list of paths to search multiple root directories:

```python
skills_provider = SkillsProvider.from_paths(
    skill_paths=[
        Path(__file__).parent / "company-skills",
        Path(__file__).parent / "team-skills",
    ]
)
```

The provider searches up to two levels deep.

### Customizing resource and script discovery

By default, resources are discovered from `references/` and `assets/` subdirectories, and scripts from `scripts/`, per the [agentskills.io specification](https://agentskills.io/specification). Recognized resource extensions are `.md`, `.json`, `.yaml`, `.yml`, `.csv`, `.xml`, and `.txt`. It searches up to two levels deep within each skill directory. Use `resource_extensions`, `script_extensions`, `search_depth`, `resource_filter`, and `script_filter` to customize discovery:

```python
skills_provider = SkillsProvider.from_paths(
    skill_paths=Path(__file__).parent / "skills",
    resource_extensions=(".md", ".txt"),
    script_extensions=(".py", ".sh"),
    search_depth=3,  # Search up to 3 levels deep (default is 2)
    resource_filter=lambda skill_name, path: path.startswith("references/"),
    script_filter=lambda skill_name, path: path.startswith("scripts/"),
)
```

The `resource_filter` and `script_filter` predicates receive the skill name and the file's relative path, letting you restrict files by location, naming convention, or any custom logic. Use `"."` to include files at the skill root level in addition to subdirectories.

### Script execution

To enable execution of file-based scripts, pass a `script_runner` to `SkillsProvider.from_paths()`. Any sync or async callable that satisfies the `SkillScriptRunner` protocol can be used:

```python
from pathlib import Path
from agent_framework import FileSkill, FileSkillScript, SkillsProvider

def my_runner(
    skill: FileSkill,
    script: FileSkillScript,
    args: dict | list[str] | None = None,
) -> str:
    """Run a file-based script as a subprocess."""
    import subprocess, sys
    script_path = Path(script.full_path)
    cmd = [sys.executable, str(script_path)]
    if isinstance(args, list):
        cmd.extend(args)
    result = subprocess.run(
        cmd, capture_output=True, text=True, timeout=30, cwd=str(script_path.parent)
    )
    return result.stdout.strip()

skills_provider = SkillsProvider.from_paths(
    skill_paths=Path(__file__).parent / "skills",
    script_runner=my_runner,
)
```

The runner receives the resolved `FileSkill`, `FileSkillScript`, and an optional `args` argument. File-based scripts expect arguments as a JSON array of strings - each array element becomes a positional command-line argument. Scripts are automatically discovered from `.py` files in the `scripts/` subdirectory of each skill directory.

> [!WARNING]
> The runner above is provided for **demonstration purposes only**. For production use, consider adding:
>
> - Sandboxing (for example, containers, `seccomp`, or `firejail`)
> - Resource limits (CPU, memory, wall-clock timeout)
> - Input validation and allow-listing of executable scripts
> - Structured logging and audit trails

> [!NOTE]
> If file-based skills with scripts are provided but no `script_runner` is set, `SkillsProvider` raises an error when script execution is attempted.

:::zone-end

:::zone pivot="programming-language-go"

## File-based skills

Go agents support skills through the `agent/skills` package. Skills follow the same progressive disclosure pattern: advertise -> load -> read resources -> run scripts.

Discover skills from `SKILL.md` files on disk and register the skills provider as an agent context provider:

```go
import (
    "os"

    "github.com/microsoft/agent-framework-go/agent"
    "github.com/microsoft/agent-framework-go/provider/foundryprovider"
    "github.com/microsoft/agent-framework-go/agent/skills"
    "github.com/microsoft/agent-framework-go/agent/skills/fsskills"
)

skillsRoot, _ := os.OpenRoot("skills")
defer skillsRoot.Close()

skillsProvider := skills.NewContextProvider(skills.ContextProviderOptions{
    Sources: []skills.Source{
        fsskills.NewSourceOptions(fsskills.SourceOptions{}, skillsRoot.FS()),
    },
})

a := foundryprovider.NewAgent(endpoint, token, foundryprovider.ModelDeployment(model), foundryprovider.AgentConfig{
    Instructions: "You are a helpful assistant.",
    Config: agent.Config{
        ContextProviders: []agent.ContextProvider{skillsProvider},
    },
})
```

:::zone-end

## Code-defined skills

:::zone pivot="programming-language-csharp"

In addition to file-based skills discovered from `SKILL.md` files, you can define skills entirely in code using `AgentInlineSkill`. Code-defined skills are useful when:

- Skill content is generated dynamically (for example, reading from a database or environment).
- You want to keep skill definitions alongside the application code that uses them.
- You need resources that execute logic at read time rather than serving static files.
- Skill definitions need to be **constructed at runtime from data** - for example, creating a personalized skill for each user session based on their role or permissions.
- A skill needs to **close over call-site state** (local variables, closures) rather than resolve services from a DI container.

### Basic code skill

Create an `AgentInlineSkill` with a name, description, and instructions. Attach resources using `.AddResource()`:

```csharp
using Microsoft.Agents.AI;

var codeStyleSkill = new AgentInlineSkill(
    name: "code-style",
    description: "Coding style guidelines and conventions for the team",
    instructions: """
        Use this skill when answering questions about coding style, conventions, or best practices for the team.
        1. Read the style-guide resource for the full set of rules.
        2. Answer based on those rules, quoting the relevant guideline where helpful.
        """)
    .AddResource(
        "style-guide",
        """
        # Team Coding Style Guide
        - Use 4-space indentation (no tabs)
        - Maximum line length: 120 characters
        - Use type annotations on all public methods
        """);

var skillsProvider = new AgentSkillsProvider(codeStyleSkill);
```

### Dynamic resources

Pass a factory delegate to `.AddResource()` to compute the content at runtime. The delegate is invoked each time the agent reads the resource:

```csharp
var projectInfoSkill = new AgentInlineSkill(
    name: "project-info",
    description: "Project status and configuration information",
    instructions: """
        Use this skill for questions about the current project.
        1. Read the environment resource for deployment configuration details.
        2. Read the team-roster resource for information about team members.
        """)
    .AddResource("environment", () =>
    {
        string env = Environment.GetEnvironmentVariable("APP_ENV") ?? "development";
        string region = Environment.GetEnvironmentVariable("APP_REGION") ?? "us-east-1";
        return $"Environment: {env}, Region: {region}";
    })
    .AddResource(
        "team-roster",
        "Alice Chen (Tech Lead), Bob Smith (Backend Engineer)");
```

### Code-defined scripts

Use `.AddScript()` to register a delegate as an executable script. Code-defined scripts run **in-process** as direct delegate calls. No script runner is needed. The delegate's typed parameters are automatically converted into a JSON Schema that the agent uses to pass arguments:

```csharp
using System.Text.Json;

var unitConverterSkill = new AgentInlineSkill(
    name: "unit-converter",
    description: "Convert between common units using a conversion factor",
    instructions: """
        Use this skill when the user asks to convert between units.
        1. Review the conversion-table resource to find the correct factor.
        2. Use the convert script, passing the value and factor from the table.
        3. Present the result clearly with both units.
        """)
    .AddResource(
        "conversion-table",
        """
        # Conversion Tables
        Formula: **result = value × factor**
        | From       | To         | Factor   |
        |------------|------------|----------|
        | miles      | kilometers | 1.60934  |
        | kilometers | miles      | 0.621371 |
        | pounds     | kilograms  | 0.453592 |
        | kilograms  | pounds     | 2.20462  |
        """)
    .AddScript("convert", (double value, double factor) =>
    {
        double result = Math.Round(value * factor, 4);
        return JsonSerializer.Serialize(new { value, factor, result });
    });

var skillsProvider = new AgentSkillsProvider(unitConverterSkill);
```

> [!NOTE]
> To combine code-defined skills with file-based or class-based skills in a single provider, use `AgentSkillsProviderBuilder` - see [Provider construction](#provider-construction).

:::zone-end

:::zone pivot="programming-language-python"

In addition to file-based skills discovered from `SKILL.md` files, you can define skills entirely in Python code using `InlineSkill`. Code-defined skills are useful when:

- Skill content is generated dynamically (for example, reading from a database or environment).
- You want to keep skill definitions alongside the application code that uses them.
- You need resources that execute logic at read time rather than serving static files.
- Skill definitions need to be **constructed at runtime from data** - for example, creating a personalized skill for each user session based on their role or permissions.
- A skill needs to **close over call-site state** (local variables, closures) rather than resolve services through `**kwargs`.

### Basic code skill

Create an `InlineSkill` instance with a `SkillFrontmatter` (containing the name and description) and instruction content. Optionally attach `InlineSkillResource` instances with static content:

```python
from textwrap import dedent
from agent_framework import InlineSkill, InlineSkillResource, SkillFrontmatter, SkillsProvider

code_style_skill = InlineSkill(
    frontmatter=SkillFrontmatter(
        name="code-style",
        description="Coding style guidelines and conventions for the team",
    ),
    instructions=dedent("""\
        Use this skill when answering questions about coding style,
        conventions, or best practices for the team.
    """),
    resources=[
        InlineSkillResource(
            name="style-guide",
            content=dedent("""\
                # Team Coding Style Guide
                - Use 4-space indentation (no tabs)
                - Maximum line length: 120 characters
                - Use type annotations on all public functions
            """),
        ),
    ],
)

skills_provider = SkillsProvider(code_style_skill)
```

### Dynamic resources

Use the `@skill.resource` decorator to register a function as a resource. The function is called each time the agent reads the resource, so it can return up-to-date data. Both sync and async functions are supported:

```python
import os
from agent_framework import InlineSkill, SkillFrontmatter

project_info_skill = InlineSkill(
    frontmatter=SkillFrontmatter(
        name="project-info",
        description="Project status and configuration information",
    ),
    instructions="Use this skill for questions about the current project.",
)

@project_info_skill.resource
def environment() -> str:
    """Get current environment configuration."""
    env = os.environ.get("APP_ENV", "development")
    region = os.environ.get("APP_REGION", "us-east-1")
    return f"Environment: {env}, Region: {region}"

@project_info_skill.resource(name="team-roster", description="Current team members")
def get_team_roster() -> str:
    """Return the team roster."""
    return "Alice Chen (Tech Lead), Bob Smith (Backend Engineer)"
```

When the decorator is used without arguments (`@skill.resource`), the function name becomes the resource name and the docstring becomes the description. Use `@skill.resource(name="...", description="...")` to set them explicitly.

### Code-defined scripts

Use the `@skill.script` decorator to register a function as an executable script on a skill. Code-defined scripts run **in-process** and do not require a script runner. Both sync and async functions are supported:

```python
from agent_framework import InlineSkill, SkillFrontmatter

unit_converter_skill = InlineSkill(
    frontmatter=SkillFrontmatter(
        name="unit-converter",
        description="Convert between common units using a conversion factor",
    ),
    instructions="Use the convert script to perform unit conversions.",
)

@unit_converter_skill.script(name="convert", description="Convert a value: result = value × factor")
def convert_units(value: float, factor: float) -> str:
    """Convert a value using a multiplication factor."""
    import json
    result = round(value * factor, 4)
    return json.dumps({"value": value, "factor": factor, "result": result})
```

When the decorator is used without arguments (`@skill.script`), the function name becomes the script name and the docstring becomes the description. The function's typed parameters are automatically converted into a JSON Schema that the agent uses to pass arguments.

:::zone-end

:::zone pivot="programming-language-go"

In addition to file-based skills discovered from `SKILL.md` files, you can define skills entirely in Go code:

```go
skill := &skills.Skill{
    Frontmatter: skills.Frontmatter{
        Name:        "unit-converter",
        Description: "Convert between common units using a multiplication factor.",
    },
    GetContent: func(context.Context) (string, error) {
        return "Use this skill when the user asks to convert between units.", nil
    },
    Resources: []skills.Resource{
        {
            Name:        "conversion-table",
            Description: "Lookup table of multiplication factors.",
            Read: func(context.Context) (any, error) {
                return conversionTable, nil
            },
        },
    },
    Scripts: []skills.Script{
        {
            Name:        "convert",
            Description: "Multiplies a value by a conversion factor. Pass value and factor as positional string arguments: [\"<...

© SergeyMenshykh · MIT · managedcode/dotnet-skills

Похожие субагенты

Все субагенты по теме «Настройка агента: память, контекст, субагенты» →
canvas-create-discovery Microsoft Субагент canvas-create-discovery для Claude Code проверяет доступные в Power Apps элементы управления, источники данных и API, фиксируя решения и ограничения. Оценивает осуществимость замысла холст-приложения. CX Codex ★ 1 167звёзд репо canvas-screen-builder Microsoft Субагент canvas-screen-builder для Claude Code добавляет или изменяет один экран в существующем Canvas App по общему контракту и заданию. Он выполняет локальную проверку без компиляции. CX Codex ★ 1 167звёзд репо debugger justxor Субагент debugger в Claude Code воспроизводит ошибки и падающие тесты, ищет первопричину и проверяет исправление. Разбирает стектрейсы и неожиданные результаты. CX Codex ★ 353звёзд репо docs-writer justxor Субагент docs-writer автоматически актуализирует README, API-документацию, комментарии и ADR когда вы меняете код. Проверяет фактическое поведение и держит примеры в синхронизации с реальностью. CX Codex ★ 353звёзд репо APP-4913-tui-input-prompt-prefix dominikmartn Субагент APP-4913-tui-input-prompt-prefix для Claude Code настраивает префикс строки ввода в терминальном интерфейсе harp. Добавляет двухсимвольный отступ с символами для режима агента и шелла. CX Codex ★ 720звёзд репо APP-4903 improve TUI tab bar keybindings dominikmartn Субагент APP-4903 improve TUI tab bar keybindings для Claude Code меняет фокус и клавиши вкладок оркестрации. Он запускается при работе с TUI и проверяет регрессии. CX Codex ★ 720звёзд репо

Из того же набора38

Весь набор →
defining-middleware Субагент defining-middleware для Claude Code, Cursor и Codex показывает, как добавить middleware для перехвата и изменения взаимодействий агента. Позволяет логировать запросы и контролировать вызовы функций. CX Codex ★ 521звёзд репо security Субагент security защищает агентов от prompt injection и утечки данных через детерминированный контроль информационных потоков FIDES. CX Codex ★ 521звёзд репо agent-vs-run-scope Субагент agent-vs-run-scope для Claude Code, Cursor и Codex, который объясняет разницу между middleware на уровне агента и на уровне запроса. Применяется, когда нужно понять, как и когда срабатывает middleware в Agent Framework. CX Codex ★ 521звёзд репо test-engineer Субагент test-engineer для написания, исправления и улучшения тестов на разных языках. Работает с существующими фреймворками проекта и координирует специализированных помощников для массовой генерации и глубокого аудита качества. CX Codex ★ 521звёзд репо blazing-fast-dotnet Скилл blazing-fast-dotnet подсказывает способы профилирования и ускорения кода на C#, сокращения аллокаций памяти и настройки NativeAOT. CX Codex +1 ★ 521звёзд репо compaction Субагент compaction для Claude Code сокращает историю диалога, чтобы она укладывалась в контекст модели. Работает с историей, которую агент хранит в памяти. CX Codex ★ 521звёзд репо observability Субагент по observability в Microsoft Agent Framework: разбирает, как подключить OpenTelemetry к чат-клиентам и агентам на C#, и как отправить трейсы, метрики и логи в нужный бэкенд. CX Codex ★ 521звёзд репо index Субагент index помогает проектировать middleware в Microsoft Agent Framework для .NET: перехватывать запуски агентов, вызовы функций и запросы к IChatClient. CX Codex ★ 521звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой