typespec-create-api-plugin

typespec-create-api-plugin

热门

生成一个包含REST操作、身份验证和自适应卡片的TypeSpec API插件,用于Microsoft 365 Copilot

3.7万Star
4569Fork
更新于 2026/7/14
SKILL.md
readonly只读
name
typespec-create-api-plugin
description

生成一个包含REST操作、身份验证和自适应卡片的TypeSpec API插件,用于Microsoft 365 Copilot

创建TypeSpec API插件

为Microsoft 365 Copilot创建一个完整的TypeSpec API插件,与外部REST API集成。

要求

生成包含以下内容的TypeSpec文件:

main.tsp - 代理定义

import "@typespec/http";
import "@typespec/openapi3";
import "@microsoft/typespec-m365-copilot";
import "./actions.tsp";

using TypeSpec.Http;
using TypeSpec.M365.Copilot.Agents;
using TypeSpec.M365.Copilot.Actions;

@agent({
  name: "[代理名称]",
  description: "[描述]"
})
@instructions("""
  [使用API操作的说明]
""")
namespace [AgentName] {
  // 引用actions.tsp中的操作
  op operation1 is [APINamespace].operationName;
}

actions.tsp - API操作

import "@typespec/http";
import "@microsoft/typespec-m365-copilot";

using TypeSpec.Http;
using TypeSpec.M365.Copilot.Actions;

@service
@actions(#{
    nameForHuman: "[API显示名称]",
    descriptionForModel: "[模型描述]",
    descriptionForHuman: "[用户描述]"
})
@server("[API_BASE_URL]", "[API名称]")
@useAuth([AuthType]) // 可选
namespace [APINamespace] {
  
  @route("[/路径]")
  @get
  @action
  op operationName(
    @path param1: string,
    @query param2?: string
  ): ResponseModel;

  model ResponseModel {
    // 响应结构
  }
}

身份验证选项

根据API要求选择:

  1. 无身份验证(公共API)

    // 不需要@useAuth装饰器
    
  2. API密钥

    @useAuth(ApiKeyAuth<ApiKeyLocation.header, "X-API-Key">)
    
  3. OAuth2

    @useAuth(OAuth2Auth<[{
      type: OAuth2FlowType.authorizationCode;
      authorizationUrl: "https://oauth.example.com/authorize";
      tokenUrl: "https://oauth.example.com/token";
      refreshUrl: "https://oauth.example.com/token";
      scopes: ["read", "write"];
    }]>)
    
  4. 已注册的身份验证引用

    @useAuth(Auth)
    
    @authReferenceId("registration-id-here")
    model Auth is ApiKeyAuth<ApiKeyLocation.header, "X-API-Key">
    

功能能力

确认对话框

@capabilities(#{
  confirmation: #{
    type: "AdaptiveCard",
    title: "确认操作",
    body: """
    您确定要执行此操作吗?
      * **参数**: {{ function.parameters.paramName }}
    """
  }
})

自适应卡片响应

@card(#{
  dataPath: "$.items",
  title: "$.title",
  url: "$.link",
  file: "cards/card.json"
})

推理与响应指令

@reasoning("""
  调用此操作时考虑用户的上下文。
  优先处理较新的项目而非旧项目。
""")
@responding("""
  以清晰的表格格式呈现结果,列包括:ID、标题、状态。
  最后包含汇总计数。
""")

最佳实践

  1. 操作名称:使用清晰、面向操作的名称(listProjects, createTicket)
  2. 模型:为请求和响应定义类似TypeScript的模型
  3. HTTP方法:使用适当的动词(@get, @post, @patch, @delete)
  4. 路径:使用RESTful路径约定与@route
  5. 参数:适当使用@path, @query, @header, @body
  6. 描述:为模型理解提供清晰的描述
  7. 确认:为破坏性操作添加(删除、更新关键数据)
  8. 卡片:用于包含多个数据项的丰富视觉响应

工作流程

询问用户:

  1. API的基础URL和用途是什么?
  2. 需要哪些操作(CRUD操作)?
  3. API使用哪种身份验证方法?
  4. 任何操作是否需要确认?
  5. 响应是否需要自适应卡片?

然后生成:

  • 完整的main.tsp,包含代理定义
  • 完整的actions.tsp,包含API操作和模型
  • 可选的cards/card.json(如果需要自适应卡片)