-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathBaseTool.ts
194 lines (170 loc) · 4.92 KB
/
BaseTool.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { z } from "zod";
import { Tool as SDKTool } from "@modelcontextprotocol/sdk/types.js";
import { ImageContent } from "../transports/utils/image-handler.js";
export type ToolInputSchema<T> = {
[K in keyof T]: {
type: z.ZodType<T[K]>;
description: string;
};
};
export type ToolInput<T extends ToolInputSchema<any>> = {
[K in keyof T]: z.infer<T[K]["type"]>;
};
export type TextContent = {
type: "text";
text: string;
};
export type ErrorContent = {
type: "error";
text: string;
};
export type ToolContent = TextContent | ErrorContent | ImageContent;
export type ToolResponse = {
content: ToolContent[];
};
export interface ToolProtocol extends SDKTool {
name: string;
description: string;
toolDefinition: {
name: string;
description: string;
inputSchema: {
type: "object";
properties?: Record<string, unknown>;
};
};
toolCall(request: {
params: { name: string; arguments?: Record<string, unknown> };
}): Promise<ToolResponse>;
}
export abstract class MCPTool<TInput extends Record<string, any> = {}>
implements ToolProtocol
{
abstract name: string;
abstract description: string;
protected abstract schema: ToolInputSchema<TInput>;
protected useStringify: boolean = true;
[key: string]: unknown;
get inputSchema(): { type: "object"; properties?: Record<string, unknown> } {
return {
type: "object" as const,
properties: Object.fromEntries(
Object.entries(this.schema).map(([key, schema]) => [
key,
{
type: this.getJsonSchemaType(schema.type),
description: schema.description,
},
])
),
};
}
get toolDefinition() {
return {
name: this.name,
description: this.description,
inputSchema: this.inputSchema,
};
}
protected abstract execute(input: TInput): Promise<unknown>;
async toolCall(request: {
params: { name: string; arguments?: Record<string, unknown> };
}): Promise<ToolResponse> {
try {
const args = request.params.arguments || {};
const validatedInput = await this.validateInput(args);
const result = await this.execute(validatedInput);
return this.createSuccessResponse(result);
} catch (error) {
return this.createErrorResponse(error as Error);
}
}
private async validateInput(args: Record<string, unknown>): Promise<TInput> {
const zodSchema = z.object(
Object.fromEntries(
Object.entries(this.schema).map(([key, schema]) => [key, schema.type])
)
);
return zodSchema.parse(args) as TInput;
}
private getJsonSchemaType(zodType: z.ZodType<any>): string {
if (zodType instanceof z.ZodString) return "string";
if (zodType instanceof z.ZodNumber) return "number";
if (zodType instanceof z.ZodBoolean) return "boolean";
if (zodType instanceof z.ZodArray) return "array";
if (zodType instanceof z.ZodObject) return "object";
return "string";
}
protected createSuccessResponse(data: unknown): ToolResponse {
if (this.isImageContent(data)) {
return {
content: [data],
};
}
if (Array.isArray(data)) {
const validContent = data.filter(item => this.isValidContent(item)) as ToolContent[];
if (validContent.length > 0) {
return {
content: validContent,
};
}
}
return {
content: [{
type: "text",
text: this.useStringify ? JSON.stringify(data) : String(data)
}],
};
}
protected createErrorResponse(error: Error): ToolResponse {
return {
content: [{ type: "error", text: error.message }],
};
}
private isImageContent(data: unknown): data is ImageContent {
return (
typeof data === "object" &&
data !== null &&
"type" in data &&
data.type === "image" &&
"data" in data &&
"mimeType" in data &&
typeof (data as ImageContent).data === "string" &&
typeof (data as ImageContent).mimeType === "string"
);
}
private isTextContent(data: unknown): data is TextContent {
return (
typeof data === "object" &&
data !== null &&
"type" in data &&
data.type === "text" &&
"text" in data &&
typeof (data as TextContent).text === "string"
);
}
private isErrorContent(data: unknown): data is ErrorContent {
return (
typeof data === "object" &&
data !== null &&
"type" in data &&
data.type === "error" &&
"text" in data &&
typeof (data as ErrorContent).text === "string"
);
}
private isValidContent(data: unknown): data is ToolContent {
return (
this.isImageContent(data) ||
this.isTextContent(data) ||
this.isErrorContent(data)
);
}
protected async fetch<T>(url: string, init?: RequestInit): Promise<T> {
const response = await fetch(url, init);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
}