* tool() implementation. Parses arguments passed to overrides defined above.
(name: string, ...rest: unknown[])
| 991 | * tool() implementation. Parses arguments passed to overrides defined above. |
| 992 | */ |
| 993 | tool(name: string, ...rest: unknown[]): RegisteredTool { |
| 994 | if (this._registeredTools[name]) { |
| 995 | throw new Error(`Tool ${name} is already registered`); |
| 996 | } |
| 997 | |
| 998 | let description: string | undefined; |
| 999 | let inputSchema: ZodRawShapeCompat | undefined; |
| 1000 | let outputSchema: ZodRawShapeCompat | undefined; |
| 1001 | let annotations: ToolAnnotations | undefined; |
| 1002 | |
| 1003 | // Tool properties are passed as separate arguments, with omissions allowed. |
| 1004 | // Support for this style is frozen as of protocol version 2025-03-26. Future additions |
| 1005 | // to tool definition should *NOT* be added. |
| 1006 | |
| 1007 | if (typeof rest[0] === 'string') { |
| 1008 | description = rest.shift() as string; |
| 1009 | } |
| 1010 | |
| 1011 | // Handle the different overload combinations |
| 1012 | if (rest.length > 1) { |
| 1013 | // We have at least one more arg before the callback |
| 1014 | const firstArg = rest[0]; |
| 1015 | |
| 1016 | if (isZodRawShapeCompat(firstArg)) { |
| 1017 | // We have a params schema as the first arg |
| 1018 | inputSchema = rest.shift() as ZodRawShapeCompat; |
| 1019 | |
| 1020 | // Check if the next arg is potentially annotations |
| 1021 | if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { |
| 1022 | // Case: tool(name, paramsSchema, annotations, cb) |
| 1023 | // Or: tool(name, description, paramsSchema, annotations, cb) |
| 1024 | annotations = rest.shift() as ToolAnnotations; |
| 1025 | } |
| 1026 | } else if (typeof firstArg === 'object' && firstArg !== null) { |
| 1027 | // ToolAnnotations values are primitives. Nested objects indicate a misplaced schema |
| 1028 | if (Object.values(firstArg).some(v => typeof v === 'object' && v !== null)) { |
| 1029 | throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`); |
| 1030 | } |
| 1031 | annotations = rest.shift() as ToolAnnotations; |
| 1032 | } |
| 1033 | } |
| 1034 | const callback = rest[0] as ToolCallback<ZodRawShapeCompat | undefined>; |
| 1035 | |
| 1036 | return this._createRegisteredTool( |
| 1037 | name, |
| 1038 | undefined, |
| 1039 | description, |
| 1040 | inputSchema, |
| 1041 | outputSchema, |
| 1042 | annotations, |
| 1043 | { taskSupport: 'forbidden' }, |
| 1044 | undefined, |
| 1045 | callback |
| 1046 | ); |
| 1047 | } |
| 1048 | |
| 1049 | /** |
| 1050 | * Registers a tool with a config object and callback. |