MCP到TypeScript
  
一个库,用于将JSON模式转换为TypeScript类型,并在沙盒环境中使用工具访问执行LLM生成的代码。
特性
- JSON 模式→ TypeScript转译器:使用中间AST将JSON模式转换为干净、可读的TypeScript类型定义
- 代码执行沙盒:使AI代理能够在安全沙箱中使用工具执行代码
- Composio集成:通过Composio工具包无缝连接到外部服务
安装
bun install要求:
- 包子 1.0+
- TypeScript 5+
快速开始
模式转换器
将JSON模式转换为TypeScript类型:
import { convert } from "mcp-to-typescript";
const userSchema = {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
email: { type: "string" },
age: { type: "number" },
},
required: ["id", "name", "email"],
};
console.log(convert(userSchema, "User"));
// Output:
// export type User = {
// id: number;
// name: string;
// email: string;
// age?: number;
// };代码执行代理
创建一个可以使用自定义工具执行代码的AI代理:
import { generateText } from "ai";
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
import { createCodeExecutionTool, type Tool } from "mcp-to-typescript";
const openrouter = createOpenRouter({
apiKey: process.env.OPENROUTER_API_KEY,
});
// Define custom tools
const tools: Tool[] = [
{
name: "calculate",
description: "Performs mathematical calculations",
parameters: {
type: "object",
properties: {
expression: { type: "string", description: "Math expression to evaluate" },
},
required: ["expression"],
},
execute: (args: { expression: string }) => {
const result = new Function(`return ${args.expression}`)();
return { result };
},
},
{
name: "getCurrentTime",
description: "Gets the current date and time",
parameters: {
type: "object",
properties: {
format: { type: "string", enum: ["iso", "unix", "human"] },
},
},
execute: (args: { format?: string }) => {
const now = new Date();
if (args.format === "unix") return { timestamp: Math.floor(now.getTime() / 1000) };
if (args.format === "human") return { time: now.toLocaleString() };
return { time: now.toISOString() };
},
},
];
const executeCode = createCodeExecutionTool(tools);
const result = await generateText({
model: openrouter.chat("anthropic/claude-sonnet-4"),
messages: [{ role: "user", content: "What is 42 * 1337? Also, what time is it?" }],
tools: { executeCode },
maxSteps: 5,
});
console.log(result.text);api参考
模式模块
convert(schema, typeName?): string
将JSON模式转换为TypeScript代码的简化函数。
import { convert } from "mcp-to-typescript";
const code = convert({ type: "string" }, "MyString");
// => "export type MyString = string;"jsonSchemaToTypeScript(schema, options?): ConversionResult
具有选项的完整转换功能。
import { jsonSchemaToTypeScript } from "mcp-to-typescript";
// Get TypeScript code
const { code } = jsonSchemaToTypeScript(schema, { typeName: "User" });
// Get the intermediate AST
const { ast } = jsonSchemaToTypeScript(schema, { returnAST: true });选项:
typeName?: string-生成类型的名称returnAST?: boolean-返回AST而不是代码
parseSchema(schema): ASTNode
将JSON模式解析为中间AST。
generateTypeScript(ast, options?): string
从AST节点生成TypeScript代码。
代理模块
createCodeExecutionTool(tools, options?)
创建一个AI SDK工具,该工具通过访问提供的工具来执行代码。
import { createCodeExecutionTool } from "mcp-to-typescript";
const executeCode = createCodeExecutionTool(tools, {
timeout: 30000, // 30 seconds
});Tool 接口
interface Tool {
name: string;
description: string;
parameters: {
type: "object";
properties: Record;
required?: string[];
};
execute: (args: any) => any | Promise;
}generateToolTypes(tools): string
从工具生成TypeScript函数签名(内部用于LLM提示)。
generateToolSummary(tools): string
生成可用工具的简要摘要。
适配器
getComposioTools(options): Promise
从Composio获取工具。
import { getComposioTools } from "mcp-to-typescript";
const tools = await getComposioTools({
toolkits: ["GOOGLESHEETS", "SLACK"],
userId: "your-composio-user-id",
});listComposioToolkits(): Promise
列出可用的Composio工具包。
支持的JSON模式关键字
| 类别 | 关键字 | TypeScript输出 | ||
|---|---|---|---|---|
| 原语 | string, number, integer, boolean, null | string, number, number, boolean, null | ||
| 对象 | type: "object", properties, required | { prop: T; optionalProp?: T; } | ||
| 附加属性 | additionalProperties | { [key: string]: T } 或 never | ||
| 数组 | type: "array", items (对象) | T[] | ||
| 元组 | items (数组) | [T1, T2, T3] | ||
| 枚举 | enum, const | `"a" \ | "b" \ | "c"`,文字类型 |
| 工会 | oneOf, anyOf, type: [...] | `T1 \ | T2 \ | T3` |
| 交点 | allOf | T1 & T2 & T3 | ||
| 可空 | type: ["string", "null"] | `string \ | null` |
例子
请参阅 example/ 完整工作示例目录:
transpiler.ts-JSON模式到TypeScript转换示例agent-custom.ts-使用自定义工具执行代码agent-composio.ts-使用Composio集成执行代码
使用以下命令运行示例:
bun run example/transpiler.ts
bun run example/agent-custom.ts
bun run example/agent-composio.ts发展
# Install dependencies
bun install
# Run tests
bun test
# Run tests in watch mode
bun test --watch
# Type check
bun run typecheck参考文献
作者
- 朱利安·阿奇拉
- 圣地亚哥博特罗
许可证
麻省理工学院
