declarative-agent-developer
microsoft/skills
Criar, construir, implantar e localizar agentes declarativos para o M365 Copilot e Teams, incluindo a criação de estruturas básicas, edição de manifestos, adição de recursos e localização.
...Expandir tudoDesenvolvedor de Agentes M365
Marcação de Telemetria
Antes de executar qualquer comando do CLI atk, defina a variável de ambiente da sessão para que todas as invocações do CLI sejam marcadas como iniciadas por habilidade:
export ATK_CLI_SKILL=true
Execute isso uma vez no início da sessão. Todos os comandos atk subsequentes no mesmo terminal herdarão essa configuração.
⛔ Verificação do Espaço de Trabalho — PRIMEIRO PASSO OBRIGATÓRIO
Antes de fazer QUALQUER COISA, verifique os arquivos do espaço de trabalho para identificar o projeto:
- Execute
npx -y --package @microsoft/m365agentstoolkit-cli atk --versionpara confirmar se o CLI do ATK está instalado. Se não for encontrado → Pare. Informe ao usuário para instalar o ATK. - Verifique a existência de
m365agents.ymlouteamsApp.ymlna raiz do projeto. - Verifique a existência de
appPackage/declarativeAgent.json. - Verifique indicadores não relacionados a agentes (
package.jsoncom express/react/next,src/index.js,app.py, etc.)
Em seguida, siga o portão de decisão:
| Condição | Portão | Ação |
|---|---|---|
| Arquivos de projeto não relacionados a agentes, sem `appPackage/` | **Rejeitar** | Resposta apenas em texto. Sem arquivos, sem comandos. |
| Sem manifesto, usuário deseja editar/implementar | **Rejeitar** | Resposta apenas em texto. Explique que o manifesto está ausente. |
| Sem manifesto, usuário deseja novo projeto | **Criar Estrutura** | → Fluxo de Trabalho de Criação de Estrutura |
| Manifesto existe com erros | **Corrigir** | Detectar → Informar → Perguntar (ver abaixo). NÃO implemente. |
| Projeto válido, usuário relata problemas de comportamento | **Revisar** | → Revisão de Instruções — execute o fluxo de revisão completo de 5 fases |
| Projeto de agente válido | **Editar** | → Fluxo de Trabalho de Edição |
Regras detalhadas do portão, exemplos e anti-padrões: Portões do Espaço de Trabalho
🚫 REGRAS DE REJEIÇÃO RÍGIDA — Sem Exceções
Estas regras substituem TODAS as outras instruções. Se alguma delas se aplicar, você DEVE parar imediatamente.
- NUNCA crie
declarativeAgent.jsonvocê mesmo. Se o manifesto estiver ausente e o usuário tiver solicitado edição/modificação/implementação, responda apenas em texto: explique que o manifesto está ausente, sugiranpx -y --package @microsoft/m365agentstoolkit-cli atk newou começar do zero. NÃO crie o arquivo, NÃO crieappPackage/, NÃO "ajude" criando a estrutura implicitamente. - NUNCA crie arquivos em um projeto não relacionado a agentes. Se o espaço de trabalho for um aplicativo Express/React/Django/etc. sem
appPackage/, sua resposta deve ser apenas em texto. NÃO crie nenhum arquivo, NÃO execute nenhum comando. - NUNCA implemente quando existirem erros. Se o manifesto do agente tiver erros, PARE. NÃO execute
npx -y --package @microsoft/m365agentstoolkit-cli atk provision— nem "para testar", nem "para demonstrar o erro", nem "para ver o que acontece". Relate os erros e pergunte ao usuário como proceder.
🔍 Detectar → Informar → Perguntar (Protocolo de Manipulação de Erros)
Ao encontrar QUALQUER problema (arquivos ausentes, JSON malformado, erros de validação, recursos incompatíveis), você DEVE seguir esta sequência na ordem:
- Detectar — Identifique o problema específico. Para problemas de JSON, tente analisar o arquivo e relatar erros de sintaxe. Para campos ausentes, verifique o manifesto em relação ao Esquema.
- Informar — Informe o usuário ANTES de tomar qualquer ação. Descreva exatamente o que está errado ("declarativeAgent.json tem JSON malformado: vírgula ausente na linha 12, matriz não fechada na linha 18").
- Perguntar — Aguarde a resposta do usuário antes de fazer alterações. NÃO corrija silenciosamente, não faça correção automática e não contorne o problema.
Este protocolo aplica-se a:
declarativeAgent.jsonausente → Detectar (arquivo não encontrado) → Informar ("nenhum manifesto encontrado") → Perguntar ("você deseja criar um novo agente?")- JSON malformado → Detectar (erros de análise) → Informar (listar problemas de sintaxe específicos) → Perguntar ("devo corrigir esses erros de sintaxe?")
- Erros de validação → Detectar (analisar e verificar o manifesto) → Informar (listar todos os erros) → Perguntar ("como você deseja corrigir isso?")
- Incompatibilidade de versão → Detectar (recurso requer versão mais recente) → Informar ("este recurso requer v1.6, seu agente é v1.4") → Perguntar ("devo atualizar?")
Roteamento de Fases
| Cenário | Referência do Fluxo de Trabalho |
|---|---|
| Criando um NOVO projeto do zero | Fluxo de Trabalho de Criação de Estrutura |
| Trabalhando com manifestos `.json` existentes | Fluxo de Trabalho de Edição |
| Adicionando um plugin de API | Plugins de API |
| Adicionando um servidor MCP | Plugin MCP |
| Adicionando OAuth a um plugin MCP ou API | Autenticação |
| Revisando ou melhorando instruções de agente existentes | Revisão de Instruções |
| Usuário relata que o agente dá respostas genéricas/incorretas | Revisão de Instruções |
| Localizando um agente em vários idiomas | Localização |
| Adicionando um novo idioma a um agente já localizado | Localização |
| Escrevendo instruções do agente | Design de Conversa |
Configuração do CLI do ATK
Antes de executar qualquer comando do ATK, verifique se o CLI do ATK está disponível executando npx -y --package @microsoft/m365agentstoolkit-cli atk --version. Se não for encontrado, PARE e informe ao usuário — NÃO tente instalá-lo você mesmo.
Todos os comandos usam o prefixo npx -y --package @microsoft/m365agentstoolkit-cli atk (por exemplo, npx -y --package @microsoft/m365agentstoolkit-cli atk provision --env local).
Regras Críticas
1. Implementar APÓS CADA Edição
Após QUALQUER alteração em arquivos em appPackage/, você DEVE implementar e mostrar o link de teste antes de responder:
npx -y --package @microsoft/m365agentstoolkit-cli atk provision --env local --interactive false
Em seguida, leia M365_TITLE_ID de env/.env.local e SEMPRE apresente a interface do usuário de revisão:
✅ Agente implementado com sucesso!
🚀 Teste seu Agente no M365 Copilot:
🔗 https://m365.cloud.microsoft/chat/?titleId={M365_TITLE_ID}
⛔ Nunca responda sem este link. Se você implementou, o link de teste DEVE aparecer em sua resposta. Isso não é opcional — é assim que o usuário testa seu agente.
- Se o manifesto tiver erros → PARE. Corrija os erros. NÃO implemente.
- Exceção: usuário solicita explicitamente que você não implemente
2. Nunca Inventar Conteúdo ou Criar Arquivos Ausentes
- NÃO invente nomes, descrições ou instruções de espaço reservado
- NÃO crie
declarativeAgent.jsonouappPackage/se eles não existirem — este é um cenário de REJEIÇÃO, não um cenário de "ajudar criando" - Se os campos obrigatórios estiverem ausentes, relate as lacunas e PERGUNTE ao usuário
- Se o JSON estiver malformado, siga Detectar → Informar → Perguntar: analise o arquivo primeiro, informe ao usuário o que está quebrado e pergunte antes de corrigir. Use edições cirúrgicas (não reescritas)
- ⛔ NUNCA defina valores de espaço reservado para variáveis de ambiente que são preenchidas por automação (por exemplo,
<prefix>_MCP_AUTH_ID</prefix>,TEAMS_APP_ID). Deixe-as vazias (VAR_NAME=). Os espaços reservados serão tratados como valores reais e NÃO serão substituídos pelo provisionamento.
3. Compatibilidade da Versão do Esquema
Antes de adicionar QUALQUER recurso, leia o campo version em declarativeAgent.json e verifique a matriz de recursos do Esquema. Se o recurso não for suportado nessa versão, recuse e ofereça atualizar.
Portões de versão principais:
sensitivity_label,worker_agents,EmbeddedKnowledge→ v1.6 apenasMeetings→ v1.5+ScenarioModels,behavior_overrides,disclaimer→ v1.4+Dataverse,TeamsMessages,Email,People→ v1.3+
4. Use npx -y --package @microsoft/m365agentstoolkit-cli atk add action para Plugins de API — NUNCA Crie Arquivos de Plugin Manualmente
Você está proibido de criar manualmente ai-plugin.json, especificações OpenAPI, cartões adaptativos ou editar a matriz actions. Use o CLI:
# ⛔ Sempre liste TODAS as operações em uma única chamada — NUNCA execute chamadas separadas por operação
npx -y --package @microsoft/m365agentstoolkit-cli atk add action --api-plugin-type api-spec --openapi-spec-location URL --api-operation "GET /path,POST /path,PATCH /path/{id},DELETE /path/{id}" -i false
Execute uma única chamada npx -y --package @microsoft/m365agentstoolkit-cli atk add action por especificação OpenAPI, listando todas as operações como uma lista separada por vírgulas em --api-operation. Nunca execute chamadas npx -y --package @microsoft/m365agentstoolkit-cli atk add action separadas para operações diferentes da mesma especificação — isso cria vários plugins em vez de um. Se npx -y --package @microsoft/m365agentstoolkit-cli atk add action falhar, relate o erro; NÃO recorra à criação manual.
Exceção: Servidores MCP não são suportados por
npx -y --package @microsoft/m365agentstoolkit-cli atk add action. Use o fluxo de trabalho do Plugin MCP em vez disso.
5. Integração com Servidor MCP
Quando o usuário mencionar uma URL de servidor MCP, siga o fluxo de trabalho do Plugin MCP. Você DEVE descobrir ferramentas por meio do aperto de mão do protocolo MCP (inicializar → notificações/inicializado → tools/list) — NUNCA fabrique nomes/descrições de ferramentas. Para servidores MCP autenticados, siga o guia de autenticação para configurar o OAuth.
6. Sempre Atualizar Instruções e Inicializadores Após Alterações
Adicionar um recurso ou plugin sem atualizar as instruções é incompleto. Após QUALQUER alteração:
- Atualize as instruções para descrever a nova/altered funcionalidade — cada fonte de dados deve ter cobertura clara de intenção (QUANDO e POR QUE usá-la) de acordo com a barra de qualidade da Revisão de Instruções. Recursos integrados não precisam de nomes exatos; ações/plugins devem ser nomeados.
- NÃO liste nomes de ferramentas, descrições ou parâmetros nas instruções — isso já está nos metadados do plugin (
ai-plugin.json, manifestos MCP, configuração de recursos). As instruções devem conter apenas lógica de decisão: QUANDO usar cada ferramenta, regras de encadeamento e manipulação de falhas. - Mantenha-se dentro do limite de 8.000 caracteres de instruções — se estiver próximo do limite, corte as descrições das ferramentas primeiro
- Adicione pelo menos 1 inicializador de conversa por recurso/plugin adicionado
- Remova inicializadores que referenciam recursos removidos
- Execute a Lista de Verificação de Diagnóstico contra as instruções atualizadas para verificar a qualidade
7. Nome do Aplicativo
Sempre atualize o nome e a descrição do aplicativo para algo significativo. Nunca deixe padrões como "Meu Agente".
Referências
Compartilhado
- Autenticação — Descoberta de OAuth, credenciais, ciclo de vida oauth/register, OAuthPluginVault
- Melhores Práticas — Segurança, desempenho, testes, conformidade
- Design de Conversa — Autoração de instruções e inicializadores de conversa do zero
- Revisão de Instruções — Auditoria, diagnóstico e melhoria de instruções existentes; detecção de anti-padrões; reescritas antes/depois
- Implementação — Fluxos de trabalho do CLI do ATK, ambientes, CI/CD
- Localização — Suporte a vários idiomas, manifestos tokenizados, arquivos de idioma
- Portões do Espaço de Trabalho — Regras detalhadas do portão, exemplos, anti-padrões
Criação de Estrutura
- Fluxo de Trabalho de Criação de Estrutura — Instruções passo a passo para criação de estrutura, regras de nomenclatura, manipulação de erros
Desenvolvimento JSON
- Fluxo de Trabalho de Edição — Instruções passo a passo para desenvolvimento JSON
- Esquema — Esquema JSON oficial para manifestos de agente
- Plugins de API — Integração OpenAPI para agentes JSON
- Plugin MCP — Integração de servidor MCP com RemoteMCPServer, OAuth, semântica de resposta, manipulação de logotipos
- Exemplos — Exemplos de manifesto JSON
---
name: declarative-agent-developer
description: Create, build, deploy, and localize declarative agents for M365 Copilot and Teams, including scaffolding, editing manifests, adding capabilities, and localization.
---
# M365 Agent Developer
## Telemetry Tagging
Before running any `atk` CLI commands, set the session environment variable so all CLI invocations are tagged as skill-initiated:
```bash
export ATK_CLI_SKILL=true
```
Run this once at the start of the session. All subsequent `atk` commands in the same terminal will inherit it.
## ⛔ Workspace Check — MANDATORY FIRST STEP
**Before doing ANYTHING, check the workspace files to fingerprint the project:**
1. Run `npx -y --package @microsoft/m365agentstoolkit-cli atk --version` to confirm ATK CLI is installed. If not found → **Stop.** Tell the user to install ATK.
2. Check for `m365agents.yml` or `teamsApp.yml` at the project root.
3. Check for `appPackage/declarativeAgent.json`.
4. Check for non-agent indicators (`package.json` with express/react/next, `src/index.js`, `app.py`, etc.)
**Then follow the decision gate:**
| Condition | Gate | Action |
|-----------|------|--------|
| Non-agent project files, no `appPackage/` | **Reject** | Text-only response. No files, no commands. |
| No manifest, user wants to edit/deploy | **Reject** | Text-only response. Explain manifest is missing. |
| No manifest, user wants new project | **Scaffold** | → [Scaffolding Workflow](references/scaffolding-workflow.md) |
| Manifest exists with errors | **Fix** | Detect → Inform → Ask (see below). Do NOT deploy. |
| Valid project, user reports behavior issues | **Review** | → [Instruction Review](references/instruction-review.md) — run the full 5-phase review workflow |
| Valid agent project | **Edit** | → [Editing Workflow](references/editing-workflow.md) |
> **Detailed gate rules, examples, and anti-patterns:** [Workspace Gates](references/workspace-gates.md)
### 🚫 HARD REJECTION RULES — No Exceptions
**These rules override ALL other instructions.** If any of these apply, you MUST stop immediately.
1. **NEVER create `declarativeAgent.json` yourself.** If the manifest is missing and the user asked to edit/modify/deploy, respond with text only: explain the manifest is missing, suggest `npx -y --package @microsoft/m365agentstoolkit-cli atk new` or starting from scratch. Do NOT create the file, do NOT create `appPackage/`, do NOT "help" by scaffolding implicitly.
2. **NEVER create files in a non-agent project.** If the workspace is an Express/React/Django/etc. app without `appPackage/`, your response must be text-only. Do NOT create any files, do NOT run any commands.
3. **NEVER deploy when errors exist.** If the agent manifest has errors, STOP. Do NOT run `npx -y --package @microsoft/m365agentstoolkit-cli atk provision` — not "to test", not "to demonstrate the error", not "to see what happens". Report the errors and ask the user how to proceed.
### 🔍 Detect → Inform → Ask (Error-Handling Protocol)
When you encounter ANY problem (missing files, malformed JSON, validation errors, incompatible features), you MUST follow this sequence **in order**:
1. **Detect** — Identify the specific problem. For JSON issues, attempt to parse the file and report syntax errors. For missing fields, check the manifest against the [Schema](references/schema.md).
2. **Inform** — Tell the user BEFORE taking any action. Describe exactly what is wrong ("declarativeAgent.json has malformed JSON: missing comma on line 12, unclosed array on line 18").
3. **Ask** — Wait for the user's response before making changes. Do NOT silently fix, auto-correct, or work around the problem.
**This protocol applies to:**
- Missing `declarativeAgent.json` → Detect (file not found) → Inform ("no manifest found") → Ask ("would you like to create a new agent?")
- Malformed JSON → Detect (parse errors) → Inform (list specific syntax issues) → Ask ("should I fix these syntax errors?")
- Validation errors → Detect (parse and check manifest) → Inform (list all errors) → Ask ("how would you like to fix these?")
- Version incompatibility → Detect (feature requires newer version) → Inform ("this feature requires v1.6, your agent is v1.4") → Ask ("should I upgrade?")
---
## Phase Routing
| Scenario | Workflow Reference |
|----------|-------------------|
| Creating a NEW project from scratch | [Scaffolding Workflow](references/scaffolding-workflow.md) |
| Working with existing `.json` manifests | [Editing Workflow](references/editing-workflow.md) |
| Adding an API plugin | [API Plugins](references/api-plugins.md) |
| Adding an MCP server | [MCP Plugin](references/mcp-plugin.md) |
| Adding OAuth to an MCP or API plugin | [Authentication](references/authentication.md) |
| Reviewing or improving existing agent instructions | [Instruction Review](references/instruction-review.md) |
| User reports agent gives generic/wrong answers | [Instruction Review](references/instruction-review.md) |
| Localizing an agent into multiple languages | [Localization](references/localization.md) |
| Adding a new language to an already-localized agent | [Localization](references/localization.md) |
| Writing agent instructions | [Conversation Design](references/conversation-design.md) |
---
## ATK CLI Setup
Before running any ATK commands, check if the ATK CLI is available by running `npx -y --package @microsoft/m365agentstoolkit-cli atk --version`. If not found, **STOP and tell the user** — do NOT attempt to install it yourself.
All commands use the `npx -y --package @microsoft/m365agentstoolkit-cli atk` prefix (e.g., `npx -y --package @microsoft/m365agentstoolkit-cli atk provision --env local`).
---
## Critical Rules
### 1. Deploy After EVERY Edit
After ANY change to files in `appPackage/`, you MUST deploy and show the test link before responding:
```bash
npx -y --package @microsoft/m365agentstoolkit-cli atk provision --env local --interactive false
```
Then read `M365_TITLE_ID` from `env/.env.local` and **ALWAYS** present the review UX:
```
✅ Agent deployed successfully!
🚀 Test Your Agent in M365 Copilot:
🔗 https://m365.cloud.microsoft/chat/?titleId={M365_TITLE_ID}
```
**⛔ Never respond without this link.** If you deployed, the test link MUST appear in your response. This is not optional — it is how the user tests their agent.
- If the manifest has errors → **STOP. Fix errors. Do NOT deploy.**
- Exception: user explicitly asks you not to deploy
### 2. Never Invent Content or Create Missing Files
- Do NOT invent placeholder names, descriptions, or instructions
- Do NOT create `declarativeAgent.json` or `appPackage/` if they don't exist — this is a REJECT scenario, not a "help by creating" scenario
- If required fields are missing, report the gaps, and ASK the user
- If JSON is malformed, follow Detect → Inform → Ask: parse the file first, tell the user what's broken, then ask before fixing. Use surgical edits (not rewrites)
- **⛔ NEVER set placeholder values for environment variables** that are populated by automation (e.g., `<PREFIX>_MCP_AUTH_ID`, `TEAMS_APP_ID`). Leave them empty (`VAR_NAME=`). Placeholders will be treated as real values and will NOT be overwritten by provisioning.
### 3. Schema Version Compatibility
Before adding ANY feature, read the `version` field in `declarativeAgent.json` and check the [Schema](references/schema.md) feature matrix. If the feature isn't supported in that version, **refuse** and offer to upgrade.
Key version gates:
- `sensitivity_label`, `worker_agents`, `EmbeddedKnowledge` → **v1.6 only**
- `Meetings` → **v1.5+**
- `ScenarioModels`, `behavior_overrides`, `disclaimer` → **v1.4+**
- `Dataverse`, `TeamsMessages`, `Email`, `People` → **v1.3+**
### 4. Use `npx -y --package @microsoft/m365agentstoolkit-cli atk add action` for API Plugins — NEVER Create Plugin Files Manually
You are **forbidden** from manually creating `ai-plugin.json`, OpenAPI specs, adaptive cards, or editing the `actions` array. Use the CLI:
```bash
# ⛔ Always list ALL operations in a single call — NEVER run separate calls per operation
npx -y --package @microsoft/m365agentstoolkit-cli atk add action --api-plugin-type api-spec --openapi-spec-location URL --api-operation "GET /path,POST /path,PATCH /path/{id},DELETE /path/{id}" -i false
```
Run a **single** `npx -y --package @microsoft/m365agentstoolkit-cli atk add action` call per OpenAPI spec, listing **all** operations as a comma-separated list in `--api-operation`. Never run separate `npx -y --package @microsoft/m365agentstoolkit-cli atk add action` calls for different operations from the same spec — this creates multiple plugins instead of one. If `npx -y --package @microsoft/m365agentstoolkit-cli atk add action` fails, report the error; do NOT fall back to manual creation.
> **Exception:** MCP servers are not supported by `npx -y --package @microsoft/m365agentstoolkit-cli atk add action`. Use the [MCP Plugin workflow](references/mcp-plugin.md) instead.
### 5. MCP Server Integration
When the user mentions an MCP server URL, follow the [MCP Plugin workflow](references/mcp-plugin.md). You MUST discover tools via the MCP protocol handshake (initialize → notifications/initialized → tools/list) — **NEVER fabricate tool names/descriptions**. For authenticated MCP servers, follow the [authentication guide](references/authentication.md) to configure OAuth.
### 6. Always Update Instructions & Starters After Changes
Adding a capability or plugin without updating instructions is incomplete. After ANY change:
1. Update instructions to describe the new/changed functionality — every data source should have clear intent coverage (WHEN and WHY to use it) per the [Instruction Review](references/instruction-review.md) quality bar. Built-in capabilities don't need exact names; actions/plugins should be named.
2. **Do NOT list tool names, descriptions, or parameters in instructions** — these are already in the plugin metadata (`ai-plugin.json`, MCP manifests, capability config). Instructions should contain decision logic only: WHEN to use each tool, chaining rules, and failure handling.
3. **Stay within the 8,000-character instruction limit** — if close to the limit, cut tool descriptions first
4. Add at least 1 conversation starter per added capability/plugin
5. Remove starters that reference removed capabilities
6. Run the [Diagnostic Checklist](references/instruction-review.md) against the updated instructions to verify quality
### 7. App Name Requirement
Always update the app name and description to something meaningful. Never leave defaults like "My Agent".
---
## References
### Shared
- **[Authentication](references/authentication.md)** — OAuth discovery, credentials, oauth/register lifecycle, OAuthPluginVault
- **[Best Practices](references/best-practices.md)** — Security, performance, testing, compliance
- **[Conversation Design](references/conversation-design.md)** — Authoring instructions and conversation starters from scratch
- **[Instruction Review](references/instruction-review.md)** — Auditing, diagnosing, and improving existing instructions; anti-pattern detection; before/after rewrites
- **[Deployment](references/deployment.md)** — ATK CLI workflows, environments, CI/CD
- **[Localization](references/localization.md)** — Multi-language support, tokenized manifests, language files
- **[Workspace Gates](references/workspace-gates.md)** — Detailed gate rules, examples, anti-patterns
### Scaffolding
- **[Scaffolding Workflow](references/scaffolding-workflow.md)** — Step-by-step scaffolding instructions, naming rules, error handling
### JSON Development
- **[Editing Workflow](references/editing-workflow.md)** — Step-by-step JSON development instructions
- **[Schema](references/schema.md)** — Official JSON schema for agent manifests
- **[API Plugins](references/api-plugins.md)** — OpenAPI integration for JSON agents
- **[MCP Plugin](references/mcp-plugin.md)** — MCP server integration with RemoteMCPServer, OAuth, response semantics, logo handling
- **[Examples](references/examples.md)** — JSON manifest examples
Todos os arquivos
0 arquivosInstalar declarative-agent-developer
Baixe e extraia os arquivos de habilidade para o diretório .claude/skills/.
Baixar ZIPClone o repositório e copie os arquivos da habilidade para o seu projeto.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/microsoft-365-agents-toolkit/skills/declarative-agent-developer # Copy SKILL.md to your .claude/skills/ directory
Copiar





Lar
