Chuyển tới nội dung chính

callTool

callTool là JS API dùng để gọi một MCP tool từ bên trong AI App tới MCP server tương ứng.

Import

import apis from '@v-miniapp/ai/apis'

Tham số

Thuộc tínhKiểu dữ liệuBắt buộcMô tả
namestringTên của MCP tool cần gọi
argsRecord<string, unknown>Tham số truyền vào tool (mặc định: {})
success(res: CallToolResult) => voidCallback khi gọi tool thành công
fail(error) => voidCallback khi thất bại
complete() => voidCallback khi hoàn tất (dù thành công hay thất bại)

Giá trị trả về

  • CallToolResult: Kết quả trả về từ MCP tool.
interface CallToolResult {
/** Nội dung trả về dạng text hoặc image */
content: Array<
| { type: 'text'; text: string }
| { type: 'image'; data: string; mimeType: string }
>
/** Dữ liệu có cấu trúc (structured output) nếu tool hỗ trợ */
structuredContent?: Record<string, unknown>
/** `true` nếu tool thực thi thất bại */
isError?: boolean
}

Ví dụ

Callback

import apis from '@v-miniapp/ai/apis'

apis.callTool({
name: 'get_weather',
args: { city: 'Hanoi' },
success: (res) => {
if (res.isError) {
console.error('Tool báo lỗi')
return
}
// Đọc nội dung text từ kết quả
const text = res.content.find((c) => c.type === 'text')?.text
console.log('Kết quả:', text)

// Hoặc đọc structured output
console.log('Structured:', res.structuredContent)
},
fail: (err) => {
console.error('Lỗi', err)
},
})

Async/Await

import { apisAsync } from '@v-miniapp/ai/apis'

try {
const res = await apisAsync.callToolAsync('get_weather', { city: 'Hanoi' })

const text = res.content.find((c) => c.type === 'text')?.text
console.log('Kết quả:', text)
} catch (err) {
console.error('Lỗi', err)
}