资源

模板与处理程序

ResourceTemplate URI、变量和资源处理程序函数。

使用模板的动态资源

使用 ResourceTemplate 创建接受变量的动态资源:

server/mcp/resources/file.ts
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { Variables } from '@modelcontextprotocol/sdk/shared/uriTemplate.js'
import { defineMcpResource } from '@nuxtjs/mcp-toolkit/server'

export default defineMcpResource({
  name: 'file',
  title: '文件资源',
  uri: new ResourceTemplate('file:///project/{+path}', {
    list: async () => {
      // 返回可用资源列表
      return {
        resources: [
          { uri: 'file:///project/README.md', name: 'README.md' },
          { uri: 'file:///project/src/index.ts', name: 'src/index.ts' },
        ],
      }
    },
  }),
  handler: async (uri: URL, variables: Variables) => {
    const path = variables.path as string
    const filePath = join(process.cwd(), path)
    const content = await readFile(filePath, 'utf-8')

    return {
      contents: [{
        uri: uri.toString(),
        mimeType: 'text/plain',
        text: content,
      }],
    }
  },
})

ResourceTemplate

ResourceTemplate 允许你创建 URI 中包含可变部分的资源:

new ResourceTemplate('file:///project/{+path}', {
  list: async () => {
    // 可选:返回可用资源列表
    return {
      resources: [
        { uri: 'file:///project/file1.txt', name: '文件 1' },
        { uri: 'file:///project/file2.txt', name: '文件 2' },
      ],
    }
  },
})

模板变量

URI 中的变量使用 {variableName} 定义:

// 单个变量
new ResourceTemplate('file:///project/{path}', { ... })

// 允许斜杠的变量(保留扩展)
new ResourceTemplate('file:///project/{+path}', { ... })

// 多个变量
new ResourceTemplate('api://users/{userId}/posts/{postId}', { ... })

处理程序函数

处理程序接收解析后的 URI 和可选变量:

// 静态资源处理程序
handler: async (uri: URL) => {
  return {
    contents: [{
      uri: uri.toString(),
      mimeType: 'text/plain',
      text: 'Content',
    }],
  }
}

// 动态资源处理程序
handler: async (uri: URL, variables: Variables) => {
  const path = variables.path as string
  // 使用变量来解析资源
  return {
    contents: [{
      uri: uri.toString(),
      mimeType: 'text/plain',
      text: 'Content',
    }],
  }
}