ts-agent-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ts-agent-sdk

ts-agent-sdk

Overview

概述

This skill generates typed TypeScript SDKs that allow AI agents (primarily Claude Code) to interact with web applications via MCP servers. It replaces verbose JSON-RPC curl commands with clean function calls.
本Skill用于生成类型化的TypeScript SDK,让AI Agent(主要是Claude Code)能够通过MCP服务器与Web应用交互。它将冗长的JSON-RPC curl命令替换为简洁的函数调用。

Template Location

模板位置

The core SDK template files are bundled with this skill at:
templates/
Copy these files to the target project's
scripts/sdk/
directory as a starting point:
bash
cp -r ~/.claude/skills/ts-agent-sdk/templates/* ./scripts/sdk/
核心SDK模板文件随本Skill一起打包在以下路径:
templates/
将这些文件复制到目标项目的
scripts/sdk/
目录作为起点:
bash
cp -r ~/.claude/skills/ts-agent-sdk/templates/* ./scripts/sdk/

SDK Generation Workflow

SDK生成流程

Step 1: Detect MCP Servers

步骤1:检测MCP服务器

Scan the project for MCP server modules:
src/server/modules/mcp*/server.ts
Each server.ts file contains tool definitions using the pattern:
typescript
server.tool(
  'tool_name',
  'Tool description',
  zodInputSchema,
  async (params) => { ... }
)
扫描项目中的MCP服务器模块:
src/server/modules/mcp*/server.ts
每个server.ts文件都包含如下模式的工具定义:
typescript
server.tool(
  'tool_name',
  'Tool description',
  zodInputSchema,
  async (params) => { ... }
)

Step 2: Extract Tool Definitions

步骤2:提取工具定义

For each tool, extract:
  1. name: The tool identifier (e.g., 'create_document')
  2. description: Tool description for JSDoc
  3. inputSchema: Zod schema defining input parameters
  4. endpoint: The MCP endpoint path (e.g., '/api/mcp-docs/message')
针对每个工具,提取以下内容:
  1. name:工具标识符(例如'create_document')
  2. description:用于JSDoc的工具描述
  3. inputSchema:定义输入参数的Zod schema
  4. endpoint:MCP端点路径(例如'/api/mcp-docs/message')

Step 3: Generate TypeScript Interfaces

步骤3:生成TypeScript接口

Convert Zod schemas to TypeScript interfaces:
typescript
// From: z.object({ name: z.string(), email: z.string().email() })
// To:
export interface CreateEnquiryInput {
  name: string;
  email: string;
}
将Zod schema转换为TypeScript接口:
typescript
// 原代码:z.object({ name: z.string(), email: z.string().email() })
// 转换后:
export interface CreateEnquiryInput {
  name: string;
  email: string;
}

Step 4: Generate Module Client

步骤4:生成模块客户端

Create a client class with methods for each tool:
typescript
// scripts/sdk/docs/client.ts
import { MCPClient, defaultClient } from '../client';
import type { CreateDocumentInput, CreateDocumentOutput } from './types';

const ENDPOINT = '/api/mcp-docs/message';

export class DocsClient {
  private mcp: MCPClient;

  constructor(client?: MCPClient) {
    this.mcp = client || defaultClient;
  }

  async createDocument(input: CreateDocumentInput): Promise<CreateDocumentOutput> {
    return this.mcp.callTool(ENDPOINT, 'create_document', input);
  }

  async listDocuments(input: ListDocumentsInput): Promise<ListDocumentsOutput> {
    return this.mcp.callTool(ENDPOINT, 'list_documents', input);
  }

  // ... one method per tool
}

export const docs = new DocsClient();
创建包含每个工具对应方法的客户端类:
typescript
// scripts/sdk/docs/client.ts
import { MCPClient, defaultClient } from '../client';
import type { CreateDocumentInput, CreateDocumentOutput } from './types';

const ENDPOINT = '/api/mcp-docs/message';

export class DocsClient {
  private mcp: MCPClient;

  constructor(client?: MCPClient) {
    this.mcp = client || defaultClient;
  }

  async createDocument(input: CreateDocumentInput): Promise<CreateDocumentOutput> {
    return this.mcp.callTool(ENDPOINT, 'create_document', input);
  }

  async listDocuments(input: ListDocumentsInput): Promise<ListDocumentsOutput> {
    return this.mcp.callTool(ENDPOINT, 'list_documents', input);
  }

  // ... 每个工具对应一个方法
}

export const docs = new DocsClient();

Step 5: Generate Example Scripts

步骤5:生成示例脚本

Create runnable examples in
scripts/sdk/examples/
:
typescript
#!/usr/bin/env npx tsx
// scripts/sdk/examples/create-doc.ts
import { docs } from '../';

async function main() {
  const result = await docs.createDocument({
    spaceId: 'wiki',
    title: 'Getting Started',
    content: '# Welcome\n\nThis is the intro.',
  });

  console.log(`Created document: ${result.document.id}`);
}

