typespec-create-api-plugin

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Create TypeSpec API Plugin

创建TypeSpec API插件

Create a complete TypeSpec API plugin for Microsoft 365 Copilot that integrates with external REST APIs.
为Microsoft 365 Copilot创建一个完整的TypeSpec API插件,该插件可与外部REST API集成。

Requirements

需求

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

main.tsp - Agent Definition

main.tsp - 代理定义

typescript
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: "[Agent Name]",
  description: "[Description]"
})
@instructions("""
  [Instructions for using the API operations]
""")
namespace [AgentName] {
  // Reference operations from actions.tsp
  op operation1 is [APINamespace].operationName;
}
typescript
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: "[Agent Name]",
  description: "[Description]"
})
@instructions("""
  [Instructions for using the API operations]
""")
namespace [AgentName] {
  // Reference operations from actions.tsp
  op operation1 is [APINamespace].operationName;
}

actions.tsp - API Operations

actions.tsp - API操作

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

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

@service
@actions(#{
    nameForHuman: "[API Display Name]",
    descriptionForModel: "[Model description]",
    descriptionForHuman: "[User description]"
})
@server("[API_BASE_URL]", "[API Name]")
@useAuth([AuthType]) // Optional
namespace [APINamespace] {
  
  @route("[/path]")
  @get
  @action
  op operationName(
    @path param1: string,
    @query param2?: string
  ): ResponseModel;

  model ResponseModel {
    // Response structure
  }
}
typescript
import "@typespec/http";
import "@microsoft/typespec-m365-copilot";

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

@service
@actions(#{
    nameForHuman: "[API Display Name]",
    descriptionForModel: "[Model description]",
    descriptionForHuman: "[User description]"
})
@server("[API_BASE_URL]", "[API Name]")
@useAuth([AuthType]) // Optional
namespace [APINamespace] {
  
  @route("[/path]")
  @get
  @action
  op operationName(
    @path param1: string,
    @query param2?: string
  ): ResponseModel;

  model ResponseModel {
    // Response structure
  }
}

Authentication Options

身份验证选项

Choose based on API requirements:
  1. No Authentication (Public APIs)
    typescript
    // No @useAuth decorator needed
  2. API Key
    typescript
    @useAuth(ApiKeyAuth<ApiKeyLocation.header, "X-API-Key">)
  3. OAuth2
    typescript
    @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. Registered Auth Reference
    typescript
    @useAuth(Auth)
    
    @authReferenceId("registration-id-here")
    model Auth is ApiKeyAuth<ApiKeyLocation.header, "X-API-Key">
根据API需求选择:
  1. 无身份验证(公开API)
    typescript
    // No @useAuth decorator needed
  2. API密钥
    typescript
    @useAuth(ApiKeyAuth<ApiKeyLocation.header, "X-API-Key">)
  3. OAuth2
    typescript
    @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. 已注册身份验证引用
    typescript
    @useAuth(Auth)
    
    @authReferenceId("registration-id-here")
    model Auth is ApiKeyAuth<ApiKeyLocation.header, "X-API-Key">

Function Capabilities

功能特性

Confirmation Dialog

确认对话框

typescript
@capabilities(#{
  confirmation: #{
    type: "AdaptiveCard",
    title: "Confirm Action",
    body: """
    Are you sure you want to perform this action?
      * **Parameter**: {{ function.parameters.paramName }}
    """
  }
})
typescript
@capabilities(#{
  confirmation: #{
    type: "AdaptiveCard",
    title: "Confirm Action",
    body: """
    Are you sure you want to perform this action?
      * **Parameter**: {{ function.parameters.paramName }}
    """
  }
})

Adaptive Card Response

Adaptive Card响应

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

Reasoning & Response Instructions

推理与响应说明

typescript
@reasoning("""
  Consider user's context when calling this operation.
  Prioritize recent items over older ones.
""")
@responding("""
  Present results in a clear table format with columns: ID, Title, Status.
  Include a summary count at the end.
""")
typescript
@reasoning("""
  Consider user's context when calling this operation.
  Prioritize recent items over older ones.
""")
@responding("""
  Present results in a clear table format with columns: ID, Title, Status.
  Include a summary count at the end.
""")

Best Practices

最佳实践

  1. Operation Names: Use clear, action-oriented names (listProjects, createTicket)
  2. Models: Define TypeScript-like models for requests and responses
  3. HTTP Methods: Use appropriate verbs (@get, @post, @patch, @delete)
  4. Paths: Use RESTful path conventions with @route
  5. Parameters: Use @path, @query, @header, @body appropriately
  6. Descriptions: Provide clear descriptions for model understanding
  7. Confirmations: Add for destructive operations (delete, update critical data)
  8. Cards: Use for rich visual responses with multiple data items
  1. 操作名称:使用清晰、面向动作的名称(如listProjects、createTicket)
  2. 模型:为请求和响应定义类似TypeScript的模型
  3. HTTP方法:使用合适的动词(@get、@post、@patch、@delete)
  4. 路径:使用符合REST规范的路径约定并搭配@route
  5. 参数:合理使用@path、@query、@header、@body
  6. 描述:为模型提供清晰的描述以助于理解
  7. 确认机制:为破坏性操作(删除、更新关键数据)添加确认机制
  8. 卡片:为包含多个数据项的富视觉响应使用卡片

Workflow

工作流程

Ask the user:
  1. What is the API base URL and purpose?
  2. What operations are needed (CRUD operations)?
  3. What authentication method does the API use?
  4. Should confirmations be required for any operations?
  5. Do responses need Adaptive Cards?
Then generate:
  • Complete
    main.tsp
    with agent definition
  • Complete
    actions.tsp
    with API operations and models
  • Optional
    cards/card.json
    if Adaptive Cards are needed
询问用户:
  1. API的基础URL和用途是什么?
  2. 需要哪些操作(CRUD操作)?
  3. API使用哪种身份验证方式?
  4. 是否需要为某些操作添加确认机制?
  5. 响应是否需要Adaptive Cards?
然后生成:
  • 包含代理定义的完整
    main.tsp
    文件
  • 包含API操作和模型的完整
    actions.tsp
    文件
  • 如果需要Adaptive Cards,则生成可选的
    cards/card.json
    文件