ts-agent-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesets-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 directory as a starting point:
scripts/sdk/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.tsEach 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:
- name: The tool identifier (e.g., 'create_document')
- description: Tool description for JSDoc
- inputSchema: Zod schema defining input parameters
- endpoint: The MCP endpoint path (e.g., '/api/mcp-docs/message')
针对每个工具,提取以下内容:
- name:工具标识符(例如'create_document')
- description:用于JSDoc的工具描述
- inputSchema:定义输入参数的Zod schema
- 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.tstypescript
export { docs } from './docs';
export { enquiries } from './enquiries';将模块导出添加到:
scripts/sdk/index.tstypescript
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.tsproject/
└── 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.tsEnvironment Variables
环境变量
The SDK uses these environment variables:
| Variable | Description | Default |
|---|---|---|
| Execution mode: 'local', 'remote', 'auto' | 'auto' |
| Target Worker URL | http://localhost:8787 |
| Bearer token for auth | (none) |
SDK使用以下环境变量:
| 变量名 | 描述 | 默认值 |
|---|---|---|
| 执行模式:'local'、'remote'、'auto' | 'auto' |
| 目标Worker URL | http://localhost:8787 |
| 用于认证的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.tsNaming 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:
- - 401, invalid token
AuthError - - Invalid input
ValidationError - - Resource not found
NotFoundError - - 429, too many requests
RateLimitError - - MCP protocol errors
MCPError - - Connection failures
NetworkError
SDK提供类型化错误:
- - 401,令牌无效
AuthError - - 输入无效
ValidationError - - 资源未找到
NotFoundError - - 429,请求过于频繁
RateLimitError - - MCP协议错误
MCPError - - 连接失败
NetworkError
Regeneration
重新生成
When MCP tools change, regenerate the SDK:
- Re-scan
src/server/modules/mcp*/server.ts - Update types.ts with new/changed schemas
- Update client.ts with new/changed methods
- Preserve any custom code in examples/
当MCP工具发生变更时,重新生成SDK的步骤:
- 重新扫描
src/server/modules/mcp*/server.ts - 更新types.ts中的新增/变更schema
- 更新client.ts中的新增/变更方法
- 保留examples/目录中的自定义代码