main().catch(console.error);
scripts/sdk/examples/
目录中创建可运行的示例:
typescript
#!/usr/bin/env npx tsx
// scripts/sdk/examples/create-doc.ts
import { docs } from '../';

async function main() {
  const result = await docs.createDocument({
    spaceId: 'wiki',
    title: 'Getting Started',
    content: '# Welcome\n\nThis is the intro.',
  });

  console.log(`Created document: ${result.document.id}`);
}

main().catch(console.error);

Step 6: Update Index Exports

步骤6:更新索引导出

Add module exports to
scripts/sdk/index.ts
:
typescript
export { docs } from './docs';
export { enquiries } from './enquiries';
将模块导出添加到
scripts/sdk/index.ts
typescript
export { docs } from './docs';
export { enquiries } from './enquiries';

Output Structure

输出结构

project/
└── scripts/sdk/
    ├── index.ts           # Main exports
    ├── config.ts          # Environment config
    ├── errors.ts          # Error classes
    ├── client.ts          # MCP client
    ├── docs/              # Generated module
    │   ├── types.ts       # TypeScript interfaces
    │   ├── client.ts      # Typed methods
    │   └── index.ts       # Module exports
    ├── enquiries/         # Another module
    │   ├── types.ts
    │   ├── client.ts
    │   └── index.ts
    └── examples/          # Runnable scripts
        ├── create-doc.ts
        ├── list-spaces.ts
        └── create-enquiry.ts
project/
└── scripts/sdk/
    ├── index.ts           # 主导出文件
    ├── config.ts          # 环境配置
    ├── errors.ts          # 错误类
    ├── client.ts          # MCP客户端
    ├── docs/              # 生成的模块
    │   ├── types.ts       # TypeScript接口
    │   ├── client.ts      # 类型化方法
    │   └── index.ts       # 模块导出
    ├── enquiries/         # 另一个模块
    │   ├── types.ts
    │   ├── client.ts
    │   └── index.ts
    └── examples/          # 可运行脚本
        ├── create-doc.ts
        ├── list-spaces.ts
        └── create-enquiry.ts

Environment Variables

环境变量

The SDK uses these environment variables:
VariableDescriptionDefault
SDK_MODE
Execution mode: 'local', 'remote', 'auto''auto'
SDK_BASE_URL
Target Worker URLhttp://localhost:8787
SDK_API_TOKEN
Bearer token for auth(none)
SDK使用以下环境变量:
变量名描述默认值
SDK_MODE
执行模式:'local'、'remote'、'auto''auto'
SDK_BASE_URL
目标Worker URLhttp://localhost:8787
SDK_API_TOKEN
用于认证的Bearer令牌(无)

Execution

执行方式

Run generated scripts with:
bash
SDK_API_TOKEN="your-token" SDK_BASE_URL="https://app.workers.dev" npx tsx scripts/sdk/examples/create-doc.ts
使用以下命令运行生成的脚本:
bash
SDK_API_TOKEN="your-token" SDK_BASE_URL="https://app.workers.dev" npx tsx scripts/sdk/examples/create-doc.ts

Naming Conventions

命名规范

  • Module names: Lowercase, from MCP server name (e.g., 'mcp-docs' → 'docs')
  • Method names: camelCase from tool name (e.g., 'create_document' → 'createDocument')
  • Type names: PascalCase (e.g., 'CreateDocumentInput', 'CreateDocumentOutput')
  • 模块名称:小写,源自MCP服务器名称(例如'mcp-docs' → 'docs')
  • 方法名称:由工具名称转换为小驼峰式(例如'create_document' → 'createDocument')
  • 类型名称:大驼峰式(例如'CreateDocumentInput'、'CreateDocumentOutput')

Error Handling

错误处理

The SDK provides typed errors:
  • AuthError
    - 401, invalid token
  • ValidationError
    - Invalid input
  • NotFoundError
    - Resource not found
  • RateLimitError
    - 429, too many requests
  • MCPError
    - MCP protocol errors
  • NetworkError
    - Connection failures
SDK提供类型化错误:
  • AuthError
    - 401,令牌无效
  • ValidationError
    - 输入无效
  • NotFoundError
    - 资源未找到
  • RateLimitError
    - 429,请求过于频繁
  • MCPError
    - MCP协议错误
  • NetworkError
    - 连接失败

Regeneration

重新生成

When MCP tools change, regenerate the SDK:
  1. Re-scan
    src/server/modules/mcp*/server.ts
  2. Update types.ts with new/changed schemas
  3. Update client.ts with new/changed methods
  4. Preserve any custom code in examples/
当MCP工具发生变更时,重新生成SDK的步骤:
  1. 重新扫描
    src/server/modules/mcp*/server.ts
  2. 更新types.ts中的新增/变更schema
  3. 更新client.ts中的新增/变更方法
  4. 保留examples/目录中的自定义代码