示例
API 集成
在 MCP 工具中集成外部 API 并使用 Nuxt 服务器工具。
获取外部数据
这是一个从公共 API 获取数据的简单工具:
server/mcp/tools/get-weather.ts
import { z } from 'zod'
import { defineMcpTool } from '@nuxtjs/mcp-toolkit/server'
export default defineMcpTool({
description: 'Get current weather for a city',
inputSchema: {
city: z.string().describe('City name'),
},
cache: '15m',
handler: async ({ city }) => {
return await $fetch(`https://wttr.in/${city}?format=j1`)
},
})
使用 Nuxt 服务器工具
要在处理程序中使用 useEvent() 等 Nuxt 服务器工具,请启用 asyncContext:
nuxt.config.ts
export default defineNuxtConfig({
experimental: {
asyncContext: true,
},
})
然后你就可以访问 H3 事件并使用 Nuxt 服务器组合式函数:
server/mcp/tools/get-page.ts
import { z } from 'zod'
import { useEvent, createError } from 'h3'
import { queryCollection } from '@nuxt/content/server'
import { defineMcpTool } from '@nuxtjs/mcp-toolkit/server'
export default defineMcpTool({
description: 'Get a documentation page',
inputSchema: {
path: z.string().describe('Page path'),
},
cache: '1h',
handler: async ({ path }) => {
const event = useEvent()
const page = await queryCollection(event, 'docs')
.where('path', '=', path)
.first()
if (!page) throw createError({ statusCode: 404, message: 'Page not found' })
return page
},
})
启用
asyncContext 后,useEvent() 会被自动导入。后续步骤
- Common Patterns - 更多通用示例
- File Operations - 文件操作示例
- Tools - 深入了解工具