“中國版 Muse”來了:Tego OS 讓雲端 Agent 在企業上崗
Muse 讓雲端 Agent 走到臺前。Tego OS 把數字分身帶進中國企業的真實工作:接任務、用工具、交結果,也讓關鍵操作回到人的判斷中。
本文發佈於 2024年11月19日。產品當前能力參見產品能力。
裝飾器就是魔法。
不是那種虛假的、花裡胡哨的魔法。是真正的魔法 - 複雜的操作變得簡單,冗長的代碼變得優雅,而開發變得…有趣。
當我們在 Zhama 構建 @zhama/mcp-server 時,我們只有一個目標:讓為 Claude Desktop 構建 AI 工具的感覺,不再像是與配置搏鬥,而更像是在寫詩。
答案?TypeScript 裝飾器。
讓我展示為什麼用裝飾器構建 AI 工具是擴展 Claude 能力最令人愉悅的方式。
我記得那個確切的時刻。凌晨 2 點,我正喝著第五杯咖啡,盯著 200 行 JSON Schema 定義,只是為了一個簡單的郵件工具。我的大腦快要融化了。
然後我想:“如果我可以直接…描述我想要的呢?”
@Tool({
name: 'send_email',
description: '发送邮件',
parameters: [
{ name: 'to', type: 'string', required: true },
{ name: 'subject', type: 'string', required: true },
{ name: 'body', type: 'string', required: true }
]
})
class EmailTool extends BaseTool {
async executeInternal(params) {
// 只需发送邮件
return await sendEmail(params);
}
}
**就這樣。**沒有 schema 對象。沒有處理器註冊。沒有請求路由。只有純粹的、聲明式的美。
我刪除了 180 行樣板代碼,開心地去睡覺了。
看看這個:
@Tool({
name: 'get_weather',
description: '获取任何城市的当前天气',
parameters: [
{ name: 'city', type: 'string', description: '城市名称', required: true }
]
})
**你能讀懂這個。**你不需要是 TypeScript 專家。你不需要理解 JSON Schema。你就是…理解它。
對比傳統方法:
const weatherToolSchema = {
type: 'object',
properties: {
city: {
type: 'string',
description: '城市名称'
}
},
required: ['city']
};
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [{
name: 'get_weather',
description: '获取任何城市的当前天气',
inputSchema: weatherToolSchema
}]
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'get_weather') {
// 终于,你的实际代码
}
});
**你更願意讀哪個?**更願意寫哪個?
在傳統方法中,你的工具定義散落在多個地方:
想要改變一個參數?訪問四個不同的地方。
使用裝飾器,所有東西都在一個地方:
@Tool({
name: 'search_database',
description: '在产品数据库中搜索商品',
parameters: [
{ name: 'query', type: 'string', description: '搜索查询', required: true },
{ name: 'limit', type: 'number', description: '最大结果数', required: false }
]
})
class SearchTool extends BaseTool {
protected toolDefinition = {
name: 'search_database',
description: '搜索产品',
parameters: []
};
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { query, limit = 10 } = params as { query: string; limit?: number };
// 验证
if (query.length < 2) {
throw new Error('查询必须至少 2 个字符');
}
// 执行
const results = await this.database.search(query, limit);
// 响应
return {
query,
count: results.length,
results
};
}
}
**關於這個工具的一切都在這裡。**定義、驗證、邏輯、響應。不用在文件中尋找。
裝飾器組合得很漂亮。想添加認證?日誌?速率限制?堆疊裝飾器:
@Tool({
name: 'delete_user',
description: '删除用户账户(仅管理员)',
parameters: [
{ name: 'userId', type: 'string', required: true }
]
})
@RequireAuth('admin')
@RateLimit({ maxCalls: 10, windowMs: 60000 })
@AuditLog()
class DeleteUserTool extends BaseTool {
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
// 你的逻辑 - 认证、速率限制和日志都是自动的
return await this.userService.delete(params.userId);
}
}
**每個裝飾器添加一個能力。**簡潔、模塊化、可組合。
讓我分享一些我用 @zhama/mcp-server 構建的工具,它們讓我在編碼時微笑。
@Tool({
name: 'count_users',
description: '统计数据库中的用户总数',
parameters: []
})
class CountUsersTool extends BaseTool {
protected toolDefinition = { name: 'count_users', description: '统计用户', parameters: [] };
protected async executeInternal(): Promise<unknown> {
return { count: await this.db.users.count() };
}
}
**這就是整個工具。**七行實際代碼。在 Claude 中完美工作。
對比傳統方法:60+ 行,包含 schema 定義、處理器註冊、響應格式化。
@Tool({
name: 'shorten_url',
description: '使用 bit.ly 创建短链接',
parameters: [
{ name: 'url', type: 'string', description: '要缩短的 URL', required: true }
]
})
class ShortenUrlTool extends BaseTool {
protected toolDefinition = { name: 'shorten_url', description: '缩短 URL', parameters: [] };
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { url } = params as { url: string };
const response = await fetch('https://api-ssl.bitly.com/v4/shorten', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.BITLY_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ long_url: url })
});
const data = await response.json();
return {
original: url,
shortened: data.link,
success: true
};
}
}
**優美。**裝飾器描述接口,方法實現邏輯。清晰的關注點分離。
@Tool({
name: 'register_user',
description: '注册新用户账户',
parameters: [
{ name: 'email', type: 'string', description: '用户邮箱', required: true },
{ name: 'username', type: 'string', description: '用户名', required: true },
{ name: 'password', type: 'string', description: '密码', required: true }
]
})
class RegisterUserTool extends BaseTool {
protected toolDefinition = { name: 'register_user', description: '注册用户', parameters: [] };
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { email, username, password } = params as {
email: string;
username: string;
password: string;
};
// 验证(自动错误格式化)
if (!this.isValidEmail(email)) {
throw new Error('邮箱格式无效');
}
if (username.length < 3) {
throw new Error('用户名必须至少 3 个字符');
}
if (password.length < 8) {
throw new Error('密码必须至少 8 个字符');
}
// 注册
const user = await this.userService.create({
email,
username,
passwordHash: await this.hashPassword(password)
});
return {
success: true,
userId: user.id,
message: '用户注册成功'
};
}
private isValidEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
private async hashPassword(password: string): Promise<string> {
// 密码哈希逻辑
return await bcrypt.hash(password, 10);
}
}
**一切都在它應該在的地方。**驗證邏輯和工具在一起。輔助方法是私有的。簡潔、可維護、可測試。
一旦你開始用裝飾器思考,模式就會出現。這是我的個人收藏:
@Tool({
name: 'list_files',
description: '列出目录中的文件',
parameters: [
{ name: 'path', type: 'string', description: '目录路径', required: true },
{ name: 'limit', type: 'number', description: '返回的最大文件数', required: false }
]
})
class ListFilesTool extends BaseTool {
protected toolDefinition = { name: 'list_files', description: '列出文件', parameters: [] };
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { path, limit = 100 } = params as { path: string; limit?: number };
const files = await fs.readdir(path);
return {
path,
files: files.slice(0, limit),
total: files.length,
limited: files.length > limit
};
}
}
**帶默認值的解構。**如此簡潔,如此 JavaScript。
@Tool({
name: 'convert_temperature',
description: '在单位之间转换温度',
parameters: [
{ name: 'value', type: 'number', description: '温度值', required: true },
{ name: 'from', type: 'string', description: '源单位:celsius、fahrenheit、kelvin', required: true },
{ name: 'to', type: 'string', description: '目标单位:celsius、fahrenheit、kelvin', required: true }
]
})
class ConvertTemperatureTool extends BaseTool {
protected toolDefinition = { name: 'convert_temperature', description: '转换温度', parameters: [] };
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { value, from, to } = params as {
value: number;
from: 'celsius' | 'fahrenheit' | 'kelvin';
to: 'celsius' | 'fahrenheit' | 'kelvin';
};
const conversions = {
celsius: {
fahrenheit: (v: number) => (v * 9/5) + 32,
kelvin: (v: number) => v + 273.15
},
fahrenheit: {
celsius: (v: number) => (v - 32) * 5/9,
kelvin: (v: number) => ((v - 32) * 5/9) + 273.15
},
kelvin: {
celsius: (v: number) => v - 273.15,
fahrenheit: (v: number) => ((v - 273.15) * 9/5) + 32
}
};
if (from === to) {
return { value, unit: to };
}
const convert = conversions[from]?.[to];
if (!convert) {
throw new Error(`无法从 ${from} 转换到 ${to}`);
}
return {
original: { value, unit: from },
converted: { value: convert(value), unit: to }
};
}
}
**類型安全 + 查找表。**優雅且安全。
@Tool({
name: 'process_image',
description: '下载、调整大小并上传图片',
parameters: [
{ name: 'url', type: 'string', description: '图片 URL', required: true },
{ name: 'width', type: 'number', description: '目标宽度', required: true },
{ name: 'height', type: 'number', description: '目标高度', required: true }
]
})
class ProcessImageTool extends BaseTool {
protected toolDefinition = { name: 'process_image', description: '处理图片', parameters: [] };
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { url, width, height } = params as {
url: string;
width: number;
height: number;
};
// 优雅的异步管道
const originalBuffer = await this.downloadImage(url);
const resizedBuffer = await this.resizeImage(originalBuffer, width, height);
const uploadedUrl = await this.uploadImage(resizedBuffer);
return {
original: url,
processed: uploadedUrl,
dimensions: { width, height },
success: true
};
}
private async downloadImage(url: string): Promise<Buffer> {
const response = await fetch(url);
return Buffer.from(await response.arrayBuffer());
}
private async resizeImage(buffer: Buffer, width: number, height: number): Promise<Buffer> {
// 图片处理逻辑
return buffer; // 简化版
}
private async uploadImage(buffer: Buffer): Promise<string> {
// 上传逻辑
return 'https://cdn.example.com/processed.jpg'; // 简化版
}
}
**Async/await 鏈從上到下閱讀。**沒有回調地獄,沒有 promise 鏈,只有清晰的流程。
@Tool({
name: 'charge_payment',
description: '处理支付收费',
parameters: [
{ name: 'amount', type: 'number', description: '金额(分)', required: true },
{ name: 'currency', type: 'string', description: '货币代码', required: true },
{ name: 'customerId', type: 'string', description: '客户 ID', required: true }
]
})
class ChargePaymentTool extends BaseTool {
protected toolDefinition = { name: 'charge_payment', description: '收费', parameters: [] };
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { amount, currency, customerId } = params as {
amount: number;
currency: string;
customerId: string;
};
try {
// 尝试收费
const charge = await this.stripe.charges.create({
amount,
currency,
customer: customerId
});
return {
success: true,
chargeId: charge.id,
amount,
currency
};
} catch (error) {
// 丰富的错误上下文
this.logger.error('支付失败', {
amount,
currency,
customerId,
error: error.message
});
throw new Error(
`支付失败:${error.message}。` +
`客户:${customerId},金额:${amount/100} ${currency.toUpperCase()}`
);
}
}
}
**帶上下文的錯誤處理。**當出錯時,你確切地知道發生了什麼。
一旦你熟悉了基礎知識,試試這些高級模式:
為常見模式創建自己的裝飾器:
// 用于缓存的自定义装饰器
function Cached(ttlSeconds: number) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
const cache = new Map<string, { data: any; expires: number }>();
descriptor.value = async function (...args: any[]) {
const key = JSON.stringify(args);
const cached = cache.get(key);
if (cached && cached.expires > Date.now()) {
return cached.data;
}
const result = await originalMethod.apply(this, args);
cache.set(key, {
data: result,
expires: Date.now() + (ttlSeconds * 1000)
});
return result;
};
return descriptor;
};
}
// 使用它
@Tool({
name: 'get_exchange_rate',
description: '获取货币汇率',
parameters: [
{ name: 'from', type: 'string', required: true },
{ name: 'to', type: 'string', required: true }
]
})
class ExchangeRateTool extends BaseTool {
protected toolDefinition = { name: 'get_exchange_rate', description: '获取汇率', parameters: [] };
@Cached(300) // 缓存 5 分钟
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { from, to } = params as { from: string; to: string };
const response = await fetch(`https://api.exchangerate.com/${from}/${to}`);
const data = await response.json();
return { from, to, rate: data.rate, timestamp: Date.now() };
}
}
堆疊裝飾器以獲得強大的組合:
@Tool({
name: 'admin_action',
description: '执行管理操作',
parameters: [
{ name: 'action', type: 'string', required: true },
{ name: 'target', type: 'string', required: true }
]
})
@RequireAuth('admin') // 必须是管理员
@RateLimit(5, 60000) // 每分钟最多 5 次
@AuditLog() // 记录所有操作
@Retry(3, 1000) // 重试 3 次,延迟 1 秒
class AdminActionTool extends BaseTool {
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
// 所有装饰器魔法自动发生
return await this.performAction(params);
}
}
在 Zhama,我們在多個 Claude 集成中維護 50+ 個 AI 工具。裝飾器不僅僅是好 - 它們是必不可少的。
裝飾器之前:
开发者:"能审查一下我的新工具吗?"
审查者:*滚动 150 行*
审查者:"参数验证在哪里?"
开发者:"第 87 行"
审查者:"错误处理在哪里?"
开发者:"120-145 行"
审查者:"实际逻辑在哪里?"
开发者:"60-75 行"
使用裝飾器:
开发者:"能审查一下我的新工具吗?"
审查者:*读 40 行*
审查者:"看起来不错,批准"
代碼審查時間:20 分鐘 → 5 分鐘
新開發者的第一天:
之前:
之後:
**裝飾器之前:**每 1000 行代碼 15 個 bug
**使用裝飾器:**每 1000 行代碼 3 個 bug
**Bug 減少 5 倍。**不是因為我們是更好的程序員 - 而是因為需要搞砸的代碼更少了。
讓我誠實地說:編程應該讓人感覺良好。
不是每一天都會完美,但當你在構建東西時,工具應該幫助,而不是阻礙。
裝飾器讓我開心,因為:
**那種“好得難以置信”的感覺?**是真的。@zhama/mcp-server 兌現了它。
準備好親自體驗了嗎?
npm install @zhama/mcp-server
import { createMCPServer, BaseTool, Tool } from '@zhama/mcp-server';
@Tool({
name: 'hello',
description: '向某人问好',
parameters: [
{ name: 'name', type: 'string', description: '要问候的名字', required: true }
]
})
class HelloTool extends BaseTool {
protected toolDefinition = {
name: 'hello',
description: '打招呼',
parameters: []
};
protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
const { name } = params as { name: string };
return {
greeting: `你好,${name}!👋`,
timestamp: new Date().toISOString()
};
}
}
// 创建并运行
createMCPServer('hello-server', '1.0.0')
.enableTools()
.addTool(new HelloTool())
.runStdio();
保存這個。構建它。看它工作。
當你看到 Claude 使用你的裝飾器定義的工具時,你會明白的。
使用 @zhama/mcp-server 的開發者已經構建了:
每一個都使用裝飾器。每一個開發者都喜歡它。
我們正在添加更多裝飾器功能:
裝飾器模式可以無限擴展。
當我們構建 @zhama/mcp-server 時,我們不僅想讓開發更快。我們想讓它令人愉悅。
裝飾器實現了這一點。它們轉變了:
**結果?**開發者在編寫 AI 工具時微笑。
這不是誇張。這是我們在 Zhama 的體驗和社區的反饋。
親自試試:
npm install @zhama/mcp-server
五分鐘後,你也會微笑。
由 Zhama 用 ❤️ 和裝飾器打造
訪問:
分享你的裝飾器驅動工具!標記我們或在 GitHub 上開啟討論 - 我們很想看到你構建的東西!
Muse 讓雲端 Agent 走到臺前。Tego OS 把數字分身帶進中國企業的真實工作:接任務、用工具、交結果,也讓關鍵操作回到人的判斷中。
Tego OS v3.0.0 在桌面端做了三件事:常駐置頂的 Mini Chat 浮窗、統一的下載中心、Windows NSIS 安裝器全面重寫。本文聚焦體驗細節,解釋這套組合是怎麼把數字分身真正「裝進每天的工作流」的。
Tego OS v3.0.0 一次性補齊了 16 個 Tego 系列模板技能,覆蓋 IT 運維與跨境電商兩條最高頻的產業鏈路。每個技能都附帶可執行 bash 腳本,不是「提示詞模板」,而是真正能跑——本文系統介紹這 16 個技能、對應業務流程,以及與 per_user / 模板治理 / BusinessMonitor 是怎麼聯動的。